Merge pull request #445 from deepak-srivastava/crm43
[civicrm-core.git] / CRM / Upgrade / Incremental / php / FourThree.php
CommitLineData
6a488035
TO
1<?php
2
3/*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.3 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2013 |
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
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35class CRM_Upgrade_Incremental_php_FourThree {
36 const BATCH_SIZE = 5000;
37
38 function verifyPreDBstate(&$errors) {
39 return TRUE;
40 }
41
505cf9f9
PJ
42 /**
43 * Compute any messages which should be displayed beforeupgrade
44 *
45 * Note: This function is called iteratively for each upcoming
46 * revision to the database.
47 *
48 * @param $postUpgradeMessage string, alterable
49 * @param $rev string, a version number, e.g. '4.3.alpha1', '4.3.beta3', '4.3.0'
50 * @return void
51 */
52 function setPreUpgradeMessage(&$preUpgradeMessage, $rev, $currentVer = NULL) {
7402727c 53 if ($rev == '4.3.beta3') {
505cf9f9
PJ
54 //CRM-12084
55 //sql for checking orphaned contribution records
56 $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";
57 $count = CRM_Core_DAO::singleValueQuery($sql, array(), TRUE, FALSE);
58
59 if ($count > 0) {
60 $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>'));
61 CRM_Core_Error::fatal($error);
62 return FALSE;
63 }
64 }
de65d43e
TO
65 if ($rev == '4.3.beta4' && CRM_Utils_Constant::value('CIVICRM_UF', FALSE) == 'Drupal6') {
66 // CRM-11823 - Make sure the D6 HTML HEAD technique will work on upgrade pages
67 theme('item_list', array()); // force-load theme registry
68 $theme_registry = theme_get_registry();
69 if (
70 !isset($theme_registry['page']['preprocess functions']) ||
71 FALSE === array_search('civicrm_preprocess_page_inject', $theme_registry['page']['preprocess functions'])
72 ) {
73 CRM_Core_Error::fatal('Please reset the Drupal cache (Administer => Site Configuration => Performance => Clear cached data))');
74 }
75 }
505cf9f9
PJ
76 }
77
6a488035
TO
78 /**
79 * Compute any messages which should be displayed after upgrade
80 *
81 * @param $postUpgradeMessage string, alterable
82 * @param $rev string, an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs
83 * @return void
84 */
85 function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
86 if ($rev == '4.3.alpha1') {
87 // check if CiviMember component is enabled
88 $config = CRM_Core_Config::singleton();
89 if (in_array('CiviMember', $config->enableComponents)) {
90 $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.');
91 $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.');
92 }
c28241be 93
6a488035 94 //CRM-11636
c28241be 95 //here we do the financial type check and migration
6a488035
TO
96 $isDefaultsModified = self::_checkAndMigrateDefaultFinancialTypes();
97 if($isDefaultsModified) {
98 $postUpgradeMessage .= '<br />' . ts('Please review all price set financial type assignments.');
c28241be 99 }
6a488035
TO
100 list($context, $orgName) = self::createDomainContacts();
101 if ($context == 'added') {
10a5be27 102 $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
103 }
104 elseif ($context == 'merged') {
10a5be27 105 $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 106 }
24571eea
DS
107
108 $providerExists = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_sms_provider LIMIT 1");
109 if ($providerExists) {
110 $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'));
111 }
6a488035
TO
112 }
113
114 if ($rev == '4.3.alpha2') {
115 $sql = "
116SELECT title, id
117FROM civicrm_action_schedule
118WHERE entity_value = '' OR entity_value IS NULL
119";
c28241be 120
6a488035
TO
121 $dao = CRM_Core_DAO::executeQuery($sql);
122 $reminder = array();
123 $list = '';
124 while ($dao->fetch()) {
125 $reminder[$dao->id] = $dao->title;
126 $list .= "<li>{$dao->title}</li>";
127 }
c28241be 128 if (!empty($reminder)) {
6a488035
TO
129 $list = "<br /><ul>" . $list . "</ul>";
130 $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));
131 }
132 }
133
2cf0e58d 134 if ($rev == '4.3.beta2') {
6a488035
TO
135 $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).');
136 }
e3a96c9b
DG
137
138 if ($rev == '4.3.beta5') {
139 $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.");
140
141 // CRM-12155
22bf3365
DL
142 $query = "
143SELECT ceft.id FROM `civicrm_financial_trxn` cft
144LEFT JOIN civicrm_entity_financial_trxn ceft
145 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
146LEFT JOIN civicrm_contribution cc
147 ON cc.id = ceft.entity_id AND ceft.entity_table = 'civicrm_contribution'
148WHERE cc.id IS NULL
149";
e3a96c9b
DG
150
151 $dao = CRM_Core_DAO::executeQuery($query);
152 $isOrphanData = TRUE;
153 if (!$dao->N) {
22bf3365
DL
154 $query = "
155SELECT cli.id FROM civicrm_line_item cli
e3a96c9b
DG
156LEFT JOIN civicrm_contribution cc ON cli.entity_id = cc.id AND cli.entity_table = 'civicrm_contribution'
157LEFT JOIN civicrm_participant cp ON cli.entity_id = cp.id AND cli.entity_table = 'civicrm_participant'
158WHERE CASE WHEN cli.entity_table = 'civicrm_contribution'
22bf3365
DL
159 THEN cc.id IS NULL
160 ELSE cp.id IS NULL
161END
162";
e3a96c9b 163 $dao = CRM_Core_DAO::executeQuery($query);
22bf3365 164 if (!$dao->N) {
e3a96c9b
DG
165 $revPattern = '/^((\d{1,2})\.\d{1,2})\.(\d{1,2}|\w{4,7})?$/i';
166 preg_match($revPattern, $currentVer, $version);
167 if ($version[1] >= 4.3) {
22bf3365
DL
168 $query = "
169SELECT cfi.id
170FROM civicrm_financial_item cfi
e3a96c9b 171LEFT JOIN civicrm_entity_financial_trxn ceft ON ceft.entity_table = 'civicrm_financial_item' and cfi.id = ceft.entity_id
22bf3365
DL
172WHERE ceft.entity_id IS NULL;
173";
e3a96c9b 174 $dao = CRM_Core_DAO::executeQuery($query);
22bf3365 175 if (!$dao->N) {
e3a96c9b
DG
176 $isOrphanData = FALSE;
177 }
178 }
179 else {
22bf3365 180 $isOrphanData = FALSE;
e3a96c9b
DG
181 }
182 }
183 }
184
185 if ($isOrphanData) {
186 $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">this wiki page for details</a>.
187 ', array( 1 => 'http://wiki.civicrm.org/confluence/display/CRMDOC/Clean+up+extraneous+financial+data+-+4.3+upgrades')) . "</strong>";
188 }
189 }
6a488035
TO
190 }
191
192 function upgrade_4_3_alpha1($rev) {
193 self::task_4_3_alpha1_checkDBConstraints();
c28241be 194
b676923b
PN
195 // add indexes for civicrm_entity_financial_trxn
196 // CRM-12141
197 $this->addTask(ts('Check/Add indexes for civicrm_entity_financial_trxn'), 'task_4_3_x_checkIndexes', $rev);
6a488035
TO
198 // task to process sql
199 $this->addTask(ts('Upgrade DB to 4.3.alpha1: SQL'), 'task_4_3_x_runSql', $rev);
c28241be 200
6a488035
TO
201 //CRM-11636
202 $this->addTask(ts('Populate financial type values for price records'), 'assignFinancialTypeToPriceRecords');
203 //CRM-11514 create financial records for contributions
204 $this->addTask(ts('Create financial records for contributions'), 'createFinancialRecords');
c28241be 205
6a488035
TO
206 $minId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(min(id),0) FROM civicrm_contact');
207 $maxId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(max(id),0) FROM civicrm_contact');
208 for ($startId = $minId; $startId <= $maxId; $startId += self::BATCH_SIZE) {
209 $endId = $startId + self::BATCH_SIZE - 1;
10a5be27 210 $title = ts('Upgrade timestamps (%1 => %2)', array(1 => $startId, 2 => $endId));
6a488035
TO
211 $this->addTask($title, 'convertTimestamps', $startId, $endId);
212 }
213
214 // CRM-10893
215 // fix WP access control
216 $config = CRM_Core_Config::singleton( );
217 if ($config->userFramework == 'WordPress') {
218 civicrm_wp_set_capabilities( );
219 }
220
221 // Update phones CRM-11292.
222 $this->addTask(ts('Upgrade Phone Numbers'), 'phoneNumeric');
c28241be 223
6a488035
TO
224 return TRUE;
225 }
226
227 function upgrade_4_3_alpha2($rev) {
228 //CRM-11847
229 $isColumnPresent = CRM_Core_DAO::checkFieldExists('civicrm_dedupe_rule_group', 'is_default');
230 if ($isColumnPresent) {
231 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_dedupe_rule_group DROP COLUMN is_default');
232 }
233 $this->addTask(ts('Upgrade DB to 4.3.alpha2: SQL'), 'task_4_3_x_runSql', $rev);
234 }
235
236 function upgrade_4_3_alpha3($rev) {
237 $this->addTask(ts('Upgrade DB to 4.3.alpha3: SQL'), 'task_4_3_x_runSql', $rev);
238 }
239
8a438ec9
KJ
240 function upgrade_4_3_beta2($rev) {
241 $this->addTask(ts('Upgrade DB to 4.3.beta2: SQL'), 'task_4_3_x_runSql', $rev);
ab00f69d 242
c28241be
DL
243 // CRM-12002
244 if (
245 CRM_Core_DAO::checkTableExists('log_civicrm_line_item') &&
246 CRM_Core_DAO::checkFieldExists('log_civicrm_line_item', 'label')
247 ) {
248 CRM_Core_DAO::executeQuery('ALTER TABLE `log_civicrm_line_item` CHANGE `label` `label` VARCHAR(255) NULL DEFAULT NULL');
249 }
250 }
251
d20145bc
PN
252 function upgrade_4_3_beta3($rev) {
253 $this->addTask(ts('Upgrade DB to 4.3.beta3: SQL'), 'task_4_3_x_runSql', $rev);
254 // CRM-12065
255 $query = "SELECT id, form_values FROM civicrm_report_instance WHERE form_values LIKE '%contribution_type%'";
256 $this->addTask('Replace contribution_type to financial_type in table civicrm_report_instance', 'replaceContributionTypeId', $query, 'reportInstance');
257 $query = "SELECT * FROM civicrm_saved_search WHERE form_values LIKE '%contribution_type%'";
258 $this->addTask('Replace contribution_type to financial_type in table civicrm_saved_search', 'replaceContributionTypeId', $query, 'savedSearch');
259 }
558ccc27
DL
260
261 function upgrade_4_3_beta4($rev) {
262 $this->addTask(ts('Upgrade DB to 4.3.beta4: SQL'), 'task_4_3_x_runSql', $rev);
b676923b
PN
263 // add indexes for civicrm_entity_financial_trxn
264 // CRM-12141
265 $this->addTask(ts('Check/Add indexes for civicrm_entity_financial_trxn'), 'task_4_3_x_checkIndexes', $rev);
558ccc27
DL
266 }
267
ab00f69d 268 function upgrade_4_3_beta5($rev) {
ab00f69d
DL
269 // CRM-12205
270 if (
271 CRM_Core_DAO::checkTableExists('log_civicrm_financial_trxn') &&
272 CRM_Core_DAO::checkFieldExists('log_civicrm_financial_trxn', 'trxn_id')
273 ) {
274 CRM_Core_DAO::executeQuery('ALTER TABLE `log_civicrm_financial_trxn` CHANGE `trxn_id` `trxn_id` VARCHAR(255) NULL DEFAULT NULL');
275 }
35fe5ae1
DG
276 // CRM-12142 - some sites didn't get this column added yet, and sites which installed 4.3 from scratch will already have it
277 if (
278 !CRM_Core_DAO::checkFieldExists('civicrm_premiums', 'premiums_nothankyou_label')
279 ) {
22bf3365
DL
280 $query = "
281ALTER TABLE civicrm_premiums
282ADD COLUMN premiums_nothankyou_label varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL
283 COMMENT 'Label displayed for No Thank-you option in premiums block (e.g. No thank you)'
284";
285 CRM_Core_DAO::executeQuery($query);
286 }
35fe5ae1 287 $this->addTask(ts('Upgrade DB to 4.3.beta5: SQL'), 'task_4_3_x_runSql', $rev);
ab00f69d
DL
288 }
289
6a488035
TO
290 //CRM-11636
291 function assignFinancialTypeToPriceRecords() {
292 $upgrade = new CRM_Upgrade_Form();
293 //here we update price set entries
22bf3365
DL
294 $sqlFinancialIds = "
295SELECT id, name
296FROM civicrm_financial_type
297WHERE name IN ('Donation', 'Event Fee', 'Member Dues');
298";
6a488035
TO
299 $daoFinancialIds = CRM_Core_DAO::executeQuery($sqlFinancialIds);
300 while($daoFinancialIds->fetch()) {
301 $financialIds[$daoFinancialIds->name] = $daoFinancialIds->id;
302 }
22bf3365
DL
303 $sqlPriceSetUpdate = "
304UPDATE civicrm_price_set ps
305SET ps.financial_type_id =
306 CASE
6a488035
TO
307 WHEN ps.extends LIKE '%1%' THEN {$financialIds['Event Fee']}
308 WHEN ps.extends LIKE '2' THEN {$financialIds['Donation']}
309 WHEN ps.extends LIKE '3' THEN {$financialIds['Member Dues']}
310 END
22bf3365
DL
311WHERE financial_type_id IS NULL
312";
6a488035
TO
313 CRM_Core_DAO::executeQuery($sqlPriceSetUpdate);
314
315 //here we update price field value rows
22bf3365
DL
316 $sqlPriceFieldValueUpdate = "
317UPDATE civicrm_price_field_value pfv
318LEFT JOIN civicrm_membership_type mt ON (pfv.membership_type_id = mt.id)
319INNER JOIN civicrm_price_field pf ON (pfv.price_field_id = pf.id)
320INNER JOIN civicrm_price_set ps ON (pf.price_set_id = ps.id)
321 SET pfv.financial_type_id =
322 CASE
323 WHEN pfv.membership_type_id IS NOT NULL THEN mt.financial_type_id
324 WHEN pfv.membership_type_id IS NULL THEN ps.financial_type_id
325 END
326";
6a488035 327 CRM_Core_DAO::executeQuery($sqlPriceFieldValueUpdate);
c28241be 328
6a488035
TO
329 return TRUE;
330 }
c28241be 331
6a488035
TO
332 static function _checkAndMigrateDefaultFinancialTypes() {
333 $modifiedDefaults = FALSE;
334 //insert types if not exists
22bf3365
DL
335 $sqlFetchTypes = "
336SELECT id, name
337FROM civicrm_contribution_type
338WHERE name IN ('Donation', 'Event Fee', 'Member Dues') AND is_active =1
339";
6a488035
TO
340 $daoFetchTypes = CRM_Core_DAO::executeQuery($sqlFetchTypes);
341
342 if ($daoFetchTypes->N < 3) {
343 $modifiedDefaults = TRUE;
c28241be 344 $insertStatments = array (
6a488035
TO
345 'Donation' => "('Donation', 0, 1, 1)",
346 'Member' => "('Member Dues', 0, 1, 1)",
347 'Event Fee' => "('Event Fee', 0, 1, 0)",
348 );
349 foreach ($insertStatments as $values) {
22bf3365
DL
350 $query = "
351INSERT INTO civicrm_contribution_type (name, is_reserved, is_active, is_deductible)
352VALUES $values
353ON DUPLICATE KEY UPDATE is_active = 1
354";
6a488035 355 CRM_Core_DAO::executeQuery($query);
c28241be 356 }
6a488035
TO
357 }
358 return $modifiedDefaults;
359 }
c28241be 360
6a488035
TO
361 function createFinancialRecords() {
362 $upgrade = new CRM_Upgrade_Form();
363
364 // update civicrm_entity_financial_trxn.amount = civicrm_financial_trxn.total_amount
22bf3365
DL
365 $query = "
366UPDATE civicrm_entity_financial_trxn ceft
367LEFT JOIN civicrm_financial_trxn cft ON cft.id = ceft.financial_trxn_id
368SET ceft.amount = total_amount
369WHERE cft.net_amount IS NOT NULL
370AND ceft.entity_table = 'civicrm_contribution'
371";
6a488035 372 CRM_Core_DAO::executeQuery($query);
c28241be 373
6a488035
TO
374 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
375 $completedStatus = array_search('Completed', $contributionStatus);
376 $pendingStatus = array_search('Pending', $contributionStatus);
377 $cancelledStatus = array_search('Cancelled', $contributionStatus);
378 $queryParams = array(
379 1 => array($completedStatus, 'Integer'),
380 2 => array($pendingStatus, 'Integer'),
381 3 => array($cancelledStatus, 'Integer')
382 );
c28241be 383
6a488035
TO
384 $accountType = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name = 'Asset' "));
385 $financialAccountId =
22bf3365
DL
386 $query = "
387SELECT id
388FROM civicrm_financial_account
389WHERE is_default = 1
390AND financial_account_type_id = {$accountType}
391";
392 CRM_Core_DAO::singleValueQuery($query);
c28241be 393
6a488035 394 $accountRelationsips = CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL);
c28241be 395
6a488035
TO
396 $accountsReceivableAccount = array_search('Accounts Receivable Account is', $accountRelationsips);
397 $incomeAccountIs = array_search('Income Account is', $accountRelationsips);
398 $assetAccountIs = array_search('Asset Account is', $accountRelationsips);
399 $expenseAccountIs = array_search('Expense Account is', $accountRelationsips);
c28241be 400
6a488035
TO
401 $financialItemStatus = CRM_Core_PseudoConstant::accountOptionValues('financial_item_status');
402 $unpaidStatus = array_search('Unpaid', $financialItemStatus);
403 $paidStatus = array_search('Paid', $financialItemStatus);
c28241be 404
6a488035
TO
405 $validCurrencyCodes = CRM_Core_PseudoConstant::currencyCode();
406 $validCurrencyCodes = implode("','", $validCurrencyCodes);
407 $config = CRM_Core_Config::singleton();
408 $defaultCurrency = $config->defaultCurrency;
409 $now = date( 'YmdHis' );
410
411 //adding financial_trxn records and entity_financial_trxn records related to contribution
412 //Add temp column for easy entry in entity_financial_trxn
413 $sql = "ALTER TABLE civicrm_financial_trxn ADD COLUMN contribution_id INT DEFAULT NULL";
414 CRM_Core_DAO::executeQuery($sql);
c28241be
DL
415
416 //pending pay later status handling
6a488035
TO
417 $sql = "
418INSERT INTO civicrm_financial_trxn
419 (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id,
420 check_number, to_financial_account_id, from_financial_account_id, trxn_date)
22bf3365
DL
421SELECT con.id as contribution_id, con.payment_instrument_id,
422 IF(con.currency IN ('{$validCurrencyCodes}'), con.currency, '{$defaultCurrency}') as currency,
423 con.total_amount, con.net_amount, con.fee_amount, con.trxn_id, con.contribution_status_id,
424 con.check_number, efa.financial_account_id as to_financial_account_id, NULL as from_financial_account_id,
6a488035 425 REPLACE(REPLACE(REPLACE(
c28241be
DL
426 CASE
427 WHEN con.receive_date IS NOT NULL THEN
6a488035 428 con.receive_date
c28241be 429 WHEN con.receipt_date IS NOT NULL THEN
6a488035
TO
430 con.receipt_date
431 ELSE
c28241be 432 {$now}
6a488035
TO
433 END
434 , '-', ''), ':', ''), ' ', '') as trxn_date
435FROM civicrm_contribution con
c28241be 436 LEFT JOIN civicrm_entity_financial_account efa
6a488035
TO
437 ON (con.financial_type_id = efa.entity_id AND efa.entity_table = 'civicrm_financial_type'
438 AND efa.account_relationship = {$accountsReceivableAccount})
22bf3365
DL
439WHERE con.is_pay_later = 1
440AND con.contribution_status_id = {$pendingStatus}
441";
6a488035 442 CRM_Core_DAO::executeQuery($sql);
c28241be 443
6a488035
TO
444 //create a temp table to hold financial account id related to payment instruments
445 $tempTableName1 = CRM_Core_DAO::createTempTableName();
c28241be 446
22bf3365
DL
447 $sql = "CREATE TEMPORARY TABLE {$tempTableName1}";
448 CRM_Core_DAO::executeQuery($sql);
6a488035 449
22bf3365
DL
450 $sql = "
451SELECT ceft.financial_account_id financial_account_id, cov.value as instrument_id
452FROM civicrm_entity_financial_account ceft
453INNER JOIN civicrm_option_value cov ON cov.id = ceft.entity_id AND ceft.entity_table = 'civicrm_option_value'
454INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
455WHERE cog.name = 'payment_instrument'";
6a488035 456 CRM_Core_DAO::executeQuery($sql);
22bf3365 457
b676923b
PN
458 //CRM-12141
459 $sql = "ALTER TABLE {$tempTableName1} ADD INDEX index_instrument_id (instrument_id);";
460 CRM_Core_DAO::executeQuery($sql);
6a488035 461
c28241be 462 //create temp table to process completed / cancelled contribution
6a488035 463 $tempTableName2 = CRM_Core_DAO::createTempTableName();
22bf3365
DL
464 $sql = "CREATE TEMPORARY TABLE {$tempTableName2}";
465 CRM_Core_DAO::executeQuery($sql);
6a488035 466
22bf3365
DL
467 $sql = "
468SELECT con.id as contribution_id, con.payment_instrument_id,
469 IF(con.currency IN ('{$validCurrencyCodes}'), con.currency, '{$defaultCurrency}') as currency,
470 con.total_amount, con.net_amount, con.fee_amount, con.trxn_id, con.contribution_status_id,
471 con.check_number, NULL as from_financial_account_id,
c28241be
DL
472 REPLACE(REPLACE(REPLACE(
473 CASE
474 WHEN con.receive_date IS NOT NULL THEN
6a488035 475 con.receive_date
c28241be 476 WHEN con.receipt_date IS NOT NULL THEN
6a488035
TO
477 con.receipt_date
478 ELSE
c28241be 479 {$now}
6a488035
TO
480 END
481 , '-', ''), ':', ''), ' ', '') as trxn_date,
c28241be 482 CASE
6a488035
TO
483 WHEN con.payment_instrument_id IS NULL THEN
484 {$financialAccountId}
485 WHEN con.payment_instrument_id IS NOT NULL THEN
486 tpi.financial_account_id
487 END as to_financial_account_id,
488 IF(eft.financial_trxn_id IS NULL, 'insert', eft.financial_trxn_id) as action
22bf3365
DL
489FROM civicrm_contribution con
490LEFT JOIN civicrm_entity_financial_trxn eft
491 ON (eft.entity_table = 'civicrm_contribution' AND eft.entity_id = con.id)
492LEFT JOIN {$tempTableName1} tpi
493 ON con.payment_instrument_id = tpi.instrument_id
494WHERE con.contribution_status_id IN ({$completedStatus}, {$cancelledStatus})
495";
6a488035 496 CRM_Core_DAO::executeQuery($sql);
22bf3365 497
b676923b
PN
498 // CRM-12141
499 $sql = "ALTER TABLE {$tempTableName2} ADD INDEX index_action (action);";
500 CRM_Core_DAO::executeQuery($sql);
c28241be 501
6a488035
TO
502 //handling for completed contribution and cancelled contribution
503 //insertion of new records
504 $sql = "
c28241be 505INSERT INTO civicrm_financial_trxn
6a488035 506 (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id, check_number,
c28241be 507 to_financial_account_id, from_financial_account_id, trxn_date)
6a488035
TO
508SELECT tempI.contribution_id, tempI.payment_instrument_id, tempI.currency, tempI.total_amount, tempI.net_amount,
509 tempI.fee_amount, tempI.trxn_id, tempI.contribution_status_id, tempI.check_number,
c28241be 510 tempI.to_financial_account_id, tempI.from_financial_account_id, tempI.trxn_date
6a488035
TO
511FROM {$tempTableName2} tempI
512WHERE tempI.action = 'insert';";
513 CRM_Core_DAO::executeQuery($sql);
514
515 //update of existing records
516 $sql = "
517UPDATE civicrm_financial_trxn ft
c28241be 518 INNER JOIN {$tempTableName2} tempU
6a488035
TO
519 ON (tempU.action != 'insert' AND ft.id = tempU.action)
520SET ft.from_financial_account_id = NULL,
521 ft.to_financial_account_id = tempU.to_financial_account_id,
c28241be 522 ft.status_id = tempU.contribution_status_id,
6a488035
TO
523 ft.payment_instrument_id = tempU.payment_instrument_id,
524 ft.check_number = tempU.check_number,
525 ft.contribution_id = tempU.contribution_id;";
526 CRM_Core_DAO::executeQuery($sql);
527
528 //insert the -ve transaction rows for cancelled contributions
529 $sql = "
530INSERT INTO civicrm_financial_trxn
c28241be
DL
531 (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id,
532 check_number, to_financial_account_id, from_financial_account_id, trxn_date)
533SELECT ft.contribution_id, ft.payment_instrument_id, ft.currency, -ft.total_amount, ft.net_amount, ft.fee_amount, ft.trxn_id,
6a488035 534 ft.status_id, ft.check_number, ft.to_financial_account_id, ft.from_financial_account_id, ft.trxn_date
c28241be 535FROM civicrm_financial_trxn ft
6a488035
TO
536WHERE ft.status_id = {$cancelledStatus};";
537 CRM_Core_DAO::executeQuery($sql);
538
539 //inserting entity financial trxn entries if its not present in entity_financial_trxn for completed and pending contribution statuses
540 //this also handles +ve and -ve both transaction entries for a cancelled contribution
541 $sql = "
542INSERT INTO civicrm_entity_financial_trxn (entity_table, entity_id, financial_trxn_id, amount)
543SELECT 'civicrm_contribution', ft.contribution_id, ft.id, ft.total_amount as amount
544FROM civicrm_financial_trxn ft
c28241be
DL
545WHERE contribution_id IS NOT NULL AND
546 ft.id NOT IN (SELECT financial_trxn_id
547 FROM civicrm_entity_financial_trxn
6a488035
TO
548 WHERE entity_table = 'civicrm_contribution'
549 AND entity_id = ft.contribution_id)";
550 CRM_Core_DAO::executeQuery($sql);
551 //end of adding financial_trxn records and entity_financial_trxn records related to contribution
552
553 //update all linked line_item rows
554 // set line_item.financial_type_id = contribution.financial_type_id if contribution page id is null and not participant line item
555 // set line_item.financial_type_id = price_field_value.financial_type_id if contribution page id is set and not participant line item
556 // set line_item.financial_type_id = event.financial_type_id if its participant line item and line_item.price_field_value_id is null
557 // 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
558 $updateLineItemSql = "
559UPDATE civicrm_line_item li
560 LEFT JOIN civicrm_contribution con
561 ON (li.entity_id = con.id AND li.entity_table = 'civicrm_contribution')
562 LEFT JOIN civicrm_price_field_value cpfv
563 ON li.price_field_value_id = cpfv.id
564 LEFT JOIN civicrm_participant cp
565 ON (li.entity_id = cp.id AND li.entity_table = 'civicrm_participant')
566 LEFT JOIN civicrm_event ce
c28241be 567 ON ce.id = cp.event_id
6a488035 568SET li.financial_type_id = CASE
c28241be 569 WHEN (con.contribution_page_id IS NULL || li.price_field_value_id IS NULL) AND cp.id IS NULL THEN
6a488035
TO
570 con.financial_type_id
571 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
572 cpfv.financial_type_id
c28241be 573 WHEN cp.id IS NOT NULL AND li.price_field_value_id IS NULL THEN
6a488035
TO
574 ce.financial_type_id
575 END";
576 CRM_Core_DAO::executeQuery($updateLineItemSql, $queryParams);
c28241be
DL
577
578 //add the financial_item entries
6a488035
TO
579 //add a temp column so that inserting entity_financial_trxn entries gets easy
580 $sql = "ALTER TABLE civicrm_financial_item ADD COLUMN f_trxn_id INT DEFAULT NULL";
581 CRM_Core_DAO::executeQuery($sql);
c28241be 582
6a488035
TO
583 //add financial_item entries for contribution completed / pending pay later / cancelled
584 $contributionlineItemSql = "
c28241be 585INSERT INTO civicrm_financial_item
6a488035
TO
586 (transaction_date, contact_id, amount, currency, entity_table, entity_id, description, status_id, financial_account_id, f_trxn_id)
587
588SELECT REPLACE(REPLACE(REPLACE(ft.trxn_date, '-', ''), ':', ''), ' ', ''), con.contact_id,
c28241be 589 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
590 li.id as line_item_id, li.label as line_item_label,
591 IF(con.contribution_status_id = {$pendingStatus}, {$unpaidStatus}, {$paidStatus}) as status_id, efa.financial_account_id as financial_account_id,
592 ft.id as f_trxn_id
593FROM civicrm_line_item li
c28241be 594 INNER JOIN civicrm_contribution con
6a488035
TO
595 ON (li.entity_id = con.id AND li.entity_table = 'civicrm_contribution')
596 INNER JOIN civicrm_financial_trxn ft
597 ON (con.id = ft.contribution_id)
598 LEFT JOIN civicrm_entity_financial_account efa
599 ON (li.financial_type_id = efa.entity_id AND efa.entity_table = 'civicrm_financial_type'
600 AND efa.account_relationship = {$incomeAccountIs})
601WHERE con.contribution_status_id IN (%1, %3) OR (con.is_pay_later = 1 AND con.contribution_status_id = %2)";
602 CRM_Core_DAO::executeQuery($contributionlineItemSql, $queryParams);
c28241be 603
6a488035
TO
604 //add financial_item entries for event
605 $participantLineItemSql = "
c28241be 606INSERT INTO civicrm_financial_item
6a488035
TO
607 (transaction_date, contact_id, amount, currency, entity_table, entity_id, description, status_id, financial_account_id, f_trxn_id)
608
609SELECT REPLACE(REPLACE(REPLACE(ft.trxn_date, '-', ''), ':', ''), ' ', ''), con.contact_id,
610 IF(ft.total_amount < 0 AND con.contribution_status_id = %3, -li.line_total, li.line_total) as line_total,
c28241be 611 con.currency, 'civicrm_line_item', li.id as line_item_id, li.label as line_item_label,
6a488035
TO
612 IF(con.contribution_status_id = {$pendingStatus}, {$unpaidStatus}, {$paidStatus}) as status_id,
613 efa.financial_account_id as financial_account_id, ft.id as f_trxn_id
614FROM civicrm_line_item li
615 INNER JOIN civicrm_participant par
616 ON (li.entity_id = par.id AND li.entity_table = 'civicrm_participant')
c28241be
DL
617 INNER JOIN civicrm_participant_payment pp
618 ON (pp.participant_id = par.id)
6a488035
TO
619 INNER JOIN civicrm_contribution con
620 ON (pp.contribution_id = con.id)
c28241be 621 INNER JOIN civicrm_financial_trxn ft
6a488035
TO
622 ON (con.id = ft.contribution_id)
623 LEFT JOIN civicrm_entity_financial_account efa
624 ON (li.financial_type_id = efa.entity_id AND
625 efa.entity_table = 'civicrm_financial_type' AND efa.account_relationship = {$incomeAccountIs})
626WHERE con.contribution_status_id IN (%1, %3) OR (con.is_pay_later = 1 AND con.contribution_status_id = %2)";
627 CRM_Core_DAO::executeQuery($participantLineItemSql, $queryParams);
c28241be 628
6a488035
TO
629 //fee handling for contributions
630 //insert fee entries in financial_trxn for contributions
631 $sql = "ALTER TABLE civicrm_financial_trxn ADD COLUMN is_fee TINYINT DEFAULT NULL";
632 CRM_Core_DAO::executeQuery($sql);
c28241be 633
6a488035 634 $sql = "
c28241be 635INSERT INTO civicrm_financial_trxn
6a488035
TO
636 (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id, check_number,
637 to_financial_account_id, from_financial_account_id, trxn_date, payment_processor_id, is_fee)
638
639SELECT con.id, ft.payment_instrument_id, ft.currency, ft.fee_amount, NULL, NULL, ft.trxn_id, %1 as status_id,
640 ft.check_number, efaFT.financial_account_id as to_financial_account_id, CASE
641 WHEN efaPP.financial_account_id IS NOT NULL THEN
642 efaPP.financial_account_id
643 WHEN tpi.financial_account_id IS NOT NULL THEN
c28241be
DL
644 tpi.financial_account_id
645 ELSE
646 {$financialAccountId}
6a488035
TO
647 END as from_financial_account_id, ft.trxn_date, ft.payment_processor_id, 1 as is_fee
648FROM civicrm_contribution con
649 INNER JOIN civicrm_financial_trxn ft
650 ON (ft.contribution_id = con.id)
651 LEFT JOIN civicrm_entity_financial_account efaFT
652 ON (con.financial_type_id = efaFT.entity_id AND efaFT.entity_table = 'civicrm_financial_type'
653 AND efaFT.account_relationship = {$expenseAccountIs})
c28241be 654 LEFT JOIN civicrm_entity_financial_account efaPP
6a488035
TO
655 ON (ft.payment_processor_id = efaPP.entity_id AND efaPP.entity_table = 'civicrm_payment_processor'
656 AND efaPP.account_relationship = {$assetAccountIs})
c28241be 657 LEFT JOIN {$tempTableName1} tpi
6a488035 658 ON ft.payment_instrument_id = tpi.instrument_id
368d2a88 659WHERE 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
660GROUP BY con.id";
661 CRM_Core_DAO::executeQuery($sql, $queryParams);
662
c28241be 663 //link financial_trxn to contribution
6a488035
TO
664 $sql = "
665INSERT INTO civicrm_entity_financial_trxn
666 (entity_table, entity_id, financial_trxn_id, amount)
667SELECT 'civicrm_contribution', ft.contribution_id, ft.id, ft.total_amount
668FROM civicrm_financial_trxn ft
669WHERE ft.is_fee = 1";
670 CRM_Core_DAO::executeQuery($sql);
c28241be 671
6a488035
TO
672 //add fee related entries to financial item table
673 $domainId = CRM_Core_Config::domainID();
674 $domainContactId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id');
675 $sql = "
c28241be 676INSERT INTO civicrm_financial_item
6a488035 677 (transaction_date, contact_id, amount, currency, entity_table, entity_id, description, status_id, financial_account_id, f_trxn_id)
c28241be 678SELECT ft.trxn_date, {$domainContactId} as contact_id, ft.total_amount, ft.currency, 'civicrm_financial_trxn', ft.id,
6a488035 679 'Fee', {$paidStatus} as status_id, ft.to_financial_account_id as financial_account_id, ft.id as f_trxn_id
c28241be 680FROM civicrm_financial_trxn ft
6a488035
TO
681WHERE ft.is_fee = 1;";
682 CRM_Core_DAO::executeQuery($sql);
c28241be 683
6a488035
TO
684 //add entries to entity_financial_trxn table
685 $sql = "
686INSERT INTO civicrm_entity_financial_trxn (entity_table, entity_id, financial_trxn_id, amount)
687SELECT 'civicrm_financial_item' as entity_table, fi.id as entity_id, fi.f_trxn_id as financial_trxn_id, fi.amount
688FROM civicrm_financial_item fi";
689 CRM_Core_DAO::executeQuery($sql);
690
691 //drop the temparory columns
692 $sql = "ALTER TABLE civicrm_financial_trxn
693 DROP COLUMN contribution_id,
694 DROP COLUMN is_fee;";
695 CRM_Core_DAO::executeQuery($sql);
696
697 $sql = "ALTER TABLE civicrm_financial_item DROP f_trxn_id";
698 CRM_Core_DAO::executeQuery($sql);
c28241be 699
6a488035
TO
700 return TRUE;
701 }
702
703 function createDomainContacts() {
704 $domainParams = $context = array();
705 $query = "
22bf3365
DL
706ALTER 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',
707 ADD CONSTRAINT FK_civicrm_domain_contact_id FOREIGN KEY (contact_id) REFERENCES civicrm_contact(id);";
6a488035 708 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
c28241be 709
22bf3365
DL
710 $query = '
711SELECT cd.id, cd.name, ce.email FROM civicrm_domain cd
6a488035 712LEFT JOIN civicrm_loc_block clb ON clb.id = cd. loc_block_id
22bf3365
DL
713LEFT JOIN civicrm_email ce ON ce.id = clb.email_id ;
714' ;
6a488035
TO
715 $dao = CRM_Core_DAO::executeQuery($query);
716 while($dao->fetch()) {
717 $params = array(
718 'sort_name' => $dao->name,
719 'display_name' => $dao->name,
720 'legal_name' => $dao->name,
721 'organization_name' => $dao->name,
722 'contact_type' => 'Organization'
723 );
22bf3365
DL
724 $query = "
725SELECT cc.id FROM civicrm_contact cc
6a488035 726LEFT JOIN civicrm_email ce ON ce.contact_id = cc.id
22bf3365
DL
727WHERE cc.contact_type = 'Organization' AND cc.organization_name = %1
728";
729 $params = array(1 => array($dao->name, 'String'));
6a488035 730 if ($dao->email) {
22bf3365
DL
731 $query .= " AND ce.email = %2 ";
732 $params[2] = array($dao->email, 'String');
6a488035 733 }
22bf3365 734 $contactID = CRM_Core_DAO::singleValueQuery($query, $params);
6a488035
TO
735 $context[1] = $dao->name;
736 if (empty($contactID)) {
737 $contact = CRM_Contact_BAO_Contact::add($params);
738 $contactID = $contact->id;
739 $context[0] = 'added';
c28241be 740 }
6a488035
TO
741 else {
742 $context[0] = 'merged';
743 }
744 $domainParams['contact_id'] = $contactID;
745 CRM_Core_BAO_Domain::edit($domainParams, $dao->id);
746 }
747 return $context;
748 }
749
750 function task_4_3_alpha1_checkDBConstraints() {
751 //checking whether the foreign key exists before dropping it CRM-11260
752 $config = CRM_Core_Config::singleton();
753 $dbUf = DB::parseDSN($config->dsn);
6a488035
TO
754 $tables = array(
755 'autorenewal_msg_id' => array('tableName' => 'civicrm_membership_type', 'fkey' => 'FK_civicrm_membership_autorenewal_msg_id'),
756 'to_account_id' => array('tableName' => 'civicrm_financial_trxn', 'constraintName' => 'civicrm_financial_trxn_ibfk_2'),
757 'from_account_id' => array('tableName' => 'civicrm_financial_trxn', 'constraintName' => 'civicrm_financial_trxn_ibfk_1'),
758 'contribution_type_id' => array('tableName' => 'civicrm_contribution_recur', 'fkey' => 'FK_civicrm_contribution_recur_contribution_type_id'),
759 );
22bf3365
DL
760 $query = "
761SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
6a488035
TO
762WHERE table_name = 'civicrm_contribution_recur'
763AND constraint_name = 'FK_civicrm_contribution_recur_contribution_type_id'
22bf3365
DL
764AND TABLE_SCHEMA = %1
765";
766 $params = array(1 => array($dbUf['database'], 'String'));
6a488035
TO
767 $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, FALSE);
768 foreach($tables as $columnName => $value){
769 if ($value['tableName'] == 'civicrm_membership_type' || $value['tableName'] == 'civicrm_contribution_recur') {
770 $foreignKeyExists = CRM_Core_DAO::checkConstraintExists($value['tableName'], $value['fkey']);
771 $fKey = $value['fkey'];
772 } else {
773 $foreignKeyExists = CRM_Core_DAO::checkFKConstraintInFormat($value['tableName'], $columnName);
774 $fKey = "`FK_{$value['tableName']}_{$columnName}`";
775 }
776 if ($foreignKeyExists || $value['tableName'] == 'civicrm_financial_trxn') {
777 if ($value['tableName'] != 'civicrm_contribution_recur' || ($value['tableName'] == 'civicrm_contribution_recur' && $dao->N)) {
778 $constraintName = $foreignKeyExists ? $fKey : $value['constraintName'];
22bf3365
DL
779 $query = "ALTER TABLE {$value['tableName']} DROP FOREIGN KEY {$constraintName}";
780 CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, FALSE);
6a488035 781 }
22bf3365
DL
782 $query = "ALTER TABLE {$value['tableName']} DROP INDEX {$fKey}";
783 CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, FALSE);
6a488035
TO
784 }
785 }
786 // check if column contact_id is present or not in civicrm_financial_account
787 $fieldExists = CRM_Core_DAO::checkFieldExists('civicrm_financial_account', 'contact_id', FALSE);
788 if (!$fieldExists) {
22bf3365
DL
789 $query = "
790ALTER TABLE civicrm_financial_account
791 ADD contact_id int(10) unsigned DEFAULT NULL COMMENT 'Version identifier of financial_type' AFTER name,
792 ADD CONSTRAINT FK_civicrm_financial_account_contact_id FOREIGN KEY (contact_id) REFERENCES civicrm_contact(id);
793";
6a488035
TO
794 CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, FALSE);
795 }
796 }
797
798 /**
799 * Read creation and modification times from civicrm_log; add
800 * them to civicrm_contact.
801 */
802 function convertTimestamps(CRM_Queue_TaskContext $ctx, $startId, $endId) {
803 $sql = "
804 SELECT entity_id, min(modified_date) AS created, max(modified_date) AS modified
805 FROM civicrm_log
806 WHERE entity_table = 'civicrm_contact'
807 AND entity_id BETWEEN %1 AND %2
808 GROUP BY entity_id
809 ";
810 $params = array(
811 1 => array($startId, 'Integer'),
812 2 => array($endId, 'Integer'),
813 );
814 $dao = CRM_Core_DAO::executeQuery($sql, $params);
815 while ($dao->fetch()) {
816 // FIXME civicrm_log.modified_date is DATETIME; civicrm_contact.modified_date is TIMESTAMP
817 CRM_Core_DAO::executeQuery(
818 'UPDATE civicrm_contact SET created_date = %1, modified_date = %2 WHERE id = %3',
819 array(
820 1 => array($dao->created, 'String'),
821 2 => array($dao->modified, 'String'),
822 3 => array($dao->entity_id, 'Integer'),
823 )
824 );
825 }
826
827 return TRUE;
828 }
829
d20145bc
PN
830 /**
831 * replace contribution_type to financial_type in table
832 * civicrm_saved_search and Structure civicrm_report_instance
833 */
834 function replaceContributionTypeId(CRM_Queue_TaskContext $ctx, $query, $table) {
835 $dao = CRM_Core_DAO::executeQuery($query);
836 while ($dao->fetch()) {
837 $formValues = unserialize($dao->form_values);
838 foreach (array('contribution_type_id_op', 'contribution_type_id_value', 'contribution_type_id') as $value) {
839 if (array_key_exists($value, $formValues)) {
840 $key = preg_replace('/contribution/', 'financial', $value);
841 $formValues[$key] = $formValues[$value];
842 unset($formValues[$value]);
843 }
844 }
845 if ($table != 'savedSearch') {
846 foreach (array('fields', 'group_bys') as $value) {
847 if (array_key_exists($value, $formValues)) {
848 if (array_key_exists('contribution_type_id', $formValues[$value])) {
849 $formValues[$value]['financial_type_id'] = $formValues[$value]['contribution_type_id'];
850 unset($formValues[$value]['contribution_type_id']);
851 }
852 else if (array_key_exists('contribution_type', $formValues[$value])) {
853 $formValues[$value]['financial_type'] = $formValues[$value]['contribution_type'];
854 unset($formValues[$value]['contribution_type']);
855 }
856 }
857 }
858 if (array_key_exists('order_bys', $formValues)) {
859 foreach ($formValues['order_bys'] as $key => $values) {
860 if (preg_grep('/contribution_type/', $values)) {
861 $formValues['order_bys'][$key]['column'] = preg_replace('/contribution_type/', 'financial_type', $values['column']);
862 }
863 }
864 }
865 }
866
867 if ($table == 'savedSearch') {
868 $saveDao = new CRM_Contact_DAO_SavedSearch();
869 }
870 else {
558ccc27 871 $saveDao = new CRM_Report_DAO_Instance();
d20145bc
PN
872 }
873 $saveDao->id = $dao->id;
874
875 if ($table == 'savedSearch') {
558ccc27 876 if (array_key_exists('mapper', $formValues)) {
d20145bc
PN
877 foreach ($formValues['mapper'] as $key => $values) {
878 foreach ($values as $k => $v) {
879 if (preg_grep('/contribution_/', $v)) {
880 $formValues['mapper'][$key][$k] = preg_replace('/contribution_type/', 'financial_type', $v);
881 }
882 }
883 }
884 }
885 foreach (array('select_tables', 'where_tables') as $value) {
886 if (preg_match('/contribution_type/', $dao->$value)) {
887 $tempValue = unserialize($dao->$value);
888 if (array_key_exists('civicrm_contribution_type', $tempValue)) {
889 $tempValue['civicrm_financial_type'] = $tempValue['civicrm_contribution_type'];
890 unset($tempValue['civicrm_contribution_type']);
891 }
892 $saveDao->$value = serialize($tempValue);
893 }
894 }
895 if (preg_match('/contribution_type/', $dao->where_clause)) {
896 $saveDao->where_clause = preg_replace('/contribution_type/', 'financial_type', $dao->where_clause);
558ccc27 897 }
d20145bc
PN
898 }
899 $saveDao->form_values = serialize($formValues);
900
901 $saveDao->save();
902 }
903 return TRUE;
904 }
905
b676923b
PN
906 /**
907 * Check/Add INDEX CRM-12141
908 *
909 * @return bool TRUE for success
910 */
911 function task_4_3_x_checkIndexes(CRM_Queue_TaskContext $ctx) {
22bf3365
DL
912 $query = "
913SHOW KEYS
914FROM civicrm_entity_financial_trxn
915WHERE key_name IN ('UI_entity_financial_trxn_entity_table', 'UI_entity_financial_trxn_entity_id')
916";
b676923b
PN
917 $dao = CRM_Core_DAO::executeQuery($query);
918 if (!$dao->N) {
22bf3365
DL
919 $query = "
920ALTER TABLE civicrm_entity_financial_trxn
b676923b 921ADD INDEX UI_entity_financial_trxn_entity_table (entity_table),
22bf3365
DL
922ADD INDEX UI_entity_financial_trxn_entity_id (entity_id);
923";
924 CRM_Core_DAO::executeQuery($query);
b676923b
PN
925 }
926 return TRUE;
927 }
928
6a488035
TO
929 /**
930 * Update phones CRM-11292
931 *
932 * @return bool TRUE for success
933 */
934 static function phoneNumeric(CRM_Queue_TaskContext $ctx) {
935 CRM_Core_DAO::executeQuery(CRM_Contact_BAO_Contact::DROP_STRIP_FUNCTION_43);
936 CRM_Core_DAO::executeQuery(CRM_Contact_BAO_Contact::CREATE_STRIP_FUNCTION_43);
937 CRM_Core_DAO::executeQuery("UPDATE civicrm_phone SET phone_numeric = civicrm_strip_non_numeric(phone)");
938 return TRUE;
939 }
940
941 /**
942 * (Queue Task Callback)
943 */
944 static function task_4_3_x_runSql(CRM_Queue_TaskContext $ctx, $rev) {
945 $upgrade = new CRM_Upgrade_Form();
946 $upgrade->processSQL($rev);
947
948 return TRUE;
949 }
950
951 /**
952 * Syntatic sugar for adding a task which (a) is in this class and (b) has
953 * a high priority.
954 *
955 * After passing the $funcName, you can also pass parameters that will go to
956 * the function. Note that all params must be serializable.
957 */
958 protected function addTask($title, $funcName) {
959 $queue = CRM_Queue_Service::singleton()->load(array(
960 'type' => 'Sql',
961 'name' => CRM_Upgrade_Form::QUEUE_NAME,
962 ));
963
964 $args = func_get_args();
965 $title = array_shift($args);
966 $funcName = array_shift($args);
967 $task = new CRM_Queue_Task(
968 array(get_class($this), $funcName),
969 $args,
970 $title
971 );
972 $queue->createItem($task, array('weight' => -1));
973 }
10a5be27 974}