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