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