comment fixes
[civicrm-core.git] / CRM / Upgrade / Incremental / php / FourThree.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
6a488035
TO
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 |
c73475ea 12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
6a488035
TO
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 |
c73475ea
WA
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
bf6a5362 29 * Upgrade logic for 4.3
6a488035 30 */
bf6a5362 31class CRM_Upgrade_Incremental_php_FourThree extends CRM_Upgrade_Incremental_Base {
6a488035 32
505cf9f9 33 /**
fe482240 34 * Compute any messages which should be displayed beforeupgrade.
505cf9f9
PJ
35 *
36 * Note: This function is called iteratively for each upcoming
37 * revision to the database.
38 *
3bdf1f3a 39 * @param string $preUpgradeMessage
5a4f6742
CW
40 * @param string $rev
41 * a version number, e.g. '4.3.alpha1', '4.3.beta3', '4.3.0'.
77b97be7
EM
42 * @param null $currentVer
43 *
3bdf1f3a 44 * @return bool
505cf9f9 45 */
00be9182 46 public function setPreUpgradeMessage(&$preUpgradeMessage, $rev, $currentVer = NULL) {
7402727c 47 if ($rev == '4.3.beta3') {
505cf9f9
PJ
48 //CRM-12084
49 //sql for checking orphaned contribution records
50 $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";
51 $count = CRM_Core_DAO::singleValueQuery($sql, array(), TRUE, FALSE);
52
53 if ($count > 0) {
33421d01 54 $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(
353ffa53
TO
55 1 => $count,
56 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>',
57 ));
505cf9f9
PJ
58 CRM_Core_Error::fatal($error);
59 return FALSE;
60 }
61 }
de65d43e 62 if ($rev == '4.3.beta4' && CRM_Utils_Constant::value('CIVICRM_UF', FALSE) == 'Drupal6') {
70ec93e4
CB
63 // CRM-11823 - Make sure the D6 HTML HEAD technique will work on
64 // upgrade pages ... except when we're in Drush.
65 if (!function_exists('drush_main')) {
66 theme('item_list', array()); // force-load theme registry
67 $theme_registry = theme_get_registry();
68 if (!isset($theme_registry['page']['preprocess functions']) || FALSE === array_search('civicrm_preprocess_page_inject', $theme_registry['page']['preprocess functions'])) {
69 CRM_Core_Error::fatal('Please reset the Drupal cache (Administer => Site Configuration => Performance => Clear cached data))');
70 }
de65d43e
TO
71 }
72 }
77b97be7 73
ce4b9629
CW
74 if ($rev == '4.3.6') {
75 $constraintArray = array(
76 'civicrm_contact' => 'contact_id',
77b97be7 77 'civicrm_payment_processor' => 'payment_processor_id',
ce4b9629 78 );
77b97be7
EM
79
80 if (version_compare('4.1alpha1', $currentVer) <= 0) {
9e1a3f4f
PN
81 $constraintArray['civicrm_campaign'] = 'campaign_id';
82 }
77b97be7
EM
83
84 if (version_compare('4.3alpha1', $currentVer) <= 0) {
9e1a3f4f
PN
85 $constraintArray['civicrm_financial_type'] = 'financial_type_id';
86 }
77b97be7 87
ce4b9629
CW
88 foreach ($constraintArray as $key => $value) {
89 $query = "SELECT contri_recur.id FROM civicrm_contribution_recur contri_recur LEFT JOIN {$key} ON contri_recur.{$value} = {$key}.id
90WHERE {$key}.id IS NULL";
133b8445
PN
91 if ($value != 'contact_id') {
92 $query .= " AND contri_recur.{$value} IS NOT NULL ";
ce4b9629
CW
93 }
94 $dao = CRM_Core_DAO::executeQuery($query);
95 if ($dao->N) {
050743aa 96 $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
97 CRM_Core_Error::fatal($invalidDataMessage);
98 return FALSE;
99 }
100 }
101 }
505cf9f9
PJ
102 }
103
6a488035 104 /**
fe482240 105 * Compute any messages which should be displayed after upgrade.
6a488035 106 *
5a4f6742
CW
107 * @param string $postUpgradeMessage
108 * alterable.
109 * @param string $rev
110 * an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs.
6a488035
TO
111 * @return void
112 */
00be9182 113 public function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
6a488035
TO
114 if ($rev == '4.3.alpha1') {
115 // check if CiviMember component is enabled
116 $config = CRM_Core_Config::singleton();
117 if (in_array('CiviMember', $config->enableComponents)) {
118 $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.');
119 $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.');
120 }
c28241be 121
6a488035 122 //CRM-11636
c28241be 123 //here we do the financial type check and migration
6a488035 124 $isDefaultsModified = self::_checkAndMigrateDefaultFinancialTypes();
22e263ad 125 if ($isDefaultsModified) {
6a488035 126 $postUpgradeMessage .= '<br />' . ts('Please review all price set financial type assignments.');
c28241be 127 }
6a488035
TO
128 list($context, $orgName) = self::createDomainContacts();
129 if ($context == 'added') {
10a5be27 130 $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
131 }
132 elseif ($context == 'merged') {
10a5be27 133 $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 134 }
24571eea
DS
135
136 $providerExists = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_sms_provider LIMIT 1");
137 if ($providerExists) {
138 $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'));
139 }
6a488035
TO
140 }
141
142 if ($rev == '4.3.alpha2') {
143 $sql = "
144SELECT title, id
145FROM civicrm_action_schedule
146WHERE entity_value = '' OR entity_value IS NULL
147";
c28241be 148
6a488035
TO
149 $dao = CRM_Core_DAO::executeQuery($sql);
150 $reminder = array();
151 $list = '';
152 while ($dao->fetch()) {
33421d01
TO
153 $reminder[$dao->id] = $dao->title;
154 $list .= "<li>{$dao->title}</li>";
6a488035 155 }
c28241be 156 if (!empty($reminder)) {
6a488035 157 $list = "<br /><ul>" . $list . "</ul>";
33421d01 158 $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));
6a488035
TO
159 }
160 }
2cf0e58d 161 if ($rev == '4.3.beta2') {
6a488035
TO
162 $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).');
163 }
e3a96c9b
DG
164
165 if ($rev == '4.3.beta5') {
166 $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.");
167
168 // CRM-12155
22bf3365
DL
169 $query = "
170SELECT ceft.id FROM `civicrm_financial_trxn` cft
171LEFT JOIN civicrm_entity_financial_trxn ceft
172 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
173LEFT JOIN civicrm_contribution cc
174 ON cc.id = ceft.entity_id AND ceft.entity_table = 'civicrm_contribution'
175WHERE cc.id IS NULL
176";
e3a96c9b
DG
177
178 $dao = CRM_Core_DAO::executeQuery($query);
179 $isOrphanData = TRUE;
180 if (!$dao->N) {
22bf3365
DL
181 $query = "
182SELECT cli.id FROM civicrm_line_item cli
e3a96c9b
DG
183LEFT JOIN civicrm_contribution cc ON cli.entity_id = cc.id AND cli.entity_table = 'civicrm_contribution'
184LEFT JOIN civicrm_participant cp ON cli.entity_id = cp.id AND cli.entity_table = 'civicrm_participant'
185WHERE CASE WHEN cli.entity_table = 'civicrm_contribution'
22bf3365
DL
186 THEN cc.id IS NULL
187 ELSE cp.id IS NULL
188END
189";
e3a96c9b 190 $dao = CRM_Core_DAO::executeQuery($query);
22bf3365 191 if (!$dao->N) {
e3a96c9b
DG
192 $revPattern = '/^((\d{1,2})\.\d{1,2})\.(\d{1,2}|\w{4,7})?$/i';
193 preg_match($revPattern, $currentVer, $version);
194 if ($version[1] >= 4.3) {
22bf3365
DL
195 $query = "
196SELECT cfi.id
197FROM civicrm_financial_item cfi
e3a96c9b 198LEFT JOIN civicrm_entity_financial_trxn ceft ON ceft.entity_table = 'civicrm_financial_item' and cfi.id = ceft.entity_id
22bf3365
DL
199WHERE ceft.entity_id IS NULL;
200";
e3a96c9b 201 $dao = CRM_Core_DAO::executeQuery($query);
22bf3365 202 if (!$dao->N) {
e3a96c9b
DG
203 $isOrphanData = FALSE;
204 }
205 }
206 else {
22bf3365 207 $isOrphanData = FALSE;
e3a96c9b
DG
208 }
209 }
210 }
211
212 if ($isOrphanData) {
56181f67 213 $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>.
481a74f4 214 ', array(1 => 'http://wiki.civicrm.org/confluence/display/CRMDOC/Clean+up+extraneous+financial+data+-+4.3+upgrades')) . "</strong>";
e3a96c9b
DG
215 }
216 }
56181f67
DG
217 if ($rev == '4.3.4') {
218 $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>).',
33421d01 219 array(1 => 'http://wiki.civicrm.org/confluence/display/CRMDOC/Managing+Scheduled+Jobs'));
56181f67 220 }
5d9ebb64
PJ
221 if ($rev == '4.3.5') {
222 $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).');
223 }
b9810330
DG
224 if ($rev == '4.3.6') {
225 $flag = CRM_Core_DAO::singleValueQuery('SELECT count(ccp.id) FROM civicrm_contribution_product ccp
226INNER JOIN civicrm_product cp ON ccp.product_id = cp.id
227WHERE ccp.financial_type_id IS NULL and cp.cost > 0');
228 if ($flag) {
229 $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>',
33421d01 230 array(1 => 'http://wiki.civicrm.org/confluence/display/CRMDOC/Fixing+Issues+Caused+by+Missing+Cost+of+Goods+Account+-+4.3+Upgrades'));
b9810330
DG
231 }
232 }
6a488035
TO
233 }
234
624e56fa
EM
235 /**
236 * @param $rev
237 *
238 * @return bool
239 */
00be9182 240 public function upgrade_4_3_alpha1($rev) {
6a488035 241 self::task_4_3_alpha1_checkDBConstraints();
c28241be 242
b676923b
PN
243 // add indexes for civicrm_entity_financial_trxn
244 // CRM-12141
d1401e86 245 $this->addTask('Check/Add indexes for civicrm_entity_financial_trxn', 'task_4_3_x_checkIndexes', $rev);
6a488035 246 // task to process sql
bf6a5362 247 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.alpha1')), 'runSql', $rev);
c28241be 248
6a488035 249 //CRM-11636
d1401e86 250 $this->addTask('Populate financial type values for price records', 'assignFinancialTypeToPriceRecords');
6a488035 251 //CRM-11514 create financial records for contributions
d1401e86 252 $this->addTask('Create financial records for contributions', 'createFinancialRecords');
c28241be 253
6a488035
TO
254 $minId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(min(id),0) FROM civicrm_contact');
255 $maxId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(max(id),0) FROM civicrm_contact');
256 for ($startId = $minId; $startId <= $maxId; $startId += self::BATCH_SIZE) {
257 $endId = $startId + self::BATCH_SIZE - 1;
10a5be27 258 $title = ts('Upgrade timestamps (%1 => %2)', array(1 => $startId, 2 => $endId));
6a488035
TO
259 $this->addTask($title, 'convertTimestamps', $startId, $endId);
260 }
261
262 // CRM-10893
263 // fix WP access control
481a74f4 264 $config = CRM_Core_Config::singleton();
6a488035 265 if ($config->userFramework == 'WordPress') {
481a74f4 266 civicrm_wp_set_capabilities();
6a488035
TO
267 }
268
269 // Update phones CRM-11292.
d1401e86 270 $this->addTask('Upgrade Phone Numbers', 'phoneNumeric');
c28241be 271
6a488035
TO
272 return TRUE;
273 }
274
624e56fa
EM
275 /**
276 * @param $rev
277 */
00be9182 278 public function upgrade_4_3_alpha2($rev) {
6a488035
TO
279 //CRM-11847
280 $isColumnPresent = CRM_Core_DAO::checkFieldExists('civicrm_dedupe_rule_group', 'is_default');
281 if ($isColumnPresent) {
282 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_dedupe_rule_group DROP COLUMN is_default');
283 }
bf6a5362 284 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.alpha2')), 'runSql', $rev);
6a488035
TO
285 }
286
624e56fa
EM
287 /**
288 * @param $rev
289 */
00be9182 290 public function upgrade_4_3_alpha3($rev) {
bf6a5362 291 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.alpha3')), 'runSql', $rev);
6a488035
TO
292 }
293
624e56fa
EM
294 /**
295 * @param $rev
296 */
00be9182 297 public function upgrade_4_3_beta2($rev) {
bf6a5362 298 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.beta2')), 'runSql', $rev);
ab00f69d 299
c28241be
DL
300 // CRM-12002
301 if (
302 CRM_Core_DAO::checkTableExists('log_civicrm_line_item') &&
303 CRM_Core_DAO::checkFieldExists('log_civicrm_line_item', 'label')
304 ) {
305 CRM_Core_DAO::executeQuery('ALTER TABLE `log_civicrm_line_item` CHANGE `label` `label` VARCHAR(255) NULL DEFAULT NULL');
306 }
307 }
308
624e56fa
EM
309 /**
310 * @param $rev
311 */
00be9182 312 public function upgrade_4_3_beta3($rev) {
bf6a5362 313 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.beta3')), 'runSql', $rev);
d20145bc
PN
314 // CRM-12065
315 $query = "SELECT id, form_values FROM civicrm_report_instance WHERE form_values LIKE '%contribution_type%'";
316 $this->addTask('Replace contribution_type to financial_type in table civicrm_report_instance', 'replaceContributionTypeId', $query, 'reportInstance');
317 $query = "SELECT * FROM civicrm_saved_search WHERE form_values LIKE '%contribution_type%'";
318 $this->addTask('Replace contribution_type to financial_type in table civicrm_saved_search', 'replaceContributionTypeId', $query, 'savedSearch');
319 }
558ccc27 320
624e56fa
EM
321 /**
322 * @param $rev
323 */
00be9182 324 public function upgrade_4_3_beta4($rev) {
bf6a5362 325 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.beta4')), 'runSql', $rev);
b676923b
PN
326 // add indexes for civicrm_entity_financial_trxn
327 // CRM-12141
d1401e86 328 $this->addTask('Check/Add indexes for civicrm_entity_financial_trxn', 'task_4_3_x_checkIndexes', $rev);
558ccc27
DL
329 }
330
624e56fa
EM
331 /**
332 * @param $rev
333 */
00be9182 334 public function upgrade_4_3_beta5($rev) {
ab00f69d
DL
335 // CRM-12205
336 if (
337 CRM_Core_DAO::checkTableExists('log_civicrm_financial_trxn') &&
338 CRM_Core_DAO::checkFieldExists('log_civicrm_financial_trxn', 'trxn_id')
339 ) {
340 CRM_Core_DAO::executeQuery('ALTER TABLE `log_civicrm_financial_trxn` CHANGE `trxn_id` `trxn_id` VARCHAR(255) NULL DEFAULT NULL');
341 }
35fe5ae1 342 // 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
343 // CRM-12367 - add this column to single lingual sites only
344 $upgrade = new CRM_Upgrade_Form();
345 if (!$upgrade->multilingual &&
35fe5ae1
DG
346 !CRM_Core_DAO::checkFieldExists('civicrm_premiums', 'premiums_nothankyou_label')
347 ) {
22bf3365
DL
348 $query = "
349ALTER TABLE civicrm_premiums
350ADD COLUMN premiums_nothankyou_label varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL
351 COMMENT 'Label displayed for No Thank-you option in premiums block (e.g. No thank you)'
352";
be996105 353 CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
22bf3365 354 }
bf6a5362 355 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.beta5')), 'runSql', $rev);
ab00f69d
DL
356 }
357
624e56fa
EM
358 /**
359 * @param $rev
360 */
00be9182 361 public function upgrade_4_3_4($rev) {
bf6a5362 362 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.4')), 'runSql', $rev);
56181f67 363 }
2efcf0c2 364
624e56fa
EM
365 /**
366 * @param $rev
367 */
00be9182 368 public function upgrade_4_3_5($rev) {
d2e8983d
PN
369 // CRM-12156
370 $config = CRM_Core_Config::singleton();
33421d01 371 $dbname = DB::parseDSN($config->dsn);
d2e8983d
PN
372 $sql = "SELECT DELETE_RULE
373FROM information_schema.REFERENTIAL_CONSTRAINTS
374WHERE CONSTRAINT_NAME = 'FK_civicrm_financial_item_contact_id'
375AND CONSTRAINT_SCHEMA = %1";
376 $params = array(1 => array($dbname['database'], 'String'));
377 $onDelete = CRM_Core_DAO::singleValueQuery($sql, $params, TRUE, FALSE);
2efcf0c2 378
d2e8983d
PN
379 if ($onDelete != 'CASCADE') {
380 $query = "ALTER TABLE `civicrm_financial_item`
381DROP FOREIGN KEY FK_civicrm_financial_item_contact_id,
382DROP INDEX FK_civicrm_financial_item_contact_id;";
383 CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
384 $query = "
385ALTER TABLE `civicrm_financial_item`
386ADD CONSTRAINT `FK_civicrm_financial_item_contact_id` FOREIGN KEY (`contact_id`) REFERENCES `civicrm_contact` (`id`) ON DELETE CASCADE;
387";
388 CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
389 }
bf6a5362 390 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.5')), 'runSql', $rev);
d2e8983d 391 }
56181f67 392
624e56fa
EM
393 /**
394 * @param $rev
395 */
00be9182 396 public function upgrade_4_3_6($rev) {
5beb1de0 397 //CRM-13094
0947d54d 398 $this->addTask(ts('Add missing constraints'), 'addMissingConstraints', $rev);
bdbf899f 399 //CRM-13088
d1401e86 400 $this->addTask('Add ON DELETE Options for constraints', 'task_4_3_x_checkConstraints', $rev);
bf6a5362 401 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.6')), 'runSql', $rev);
bf45dbe8
PN
402 // CRM-12844
403 // update line_item, financial_trxn and financial_item table for recurring contributions
d1401e86
ML
404 $this->addTask('Update financial_account_id in financial_trxn table', 'updateFinancialTrxnData', $rev);
405 $this->addTask('Update Line Item Data', 'updateLineItemData', $rev);
bf45dbe8 406 }
77b97be7 407
624e56fa 408 /**
4f1f1f2a 409 * CRM-11636
624e56fa
EM
410 * @return bool
411 */
00be9182 412 public function assignFinancialTypeToPriceRecords() {
6a488035
TO
413 $upgrade = new CRM_Upgrade_Form();
414 //here we update price set entries
22bf3365 415 $sqlFinancialIds = "
abe9581c 416SELECT id, LCASE(name) name
22bf3365
DL
417FROM civicrm_financial_type
418WHERE name IN ('Donation', 'Event Fee', 'Member Dues');
419";
6a488035 420 $daoFinancialIds = CRM_Core_DAO::executeQuery($sqlFinancialIds);
22e263ad 421 while ($daoFinancialIds->fetch()) {
6a488035
TO
422 $financialIds[$daoFinancialIds->name] = $daoFinancialIds->id;
423 }
22bf3365
DL
424 $sqlPriceSetUpdate = "
425UPDATE civicrm_price_set ps
426SET ps.financial_type_id =
427 CASE
abe9581c
PN
428 WHEN ps.extends LIKE '%1%' THEN {$financialIds['event fee']}
429 WHEN ps.extends LIKE '2' THEN {$financialIds['donation']}
430 WHEN ps.extends LIKE '3' THEN {$financialIds['member dues']}
6a488035 431 END
22bf3365
DL
432WHERE financial_type_id IS NULL
433";
6a488035
TO
434 CRM_Core_DAO::executeQuery($sqlPriceSetUpdate);
435
436 //here we update price field value rows
22bf3365
DL
437 $sqlPriceFieldValueUpdate = "
438UPDATE civicrm_price_field_value pfv
439LEFT JOIN civicrm_membership_type mt ON (pfv.membership_type_id = mt.id)
440INNER JOIN civicrm_price_field pf ON (pfv.price_field_id = pf.id)
441INNER JOIN civicrm_price_set ps ON (pf.price_set_id = ps.id)
442 SET pfv.financial_type_id =
443 CASE
444 WHEN pfv.membership_type_id IS NOT NULL THEN mt.financial_type_id
445 WHEN pfv.membership_type_id IS NULL THEN ps.financial_type_id
446 END
447";
6a488035 448 CRM_Core_DAO::executeQuery($sqlPriceFieldValueUpdate);
c28241be 449
6a488035
TO
450 return TRUE;
451 }
c28241be 452
624e56fa
EM
453 /**
454 * @return bool
455 */
00be9182 456 public static function _checkAndMigrateDefaultFinancialTypes() {
6a488035
TO
457 $modifiedDefaults = FALSE;
458 //insert types if not exists
22bf3365
DL
459 $sqlFetchTypes = "
460SELECT id, name
461FROM civicrm_contribution_type
462WHERE name IN ('Donation', 'Event Fee', 'Member Dues') AND is_active =1
463";
6a488035
TO
464 $daoFetchTypes = CRM_Core_DAO::executeQuery($sqlFetchTypes);
465
466 if ($daoFetchTypes->N < 3) {
467 $modifiedDefaults = TRUE;
def009f6 468 $insertStatments = array(
6a488035
TO
469 'Donation' => "('Donation', 0, 1, 1)",
470 'Member' => "('Member Dues', 0, 1, 1)",
471 'Event Fee' => "('Event Fee', 0, 1, 0)",
472 );
473 foreach ($insertStatments as $values) {
22bf3365
DL
474 $query = "
475INSERT INTO civicrm_contribution_type (name, is_reserved, is_active, is_deductible)
476VALUES $values
477ON DUPLICATE KEY UPDATE is_active = 1
478";
6a488035 479 CRM_Core_DAO::executeQuery($query);
c28241be 480 }
6a488035
TO
481 }
482 return $modifiedDefaults;
483 }
c28241be 484
624e56fa
EM
485 /**
486 * @return bool
487 */
00be9182 488 public function createFinancialRecords() {
6a488035
TO
489 $upgrade = new CRM_Upgrade_Form();
490
491 // update civicrm_entity_financial_trxn.amount = civicrm_financial_trxn.total_amount
22bf3365
DL
492 $query = "
493UPDATE civicrm_entity_financial_trxn ceft
494LEFT JOIN civicrm_financial_trxn cft ON cft.id = ceft.financial_trxn_id
495SET ceft.amount = total_amount
496WHERE cft.net_amount IS NOT NULL
497AND ceft.entity_table = 'civicrm_contribution'
498";
6a488035 499 CRM_Core_DAO::executeQuery($query);
c28241be 500
6a488035
TO
501 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
502 $completedStatus = array_search('Completed', $contributionStatus);
503 $pendingStatus = array_search('Pending', $contributionStatus);
504 $cancelledStatus = array_search('Cancelled', $contributionStatus);
505 $queryParams = array(
506 1 => array($completedStatus, 'Integer'),
507 2 => array($pendingStatus, 'Integer'),
21dfd5f5 508 3 => array($cancelledStatus, 'Integer'),
6a488035 509 );
c28241be 510
f743a6eb 511 $accountType = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name = 'Asset' "));
909a777b 512 $query = "
22bf3365
DL
513SELECT id
514FROM civicrm_financial_account
515WHERE is_default = 1
516AND financial_account_type_id = {$accountType}
517";
909a777b 518 $financialAccountId = CRM_Core_DAO::singleValueQuery($query);
c28241be 519
cc405f4e 520 $accountRelationsips = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount',
521 'account_relationship', CRM_Core_DAO::$_nullArray, 'validate');
c28241be 522
6a488035
TO
523 $accountsReceivableAccount = array_search('Accounts Receivable Account is', $accountRelationsips);
524 $incomeAccountIs = array_search('Income Account is', $accountRelationsips);
525 $assetAccountIs = array_search('Asset Account is', $accountRelationsips);
526 $expenseAccountIs = array_search('Expense Account is', $accountRelationsips);
c28241be 527
cc405f4e 528 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id',
529 CRM_Core_DAO::$_nullArray, 'validate');
6a488035
TO
530 $unpaidStatus = array_search('Unpaid', $financialItemStatus);
531 $paidStatus = array_search('Paid', $financialItemStatus);
c28241be 532
6a488035
TO
533 $validCurrencyCodes = CRM_Core_PseudoConstant::currencyCode();
534 $validCurrencyCodes = implode("','", $validCurrencyCodes);
535 $config = CRM_Core_Config::singleton();
536 $defaultCurrency = $config->defaultCurrency;
481a74f4 537 $now = date('YmdHis');
6a488035
TO
538
539 //adding financial_trxn records and entity_financial_trxn records related to contribution
540 //Add temp column for easy entry in entity_financial_trxn
541 $sql = "ALTER TABLE civicrm_financial_trxn ADD COLUMN contribution_id INT DEFAULT NULL";
542 CRM_Core_DAO::executeQuery($sql);
c28241be
DL
543
544 //pending pay later status handling
6a488035
TO
545 $sql = "
546INSERT INTO civicrm_financial_trxn
547 (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id,
548 check_number, to_financial_account_id, from_financial_account_id, trxn_date)
22bf3365
DL
549SELECT con.id as contribution_id, con.payment_instrument_id,
550 IF(con.currency IN ('{$validCurrencyCodes}'), con.currency, '{$defaultCurrency}') as currency,
551 con.total_amount, con.net_amount, con.fee_amount, con.trxn_id, con.contribution_status_id,
552 con.check_number, efa.financial_account_id as to_financial_account_id, NULL as from_financial_account_id,
6a488035 553 REPLACE(REPLACE(REPLACE(
c28241be
DL
554 CASE
555 WHEN con.receive_date IS NOT NULL THEN
6a488035 556 con.receive_date
c28241be 557 WHEN con.receipt_date IS NOT NULL THEN
6a488035
TO
558 con.receipt_date
559 ELSE
c28241be 560 {$now}
6a488035
TO
561 END
562 , '-', ''), ':', ''), ' ', '') as trxn_date
563FROM civicrm_contribution con
c28241be 564 LEFT JOIN civicrm_entity_financial_account efa
6a488035
TO
565 ON (con.financial_type_id = efa.entity_id AND efa.entity_table = 'civicrm_financial_type'
566 AND efa.account_relationship = {$accountsReceivableAccount})
22bf3365
DL
567WHERE con.is_pay_later = 1
568AND con.contribution_status_id = {$pendingStatus}
569";
6a488035 570 CRM_Core_DAO::executeQuery($sql);
c28241be 571
6a488035
TO
572 //create a temp table to hold financial account id related to payment instruments
573 $tempTableName1 = CRM_Core_DAO::createTempTableName();
c28241be 574
33421d01 575 $sql = "
c75e8bb2 576CREATE TEMPORARY TABLE {$tempTableName1}
22bf3365
DL
577SELECT ceft.financial_account_id financial_account_id, cov.value as instrument_id
578FROM civicrm_entity_financial_account ceft
579INNER JOIN civicrm_option_value cov ON cov.id = ceft.entity_id AND ceft.entity_table = 'civicrm_option_value'
580INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
c75e8bb2
DL
581WHERE cog.name = 'payment_instrument'
582";
6a488035 583 CRM_Core_DAO::executeQuery($sql);
22bf3365 584
b676923b 585 //CRM-12141
1b1d8be3 586 $sql = "ALTER TABLE {$tempTableName1} ADD INDEX index_instrument_id (instrument_id(200));";
b676923b 587 CRM_Core_DAO::executeQuery($sql);
6a488035 588
c28241be 589 //create temp table to process completed / cancelled contribution
6a488035 590 $tempTableName2 = CRM_Core_DAO::createTempTableName();
22bf3365 591 $sql = "
c75e8bb2 592CREATE TEMPORARY TABLE {$tempTableName2}
22bf3365
DL
593SELECT con.id as contribution_id, con.payment_instrument_id,
594 IF(con.currency IN ('{$validCurrencyCodes}'), con.currency, '{$defaultCurrency}') as currency,
595 con.total_amount, con.net_amount, con.fee_amount, con.trxn_id, con.contribution_status_id,
596 con.check_number, NULL as from_financial_account_id,
c28241be
DL
597 REPLACE(REPLACE(REPLACE(
598 CASE
599 WHEN con.receive_date IS NOT NULL THEN
6a488035 600 con.receive_date
c28241be 601 WHEN con.receipt_date IS NOT NULL THEN
6a488035
TO
602 con.receipt_date
603 ELSE
c28241be 604 {$now}
6a488035
TO
605 END
606 , '-', ''), ':', ''), ' ', '') as trxn_date,
c28241be 607 CASE
6a488035
TO
608 WHEN con.payment_instrument_id IS NULL THEN
609 {$financialAccountId}
610 WHEN con.payment_instrument_id IS NOT NULL THEN
611 tpi.financial_account_id
612 END as to_financial_account_id,
613 IF(eft.financial_trxn_id IS NULL, 'insert', eft.financial_trxn_id) as action
22bf3365
DL
614FROM civicrm_contribution con
615LEFT JOIN civicrm_entity_financial_trxn eft
616 ON (eft.entity_table = 'civicrm_contribution' AND eft.entity_id = con.id)
617LEFT JOIN {$tempTableName1} tpi
618 ON con.payment_instrument_id = tpi.instrument_id
619WHERE con.contribution_status_id IN ({$completedStatus}, {$cancelledStatus})
620";
6a488035 621 CRM_Core_DAO::executeQuery($sql);
22bf3365 622
b676923b
PN
623 // CRM-12141
624 $sql = "ALTER TABLE {$tempTableName2} ADD INDEX index_action (action);";
625 CRM_Core_DAO::executeQuery($sql);
c28241be 626
6a488035
TO
627 //handling for completed contribution and cancelled contribution
628 //insertion of new records
629 $sql = "
c28241be 630INSERT INTO civicrm_financial_trxn
6a488035 631 (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id, check_number,
c28241be 632 to_financial_account_id, from_financial_account_id, trxn_date)
6a488035
TO
633SELECT tempI.contribution_id, tempI.payment_instrument_id, tempI.currency, tempI.total_amount, tempI.net_amount,
634 tempI.fee_amount, tempI.trxn_id, tempI.contribution_status_id, tempI.check_number,
c28241be 635 tempI.to_financial_account_id, tempI.from_financial_account_id, tempI.trxn_date
6a488035 636FROM {$tempTableName2} tempI
c75e8bb2
DL
637WHERE tempI.action = 'insert'
638";
6a488035
TO
639 CRM_Core_DAO::executeQuery($sql);
640
641 //update of existing records
642 $sql = "
643UPDATE civicrm_financial_trxn ft
c28241be 644 INNER JOIN {$tempTableName2} tempU
6a488035
TO
645 ON (tempU.action != 'insert' AND ft.id = tempU.action)
646SET ft.from_financial_account_id = NULL,
647 ft.to_financial_account_id = tempU.to_financial_account_id,
c28241be 648 ft.status_id = tempU.contribution_status_id,
6a488035
TO
649 ft.payment_instrument_id = tempU.payment_instrument_id,
650 ft.check_number = tempU.check_number,
651 ft.contribution_id = tempU.contribution_id;";
652 CRM_Core_DAO::executeQuery($sql);
653
654 //insert the -ve transaction rows for cancelled contributions
655 $sql = "
656INSERT INTO civicrm_financial_trxn
c28241be
DL
657 (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id,
658 check_number, to_financial_account_id, from_financial_account_id, trxn_date)
659SELECT ft.contribution_id, ft.payment_instrument_id, ft.currency, -ft.total_amount, ft.net_amount, ft.fee_amount, ft.trxn_id,
6a488035 660 ft.status_id, ft.check_number, ft.to_financial_account_id, ft.from_financial_account_id, ft.trxn_date
c28241be 661FROM civicrm_financial_trxn ft
6a488035
TO
662WHERE ft.status_id = {$cancelledStatus};";
663 CRM_Core_DAO::executeQuery($sql);
664
665 //inserting entity financial trxn entries if its not present in entity_financial_trxn for completed and pending contribution statuses
666 //this also handles +ve and -ve both transaction entries for a cancelled contribution
667 $sql = "
668INSERT INTO civicrm_entity_financial_trxn (entity_table, entity_id, financial_trxn_id, amount)
669SELECT 'civicrm_contribution', ft.contribution_id, ft.id, ft.total_amount as amount
670FROM civicrm_financial_trxn ft
c28241be
DL
671WHERE contribution_id IS NOT NULL AND
672 ft.id NOT IN (SELECT financial_trxn_id
673 FROM civicrm_entity_financial_trxn
6a488035
TO
674 WHERE entity_table = 'civicrm_contribution'
675 AND entity_id = ft.contribution_id)";
676 CRM_Core_DAO::executeQuery($sql);
677 //end of adding financial_trxn records and entity_financial_trxn records related to contribution
678
679 //update all linked line_item rows
680 // set line_item.financial_type_id = contribution.financial_type_id if contribution page id is null and not participant line item
681 // set line_item.financial_type_id = price_field_value.financial_type_id if contribution page id is set and not participant line item
682 // set line_item.financial_type_id = event.financial_type_id if its participant line item and line_item.price_field_value_id is null
683 // 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
684 $updateLineItemSql = "
685UPDATE civicrm_line_item li
686 LEFT JOIN civicrm_contribution con
687 ON (li.entity_id = con.id AND li.entity_table = 'civicrm_contribution')
688 LEFT JOIN civicrm_price_field_value cpfv
689 ON li.price_field_value_id = cpfv.id
690 LEFT JOIN civicrm_participant cp
691 ON (li.entity_id = cp.id AND li.entity_table = 'civicrm_participant')
692 LEFT JOIN civicrm_event ce
c28241be 693 ON ce.id = cp.event_id
6a488035 694SET li.financial_type_id = CASE
c28241be 695 WHEN (con.contribution_page_id IS NULL || li.price_field_value_id IS NULL) AND cp.id IS NULL THEN
6a488035
TO
696 con.financial_type_id
697 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
698 cpfv.financial_type_id
c28241be 699 WHEN cp.id IS NOT NULL AND li.price_field_value_id IS NULL THEN
6a488035
TO
700 ce.financial_type_id
701 END";
702 CRM_Core_DAO::executeQuery($updateLineItemSql, $queryParams);
c28241be
DL
703
704 //add the financial_item entries
6a488035
TO
705 //add a temp column so that inserting entity_financial_trxn entries gets easy
706 $sql = "ALTER TABLE civicrm_financial_item ADD COLUMN f_trxn_id INT DEFAULT NULL";
707 CRM_Core_DAO::executeQuery($sql);
c28241be 708
6a488035
TO
709 //add financial_item entries for contribution completed / pending pay later / cancelled
710 $contributionlineItemSql = "
c28241be 711INSERT INTO civicrm_financial_item
6a488035
TO
712 (transaction_date, contact_id, amount, currency, entity_table, entity_id, description, status_id, financial_account_id, f_trxn_id)
713
714SELECT REPLACE(REPLACE(REPLACE(ft.trxn_date, '-', ''), ':', ''), ' ', ''), con.contact_id,
c28241be 715 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
716 li.id as line_item_id, li.label as line_item_label,
717 IF(con.contribution_status_id = {$pendingStatus}, {$unpaidStatus}, {$paidStatus}) as status_id, efa.financial_account_id as financial_account_id,
718 ft.id as f_trxn_id
719FROM civicrm_line_item li
c28241be 720 INNER JOIN civicrm_contribution con
6a488035
TO
721 ON (li.entity_id = con.id AND li.entity_table = 'civicrm_contribution')
722 INNER JOIN civicrm_financial_trxn ft
723 ON (con.id = ft.contribution_id)
724 LEFT JOIN civicrm_entity_financial_account efa
725 ON (li.financial_type_id = efa.entity_id AND efa.entity_table = 'civicrm_financial_type'
726 AND efa.account_relationship = {$incomeAccountIs})
727WHERE con.contribution_status_id IN (%1, %3) OR (con.is_pay_later = 1 AND con.contribution_status_id = %2)";
728 CRM_Core_DAO::executeQuery($contributionlineItemSql, $queryParams);
c28241be 729
6a488035
TO
730 //add financial_item entries for event
731 $participantLineItemSql = "
c28241be 732INSERT INTO civicrm_financial_item
6a488035
TO
733 (transaction_date, contact_id, amount, currency, entity_table, entity_id, description, status_id, financial_account_id, f_trxn_id)
734
735SELECT REPLACE(REPLACE(REPLACE(ft.trxn_date, '-', ''), ':', ''), ' ', ''), con.contact_id,
736 IF(ft.total_amount < 0 AND con.contribution_status_id = %3, -li.line_total, li.line_total) as line_total,
c28241be 737 con.currency, 'civicrm_line_item', li.id as line_item_id, li.label as line_item_label,
6a488035
TO
738 IF(con.contribution_status_id = {$pendingStatus}, {$unpaidStatus}, {$paidStatus}) as status_id,
739 efa.financial_account_id as financial_account_id, ft.id as f_trxn_id
740FROM civicrm_line_item li
741 INNER JOIN civicrm_participant par
742 ON (li.entity_id = par.id AND li.entity_table = 'civicrm_participant')
c28241be
DL
743 INNER JOIN civicrm_participant_payment pp
744 ON (pp.participant_id = par.id)
6a488035
TO
745 INNER JOIN civicrm_contribution con
746 ON (pp.contribution_id = con.id)
c28241be 747 INNER JOIN civicrm_financial_trxn ft
6a488035
TO
748 ON (con.id = ft.contribution_id)
749 LEFT JOIN civicrm_entity_financial_account efa
750 ON (li.financial_type_id = efa.entity_id AND
751 efa.entity_table = 'civicrm_financial_type' AND efa.account_relationship = {$incomeAccountIs})
752WHERE con.contribution_status_id IN (%1, %3) OR (con.is_pay_later = 1 AND con.contribution_status_id = %2)";
753 CRM_Core_DAO::executeQuery($participantLineItemSql, $queryParams);
c28241be 754
6a488035
TO
755 //fee handling for contributions
756 //insert fee entries in financial_trxn for contributions
757 $sql = "ALTER TABLE civicrm_financial_trxn ADD COLUMN is_fee TINYINT DEFAULT NULL";
758 CRM_Core_DAO::executeQuery($sql);
c28241be 759
6a488035 760 $sql = "
c28241be 761INSERT INTO civicrm_financial_trxn
6a488035
TO
762 (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id, check_number,
763 to_financial_account_id, from_financial_account_id, trxn_date, payment_processor_id, is_fee)
764
765SELECT con.id, ft.payment_instrument_id, ft.currency, ft.fee_amount, NULL, NULL, ft.trxn_id, %1 as status_id,
766 ft.check_number, efaFT.financial_account_id as to_financial_account_id, CASE
767 WHEN efaPP.financial_account_id IS NOT NULL THEN
768 efaPP.financial_account_id
769 WHEN tpi.financial_account_id IS NOT NULL THEN
c28241be
DL
770 tpi.financial_account_id
771 ELSE
772 {$financialAccountId}
6a488035
TO
773 END as from_financial_account_id, ft.trxn_date, ft.payment_processor_id, 1 as is_fee
774FROM civicrm_contribution con
775 INNER JOIN civicrm_financial_trxn ft
776 ON (ft.contribution_id = con.id)
777 LEFT JOIN civicrm_entity_financial_account efaFT
778 ON (con.financial_type_id = efaFT.entity_id AND efaFT.entity_table = 'civicrm_financial_type'
779 AND efaFT.account_relationship = {$expenseAccountIs})
c28241be 780 LEFT JOIN civicrm_entity_financial_account efaPP
6a488035
TO
781 ON (ft.payment_processor_id = efaPP.entity_id AND efaPP.entity_table = 'civicrm_payment_processor'
782 AND efaPP.account_relationship = {$assetAccountIs})
c28241be 783 LEFT JOIN {$tempTableName1} tpi
6a488035 784 ON ft.payment_instrument_id = tpi.instrument_id
368d2a88 785WHERE 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
786GROUP BY con.id";
787 CRM_Core_DAO::executeQuery($sql, $queryParams);
788
c28241be 789 //link financial_trxn to contribution
6a488035
TO
790 $sql = "
791INSERT INTO civicrm_entity_financial_trxn
792 (entity_table, entity_id, financial_trxn_id, amount)
793SELECT 'civicrm_contribution', ft.contribution_id, ft.id, ft.total_amount
794FROM civicrm_financial_trxn ft
795WHERE ft.is_fee = 1";
796 CRM_Core_DAO::executeQuery($sql);
c28241be 797
6a488035
TO
798 //add fee related entries to financial item table
799 $domainId = CRM_Core_Config::domainID();
800 $domainContactId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id');
801 $sql = "
c28241be 802INSERT INTO civicrm_financial_item
6a488035 803 (transaction_date, contact_id, amount, currency, entity_table, entity_id, description, status_id, financial_account_id, f_trxn_id)
c28241be 804SELECT ft.trxn_date, {$domainContactId} as contact_id, ft.total_amount, ft.currency, 'civicrm_financial_trxn', ft.id,
6a488035 805 'Fee', {$paidStatus} as status_id, ft.to_financial_account_id as financial_account_id, ft.id as f_trxn_id
c28241be 806FROM civicrm_financial_trxn ft
6a488035
TO
807WHERE ft.is_fee = 1;";
808 CRM_Core_DAO::executeQuery($sql);
c28241be 809
6a488035
TO
810 //add entries to entity_financial_trxn table
811 $sql = "
812INSERT INTO civicrm_entity_financial_trxn (entity_table, entity_id, financial_trxn_id, amount)
813SELECT 'civicrm_financial_item' as entity_table, fi.id as entity_id, fi.f_trxn_id as financial_trxn_id, fi.amount
814FROM civicrm_financial_item fi";
815 CRM_Core_DAO::executeQuery($sql);
816
817 //drop the temparory columns
818 $sql = "ALTER TABLE civicrm_financial_trxn
819 DROP COLUMN contribution_id,
820 DROP COLUMN is_fee;";
821 CRM_Core_DAO::executeQuery($sql);
822
823 $sql = "ALTER TABLE civicrm_financial_item DROP f_trxn_id";
824 CRM_Core_DAO::executeQuery($sql);
c28241be 825
6a488035
TO
826 return TRUE;
827 }
828
624e56fa
EM
829 /**
830 * @return array
831 */
00be9182 832 public function createDomainContacts() {
6a488035
TO
833 $domainParams = $context = array();
834 $query = "
22bf3365
DL
835ALTER 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',
836 ADD CONSTRAINT FK_civicrm_domain_contact_id FOREIGN KEY (contact_id) REFERENCES civicrm_contact(id);";
6a488035 837 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
c28241be 838
22bf3365
DL
839 $query = '
840SELECT cd.id, cd.name, ce.email FROM civicrm_domain cd
6a488035 841LEFT JOIN civicrm_loc_block clb ON clb.id = cd. loc_block_id
22bf3365 842LEFT JOIN civicrm_email ce ON ce.id = clb.email_id ;
33421d01 843';
6a488035 844 $dao = CRM_Core_DAO::executeQuery($query);
22e263ad 845 while ($dao->fetch()) {
22bf3365
DL
846 $query = "
847SELECT cc.id FROM civicrm_contact cc
6a488035 848LEFT JOIN civicrm_email ce ON ce.contact_id = cc.id
22bf3365
DL
849WHERE cc.contact_type = 'Organization' AND cc.organization_name = %1
850";
851 $params = array(1 => array($dao->name, 'String'));
6a488035 852 if ($dao->email) {
22bf3365
DL
853 $query .= " AND ce.email = %2 ";
854 $params[2] = array($dao->email, 'String');
6a488035 855 }
22bf3365 856 $contactID = CRM_Core_DAO::singleValueQuery($query, $params);
6a488035
TO
857 $context[1] = $dao->name;
858 if (empty($contactID)) {
d8e9fe86
PD
859 $params = array(
860 'sort_name' => $dao->name,
861 'display_name' => $dao->name,
862 'legal_name' => $dao->name,
863 'organization_name' => $dao->name,
21dfd5f5 864 'contact_type' => 'Organization',
d8e9fe86 865 );
6a488035
TO
866 $contact = CRM_Contact_BAO_Contact::add($params);
867 $contactID = $contact->id;
868 $context[0] = 'added';
c28241be 869 }
6a488035
TO
870 else {
871 $context[0] = 'merged';
872 }
873 $domainParams['contact_id'] = $contactID;
874 CRM_Core_BAO_Domain::edit($domainParams, $dao->id);
875 }
876 return $context;
877 }
878
00be9182 879 public function task_4_3_alpha1_checkDBConstraints() {
6a488035
TO
880 //checking whether the foreign key exists before dropping it CRM-11260
881 $config = CRM_Core_Config::singleton();
882 $dbUf = DB::parseDSN($config->dsn);
6a488035 883 $tables = array(
33421d01
TO
884 'autorenewal_msg_id' => array(
885 'tableName' => 'civicrm_membership_type',
886 'fkey' => 'FK_civicrm_membership_autorenewal_msg_id',
887 ),
888 'to_account_id' => array(
889 'tableName' => 'civicrm_financial_trxn',
890 'constraintName' => 'civicrm_financial_trxn_ibfk_2',
891 ),
892 'from_account_id' => array(
893 'tableName' => 'civicrm_financial_trxn',
894 'constraintName' => 'civicrm_financial_trxn_ibfk_1',
895 ),
896 'contribution_type_id' => array(
897 'tableName' => 'civicrm_contribution_recur',
898 'fkey' => 'FK_civicrm_contribution_recur_contribution_type_id',
899 ),
6a488035 900 );
22bf3365
DL
901 $query = "
902SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
6a488035
TO
903WHERE table_name = 'civicrm_contribution_recur'
904AND constraint_name = 'FK_civicrm_contribution_recur_contribution_type_id'
22bf3365
DL
905AND TABLE_SCHEMA = %1
906";
907 $params = array(1 => array($dbUf['database'], 'String'));
6a488035 908 $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, FALSE);
9b873358 909 foreach ($tables as $columnName => $value) {
6a488035
TO
910 if ($value['tableName'] == 'civicrm_membership_type' || $value['tableName'] == 'civicrm_contribution_recur') {
911 $foreignKeyExists = CRM_Core_DAO::checkConstraintExists($value['tableName'], $value['fkey']);
912 $fKey = $value['fkey'];
0db6c3e1
TO
913 }
914 else {
fbeab178 915 $foreignKeyExists = CRM_Core_DAO::checkFKConstraintInFormat($value['tableName'], $columnName);
6a488035
TO
916 $fKey = "`FK_{$value['tableName']}_{$columnName}`";
917 }
918 if ($foreignKeyExists || $value['tableName'] == 'civicrm_financial_trxn') {
919 if ($value['tableName'] != 'civicrm_contribution_recur' || ($value['tableName'] == 'civicrm_contribution_recur' && $dao->N)) {
33421d01 920 $constraintName = $foreignKeyExists ? $fKey : $value['constraintName'];
22bf3365
DL
921 $query = "ALTER TABLE {$value['tableName']} DROP FOREIGN KEY {$constraintName}";
922 CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, FALSE);
6a488035 923 }
22bf3365
DL
924 $query = "ALTER TABLE {$value['tableName']} DROP INDEX {$fKey}";
925 CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, FALSE);
6a488035
TO
926 }
927 }
928 // check if column contact_id is present or not in civicrm_financial_account
929 $fieldExists = CRM_Core_DAO::checkFieldExists('civicrm_financial_account', 'contact_id', FALSE);
930 if (!$fieldExists) {
22bf3365
DL
931 $query = "
932ALTER TABLE civicrm_financial_account
933 ADD contact_id int(10) unsigned DEFAULT NULL COMMENT 'Version identifier of financial_type' AFTER name,
934 ADD CONSTRAINT FK_civicrm_financial_account_contact_id FOREIGN KEY (contact_id) REFERENCES civicrm_contact(id);
935";
6a488035
TO
936 CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, FALSE);
937 }
938 }
939
940 /**
941 * Read creation and modification times from civicrm_log; add
942 * them to civicrm_contact.
943 */
00be9182 944 public function convertTimestamps(CRM_Queue_TaskContext $ctx, $startId, $endId) {
6a488035
TO
945 $sql = "
946 SELECT entity_id, min(modified_date) AS created, max(modified_date) AS modified
947 FROM civicrm_log
948 WHERE entity_table = 'civicrm_contact'
949 AND entity_id BETWEEN %1 AND %2
950 GROUP BY entity_id
951 ";
952 $params = array(
953 1 => array($startId, 'Integer'),
954 2 => array($endId, 'Integer'),
955 );
956 $dao = CRM_Core_DAO::executeQuery($sql, $params);
957 while ($dao->fetch()) {
958 // FIXME civicrm_log.modified_date is DATETIME; civicrm_contact.modified_date is TIMESTAMP
959 CRM_Core_DAO::executeQuery(
16aa2ccd 960 'UPDATE civicrm_contact SET created_date = FROM_UNIXTIME(UNIX_TIMESTAMP(%1)), modified_date = FROM_UNIXTIME(UNIX_TIMESTAMP(%2)) WHERE id = %3',
6a488035
TO
961 array(
962 1 => array($dao->created, 'String'),
963 2 => array($dao->modified, 'String'),
964 3 => array($dao->entity_id, 'Integer'),
965 )
966 );
967 }
968
969 return TRUE;
970 }
77b97be7 971
5beb1de0 972 /**
fe482240 973 * Change index and add missing constraints for civicrm_contribution_recur.
5beb1de0 974 */
00be9182 975 public function addMissingConstraints(CRM_Queue_TaskContext $ctx) {
5beb1de0
PN
976 $query = "SHOW KEYS FROM `civicrm_contribution_recur` WHERE key_name = 'UI_contrib_payment_instrument_id'";
977 $dao = CRM_Core_DAO::executeQuery($query);
978 if ($dao->N) {
979 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_contribution_recur DROP INDEX UI_contrib_payment_instrument_id');
980 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_contribution_recur ADD INDEX UI_contribution_recur_payment_instrument_id (payment_instrument_id)');
981 }
982 $constraintArray = array(
77b97be7
EM
983 'contact_id' => " ADD CONSTRAINT `FK_civicrm_contribution_recur_contact_id` FOREIGN KEY (`contact_id`) REFERENCES `civicrm_contact` (`id`) ON DELETE CASCADE ",
984 '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 ",
985 '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
986 'campaign_id' => " ADD CONSTRAINT `FK_civicrm_contribution_recur_campaign_id` FOREIGN KEY (`campaign_id`) REFERENCES `civicrm_campaign` (`id`) ON DELETE SET NULL ",
987 );
988 $constraint = array();
989 foreach ($constraintArray as $constraintKey => $value) {
990 $foreignKeyExists = CRM_Core_DAO::checkFKConstraintInFormat('civicrm_contribution_recur', $constraintKey);
991 if (!$foreignKeyExists) {
992 $constraint[] = $value;
993 }
994 }
995 if (!empty($constraint)) {
996 $query = "ALTER TABLE civicrm_contribution_recur " . implode(' , ', $constraint);
997 CRM_Core_DAO::executeQuery($query);
998 }
77b97be7 999 return TRUE;
5beb1de0
PN
1000 }
1001
bf45dbe8 1002 /**
fe482240 1003 * Update financial_account_id for bad data in financial_trxn table.
bf45dbe8 1004 * CRM-12844
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(
33421d01
TO
1028 'from_financial_account_id' => $dao->to_financial_account_id,
1029 'payment_processor_id' => $dao->payment_processor_id,
1030 $dao->contribution_id => 1,
bf45dbe8
PN
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'])
33421d01
TO
1040 || ($dao->entity_table == 'civicrm_financial_trxn' && $dao->from_financial_account_id == $financialTrxn[$dao->contribution_recur_id]['from_financial_account_id'])
1041 ) {
bf45dbe8
PN
1042 continue;
1043 }
33421d01 1044 $subsequentPayments[$dao->contribution_recur_id][$dao->entity_table][] = $dao->financial_trxn_id;
bf45dbe8
PN
1045 }
1046 }
1047 foreach ($subsequentPayments as $key => $value) {
1048 foreach ($value as $table => $val) {
1049 if ($table == 'civicrm_financial_trxn') {
1050 $field = 'from_financial_account_id';
1051 }
1052 else {
1053 $field = 'to_financial_account_id';
1054 }
77b97be7
EM
1055 $sql = "UPDATE civicrm_financial_trxn SET $field = " . $financialTrxn[$dao->contribution_recur_id]['from_financial_account_id'] . ',
1056payment_processor_id = ' . $financialTrxn[$dao->contribution_recur_id]['payment_processor_id'] . ' WHERE
bf45dbe8
PN
1057id IN (' . implode(',', $val) . ')';
1058 CRM_Core_DAO::executeQuery($sql);
1059 }
1060 }
1061 return TRUE;
1062 }
1063
1064 /**
fe482240 1065 * Update financial_account_id for bad data in financial_trxn table.
bf45dbe8 1066 * CRM-12844
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(
33421d01
TO
1089 'price_field_id' => $dao->price_field_id,
1090 'price_field_value_id' => $dao->price_field_value_id,
1091 'label' => strval($dao->label),
1092 'financial_account_id' => $dao->financial_account_id,
1093 $dao->contribution_id => 1,
bf45dbe8
PN
1094 );
1095 }
1096 else {
1097 if ($dao->price_field_value_id == $financialTrxn[$dao->contribution_recur_id]['price_field_value_id']) {
1098 continue;
1099 }
33421d01 1100 $subsequentPayments[$dao->contribution_recur_id][] = $dao->line_item_id;
bf45dbe8
PN
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'
86bfa4f6 1114AND cli.entity_table = 'civicrm_contribution' AND cli.id IN (" . implode(',', $value) . ');';
33421d01 1115 $params = array(
bf45dbe8
PN
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 /**
fe482240 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 }
4c9b6178 1150 elseif (array_key_exists('contribution_type', $formValues[$value])) {
d20145bc
PN
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 1204 /**
fe482240 1205 * Add ON DELETE options for constraint if not present.
bdbf899f
PN
1206 * CRM-13088 && CRM-12156
1207 *
77b97be7
EM
1208 * @param CRM_Queue_TaskContext $ctx
1209 *
a6c01b45
CW
1210 * @return bool
1211 * TRUE for success
bdbf899f 1212 */
00be9182 1213 public function task_4_3_x_checkConstraints(CRM_Queue_TaskContext $ctx) {
49ddb59d 1214 CRM_Core_DAO::executeQuery('ALTER TABLE `civicrm_financial_account` CHANGE `contact_id` `contact_id` INT( 10 ) UNSIGNED NULL DEFAULT NULL');
bdbf899f 1215 $config = CRM_Core_Config::singleton();
33421d01 1216 $dbname = DB::parseDSN($config->dsn);
bdbf899f
PN
1217 $constraintArray = array(
1218 "'FK_civicrm_financial_account_contact_id'",
1219 "'FK_civicrm_financial_item_contact_id'",
1220 "'FK_civicrm_contribution_recur_financial_type_id'",
1221 "'FK_civicrm_line_item_financial_type_id'",
1222 "'FK_civicrm_product_financial_type_id'",
1223 "'FK_civicrm_premiums_product_financial_type_id'",
1224 "'FK_civicrm_price_field_value_financial_type_id'",
1225 "'FK_civicrm_contribution_product_financial_type_id'",
1226 "'FK_civicrm_price_set_financial_type_id'",
d4b17c97 1227 "'FK_civicrm_grant_financial_type_id'",
bdbf899f
PN
1228 );
1229
77b97be7 1230 $sql = "SELECT DELETE_RULE, TABLE_NAME, CONSTRAINT_NAME
bdbf899f
PN
1231FROM information_schema.REFERENTIAL_CONSTRAINTS
1232WHERE CONSTRAINT_NAME IN (" . implode(',', $constraintArray) . ")
1233AND CONSTRAINT_SCHEMA = %1";
1234 $params = array(1 => array($dbname['database'], 'String'));
1235 $onDelete = CRM_Core_DAO::executeQuery($sql, $params, TRUE, FALSE);
1236 while ($onDelete->fetch()) {
77b97be7 1237 if (($onDelete->TABLE_NAME != 'civicrm_financial_item' && $onDelete->DELETE_RULE != 'SET NULL') ||
33421d01
TO
1238 ($onDelete->TABLE_NAME == 'civicrm_financial_item' && $onDelete->DELETE_RULE != 'CASCADE')
1239 ) {
bdbf899f
PN
1240 $tableName = 'civicrm_financial_type';
1241 $onDeleteOption = ' SET NULL ';
1242 $columnName = 'financial_type_id';
1243 if (preg_match('/contact_id/', $onDelete->CONSTRAINT_NAME)) {
1244 $tableName = 'civicrm_contact';
1245 $columnName = 'contact_id';
1246 if ($onDelete->TABLE_NAME == 'civicrm_financial_item') {
1247 $onDeleteOption = 'CASCADE';
1248 }
1249 }
1250 }
1251 else {
1252 continue;
1253 }
1254 $query = "ALTER TABLE {$onDelete->TABLE_NAME}
1255 DROP FOREIGN KEY {$onDelete->CONSTRAINT_NAME},
1256 DROP INDEX {$onDelete->CONSTRAINT_NAME};";
1257 CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
1258 $query = " ALTER TABLE {$onDelete->TABLE_NAME}
1259 ADD CONSTRAINT {$onDelete->CONSTRAINT_NAME} FOREIGN KEY (`" . $columnName . "`) REFERENCES {$tableName} (`id`) ON DELETE {$onDeleteOption};
1260 ";
1261 CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
1262 }
1263 return TRUE;
1264 }
1265
b676923b
PN
1266 /**
1267 * Check/Add INDEX CRM-12141
1268 *
77b97be7
EM
1269 * @param CRM_Queue_TaskContext $ctx
1270 *
a6c01b45
CW
1271 * @return bool
1272 * TRUE for success
b676923b 1273 */
00be9182 1274 public function task_4_3_x_checkIndexes(CRM_Queue_TaskContext $ctx) {
22bf3365
DL
1275 $query = "
1276SHOW KEYS
1277FROM civicrm_entity_financial_trxn
1278WHERE key_name IN ('UI_entity_financial_trxn_entity_table', 'UI_entity_financial_trxn_entity_id')
1279";
b676923b
PN
1280 $dao = CRM_Core_DAO::executeQuery($query);
1281 if (!$dao->N) {
22bf3365
DL
1282 $query = "
1283ALTER TABLE civicrm_entity_financial_trxn
b676923b 1284ADD INDEX UI_entity_financial_trxn_entity_table (entity_table),
22bf3365
DL
1285ADD INDEX UI_entity_financial_trxn_entity_id (entity_id);
1286";
1287 CRM_Core_DAO::executeQuery($query);
b676923b
PN
1288 }
1289 return TRUE;
1290 }
1291
6a488035
TO
1292 /**
1293 * Update phones CRM-11292
1294 *
77b97be7
EM
1295 * @param CRM_Queue_TaskContext $ctx
1296 *
a6c01b45
CW
1297 * @return bool
1298 * TRUE for success
6a488035 1299 */
00be9182 1300 public static function phoneNumeric(CRM_Queue_TaskContext $ctx) {
6a488035
TO
1301 CRM_Core_DAO::executeQuery(CRM_Contact_BAO_Contact::DROP_STRIP_FUNCTION_43);
1302 CRM_Core_DAO::executeQuery(CRM_Contact_BAO_Contact::CREATE_STRIP_FUNCTION_43);
1303 CRM_Core_DAO::executeQuery("UPDATE civicrm_phone SET phone_numeric = civicrm_strip_non_numeric(phone)");
1304 return TRUE;
1305 }
1306
10a5be27 1307}