Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
7e9e8871 | 4 | | CiviCRM version 4.7 | |
6a488035 | 5 | +--------------------------------------------------------------------+ |
e7112fa7 | 6 | | Copyright CiviCRM LLC (c) 2004-2015 | |
6a488035 TO |
7 | +--------------------------------------------------------------------+ |
8 | | This file is a part of CiviCRM. | | |
9 | | | | |
10 | | CiviCRM is free software; you can copy, modify, and distribute it | | |
11 | | under the terms of the GNU Affero General Public License | | |
12 | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | |
13 | | | | |
14 | | CiviCRM is distributed in the hope that it will be useful, but | | |
15 | | WITHOUT ANY WARRANTY; without even the implied warranty of | | |
16 | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | | |
17 | | See the GNU Affero General Public License for more details. | | |
18 | | | | |
19 | | You should have received a copy of the GNU Affero General Public | | |
20 | | License and the CiviCRM Licensing Exception along | | |
21 | | 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 | +--------------------------------------------------------------------+ | |
d25dd0ee | 26 | */ |
6a488035 TO |
27 | |
28 | /** | |
29 | * | |
30 | * @package CRM | |
e7112fa7 | 31 | * @copyright CiviCRM LLC (c) 2004-2015 |
6a488035 TO |
32 | * $Id$ |
33 | * | |
34 | */ | |
35 | ||
36 | /** | |
748450ad | 37 | * This class contains the functions for Component export |
6a488035 TO |
38 | * |
39 | */ | |
40 | class CRM_Export_BAO_Export { | |
41 | // increase this number a lot to avoid making too many queries | |
42 | // LIMIT is not much faster than a no LIMIT query | |
43 | // CRM-7675 | |
7da04cde | 44 | const EXPORT_ROW_COUNT = 10000; |
6a488035 | 45 | |
f34f5143 SL |
46 | /** |
47 | * Get Querymode based on ExportMode | |
48 | * | |
49 | * @param int $exportMode | |
50 | * Export mode. | |
51 | * | |
748450ad SL |
52 | * @return string $Querymode |
53 | * Query Mode | |
f34f5143 | 54 | */ |
919eddec | 55 | public static function getQueryMode($exportMode) { |
b72702ac SL |
56 | $queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS; |
57 | ||
f34f5143 SL |
58 | switch ($exportMode) { |
59 | case CRM_Export_Form_Select::CONTRIBUTE_EXPORT: | |
60 | $queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE; | |
61 | break; | |
62 | ||
63 | case CRM_Export_Form_Select::EVENT_EXPORT: | |
64 | $queryMode = CRM_Contact_BAO_Query::MODE_EVENT; | |
65 | break; | |
66 | ||
67 | case CRM_Export_Form_Select::MEMBER_EXPORT: | |
68 | $queryMode = CRM_Contact_BAO_Query::MODE_MEMBER; | |
69 | break; | |
70 | ||
71 | case CRM_Export_Form_Select::PLEDGE_EXPORT: | |
72 | $queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE; | |
73 | break; | |
74 | ||
75 | case CRM_Export_Form_Select::CASE_EXPORT: | |
76 | $queryMode = CRM_Contact_BAO_Query::MODE_CASE; | |
77 | break; | |
78 | ||
79 | case CRM_Export_Form_Select::GRANT_EXPORT: | |
80 | $queryMode = CRM_Contact_BAO_Query::MODE_GRANT; | |
81 | break; | |
82 | ||
83 | case CRM_Export_Form_Select::ACTIVITY_EXPORT: | |
84 | $queryMode = CRM_Contact_BAO_Query::MODE_ACTIVITY; | |
85 | break; | |
86 | } | |
87 | return $queryMode; | |
88 | } | |
89 | ||
90 | /** | |
91 | * Get default return property for export based on mode | |
92 | * | |
93 | * @param int $exportMode | |
94 | * Export mode. | |
919eddec | 95 | * |
748450ad SL |
96 | * @return string $property |
97 | * Default Return property | |
f34f5143 | 98 | */ |
2e28a8b9 | 99 | public static function defaultReturnProperty($exportMode) { |
748450ad | 100 | // hack to add default return property based on export mode |
0dc29086 | 101 | $property = NULL; |
f34f5143 | 102 | if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) { |
919eddec | 103 | $property = 'contribution_id'; |
f34f5143 SL |
104 | } |
105 | elseif ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { | |
919eddec | 106 | $property = 'participant_id'; |
f34f5143 SL |
107 | } |
108 | elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) { | |
919eddec | 109 | $property = 'membership_id'; |
f34f5143 SL |
110 | } |
111 | elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) { | |
919eddec | 112 | $property = 'pledge_id'; |
f34f5143 SL |
113 | } |
114 | elseif ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) { | |
919eddec | 115 | $property = 'case_id'; |
f34f5143 SL |
116 | } |
117 | elseif ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT) { | |
919eddec | 118 | $property = 'grant_id'; |
f34f5143 SL |
119 | } |
120 | elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) { | |
919eddec | 121 | $property = 'activity_id'; |
f34f5143 | 122 | } |
919eddec | 123 | return $property; |
f34f5143 SL |
124 | } |
125 | ||
126 | /** | |
127 | * Get Export component | |
128 | * | |
129 | * @param int $exportMode | |
130 | * Export mode. | |
131 | * | |
748450ad SL |
132 | * @return string $component |
133 | * CiviCRM Export Component | |
f34f5143 | 134 | */ |
7bf9f91e | 135 | public static function exportComponent($exportMode) { |
f34f5143 SL |
136 | switch ($exportMode) { |
137 | case CRM_Export_Form_Select::CONTRIBUTE_EXPORT: | |
138 | $component = 'civicrm_contribution'; | |
139 | break; | |
140 | ||
141 | case CRM_Export_Form_Select::EVENT_EXPORT: | |
142 | $component = 'civicrm_participant'; | |
143 | break; | |
144 | ||
145 | case CRM_Export_Form_Select::MEMBER_EXPORT: | |
146 | $component = 'civicrm_membership'; | |
147 | break; | |
148 | ||
149 | case CRM_Export_Form_Select::PLEDGE_EXPORT: | |
150 | $component = 'civicrm_pledge'; | |
151 | break; | |
152 | ||
153 | case CRM_Export_Form_Select::GRANT_EXPORT: | |
154 | $component = 'civicrm_grant'; | |
155 | break; | |
156 | } | |
157 | return $component; | |
158 | } | |
159 | ||
748450ad | 160 | /** |
f1ff3965 | 161 | * Get Query Group By Clause |
748450ad SL |
162 | * @param int $exportMode |
163 | * Export Mode | |
164 | * @param string $queryMode | |
165 | * Query Mode | |
166 | * @param array $returnProperties | |
167 | * Return Properties | |
0cc9927d SL |
168 | * @param object $query |
169 | * CRM_Contact_BAO_Query | |
170 | * | |
748450ad SL |
171 | * @return string $groupBy |
172 | * Group By Clause | |
173 | */ | |
0cc9927d | 174 | public static function getGroupBy($exportMode, $queryMode, $returnProperties, $query) { |
748450ad SL |
175 | if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) || |
176 | CRM_Utils_Array::value('notes', $returnProperties) || | |
177 | // CRM-9552 | |
178 | ($queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy) | |
179 | ) { | |
180 | $groupBy = " GROUP BY contact_a.id"; | |
181 | } | |
182 | ||
183 | switch ($exportMode) { | |
184 | case CRM_Export_Form_Select::CONTRIBUTE_EXPORT: | |
185 | $groupBy = 'GROUP BY civicrm_contribution.id'; | |
186 | if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) { | |
187 | // especial group by when soft credit columns are included | |
188 | $groupBy = 'GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.scredit_id'; | |
189 | } | |
190 | break; | |
191 | ||
192 | case CRM_Export_Form_Select::EVENT_EXPORT: | |
193 | $groupBy = 'GROUP BY civicrm_participant.id'; | |
194 | break; | |
195 | ||
196 | case CRM_Export_Form_Select::MEMBER_EXPORT: | |
197 | $groupBy = " GROUP BY civicrm_membership.id"; | |
198 | break; | |
199 | } | |
200 | ||
201 | if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) { | |
202 | $groupBy = " GROUP BY civicrm_activity.id "; | |
203 | } | |
ee027e3b | 204 | |
0cc9927d | 205 | $groupBy = !empty($groupBy) ? $groupBy : ''; |
ee027e3b | 206 | |
748450ad SL |
207 | return $groupBy; |
208 | } | |
209 | ||
210 | /** | |
211 | * Define extra properties for the export based on query mode | |
212 | * | |
213 | * @param string $queryMode | |
214 | * Query Mode | |
215 | * @return array $extraProperties | |
216 | * Extra Properties | |
217 | */ | |
218 | public static function defineExtraProperties($queryMode) { | |
219 | switch ($queryMode) { | |
220 | case CRM_Contact_BAO_Query::MODE_EVENT: | |
221 | $paymentFields = TRUE; | |
222 | $paymentTableId = 'participant_id'; | |
223 | $extraReturnProperties = array(); | |
224 | break; | |
225 | ||
226 | case CRM_Contact_BAO_Query::MODE_MEMBER: | |
227 | $paymentFields = TRUE; | |
228 | $paymentTableId = 'membership_id'; | |
229 | $extraReturnProperties = array(); | |
230 | break; | |
231 | ||
232 | case CRM_Contact_BAO_Query::MODE_PLEDGE: | |
233 | $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode); | |
234 | $paymentFields = TRUE; | |
235 | $paymentTableId = 'pledge_payment_id'; | |
236 | break; | |
237 | ||
238 | case CRM_Contact_BAO_Query::MODE_CASE: | |
239 | $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode); | |
240 | $paymentFields = FALSE; | |
ee027e3b | 241 | $paymentTableId = ''; |
748450ad SL |
242 | break; |
243 | ||
244 | default: | |
245 | $paymentFields = FALSE; | |
ee027e3b | 246 | $paymentTableId = ''; |
748450ad SL |
247 | $extraReturnProperties = array(); |
248 | } | |
249 | $extraProperties = array( | |
250 | 'paymentFields' => $paymentFields, | |
ee027e3b | 251 | 'paymentTableId' => $paymentTableId, |
748450ad SL |
252 | 'extraReturnProperties' => $extraReturnProperties, |
253 | ); | |
254 | return $extraProperties; | |
255 | } | |
256 | ||
6a488035 | 257 | /** |
fe482240 | 258 | * Get the list the export fields. |
6a488035 | 259 | * |
b9add4b3 TO |
260 | * @param int $selectAll |
261 | * User preference while export. | |
262 | * @param array $ids | |
263 | * Contact ids. | |
264 | * @param array $params | |
265 | * Associated array of fields. | |
266 | * @param string $order | |
267 | * Order by clause. | |
268 | * @param array $fields | |
269 | * Associated array of fields. | |
270 | * @param array $moreReturnProperties | |
271 | * Additional return fields. | |
272 | * @param int $exportMode | |
273 | * Export mode. | |
274 | * @param string $componentClause | |
275 | * Component clause. | |
276 | * @param string $componentTable | |
277 | * Component table. | |
278 | * @param bool $mergeSameAddress | |
279 | * Merge records if they have same address. | |
280 | * @param bool $mergeSameHousehold | |
281 | * Merge records if they belong to the same household. | |
6c8f6e67 EM |
282 | * |
283 | * @param array $exportParams | |
284 | * @param string $queryOperator | |
6a488035 | 285 | * |
6a488035 | 286 | */ |
317fceb4 | 287 | public static function exportComponents( |
97f6897c | 288 | $selectAll, |
6a488035 TO |
289 | $ids, |
290 | $params, | |
291 | $order = NULL, | |
292 | $fields = NULL, | |
293 | $moreReturnProperties = NULL, | |
294 | $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, | |
295 | $componentClause = NULL, | |
296 | $componentTable = NULL, | |
297 | $mergeSameAddress = FALSE, | |
298 | $mergeSameHousehold = FALSE, | |
299 | $exportParams = array(), | |
300 | $queryOperator = 'AND' | |
301 | ) { | |
ef51caa8 | 302 | |
12a36993 | 303 | $returnProperties = array(); |
36f38fe7 | 304 | $paymentFields = $selectedPaymentFields = FALSE; |
55f37718 | 305 | $relationField = NULL; |
6a488035 | 306 | |
b4f964d9 | 307 | $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); |
12a36993 | 308 | // Warning - this imProviders var is used in a somewhat fragile way - don't rename it |
309 | // without manually testing the export of IM provider still works. | |
e7e657f0 | 310 | $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); |
6a488035 TO |
311 | $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType( |
312 | NULL, | |
313 | NULL, | |
314 | NULL, | |
315 | NULL, | |
316 | TRUE, | |
545285b8 | 317 | 'name', |
6a488035 TO |
318 | FALSE |
319 | ); | |
6a488035 | 320 | |
f34f5143 | 321 | $queryMode = self::getQueryMode($exportMode); |
919eddec | 322 | |
6a488035 TO |
323 | if ($fields) { |
324 | //construct return properties | |
b2b0530a | 325 | $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); |
6a488035 TO |
326 | $locationTypeFields = array( |
327 | 'street_address', | |
328 | 'supplemental_address_1', | |
329 | 'supplemental_address_2', | |
330 | 'city', | |
331 | 'postal_code', | |
332 | 'postal_code_suffix', | |
333 | 'geo_code_1', | |
334 | 'geo_code_2', | |
335 | 'state_province', | |
336 | 'country', | |
337 | 'phone', | |
338 | 'email', | |
339 | 'im', | |
340 | ); | |
341 | ||
342 | foreach ($fields as $key => $value) { | |
343 | $phoneTypeId = $imProviderId = NULL; | |
344 | $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value); | |
345 | if (!$fieldName) { | |
346 | continue; | |
347 | } | |
b44e3f84 | 348 | // get phoneType id and IM service provider id separately |
6a488035 TO |
349 | if ($fieldName == 'phone') { |
350 | $phoneTypeId = CRM_Utils_Array::value(3, $value); | |
351 | } | |
352 | elseif ($fieldName == 'im') { | |
353 | $imProviderId = CRM_Utils_Array::value(3, $value); | |
354 | } | |
6a488035 TO |
355 | |
356 | if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) { | |
a7488080 | 357 | if (!empty($value[2])) { |
6a488035 TO |
358 | $relationField = CRM_Utils_Array::value(2, $value); |
359 | if (trim(CRM_Utils_Array::value(3, $value))) { | |
360 | $relLocTypeId = CRM_Utils_Array::value(3, $value); | |
361 | } | |
362 | else { | |
363 | $relLocTypeId = 'Primary'; | |
364 | } | |
365 | ||
366 | if ($relationField == 'phone') { | |
367 | $relPhoneTypeId = CRM_Utils_Array::value(4, $value); | |
368 | } | |
369 | elseif ($relationField == 'im') { | |
370 | $relIMProviderId = CRM_Utils_Array::value(4, $value); | |
371 | } | |
372 | } | |
a7488080 | 373 | elseif (!empty($value[4])) { |
6a488035 TO |
374 | $relationField = CRM_Utils_Array::value(4, $value); |
375 | $relLocTypeId = CRM_Utils_Array::value(5, $value); | |
376 | if ($relationField == 'phone') { | |
377 | $relPhoneTypeId = CRM_Utils_Array::value(6, $value); | |
378 | } | |
379 | elseif ($relationField == 'im') { | |
380 | $relIMProviderId = CRM_Utils_Array::value(6, $value); | |
381 | } | |
382 | } | |
383 | } | |
384 | ||
385 | $contactType = CRM_Utils_Array::value(0, $value); | |
386 | $locTypeId = CRM_Utils_Array::value(2, $value); | |
387 | ||
388 | if ($relationField) { | |
389 | if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) { | |
390 | if ($relPhoneTypeId) { | |
391 | $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1; | |
392 | } | |
393 | elseif ($relIMProviderId) { | |
394 | $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1; | |
395 | } | |
396 | else { | |
397 | $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1; | |
398 | } | |
399 | $relPhoneTypeId = $relIMProviderId = NULL; | |
400 | } | |
401 | else { | |
402 | $returnProperties[$relationshipTypes][$relationField] = 1; | |
403 | } | |
404 | } | |
405 | elseif (is_numeric($locTypeId)) { | |
406 | if ($phoneTypeId) { | |
407 | $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1; | |
408 | } | |
409 | elseif ($imProviderId) { | |
410 | $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1; | |
411 | } | |
412 | else { | |
413 | $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1; | |
414 | } | |
415 | } | |
416 | else { | |
417 | //hack to fix component fields | |
8b8fa582 | 418 | //revert mix of event_id and title |
6a488035 | 419 | if ($fieldName == 'event_id') { |
8b8fa582 | 420 | $returnProperties['event_id'] = 1; |
6a488035 | 421 | } |
4c9b6178 | 422 | elseif ( |
545285b8 | 423 | $exportMode == CRM_Export_Form_Select::EVENT_EXPORT && |
97f6897c | 424 | array_key_exists($fieldName, self::componentPaymentFields()) |
545285b8 | 425 | ) { |
97f6897c TO |
426 | $selectedPaymentFields = TRUE; |
427 | $paymentTableId = 'participant_id'; | |
428 | $returnProperties[$fieldName] = 1; | |
d77aba4b | 429 | } |
6a488035 TO |
430 | else { |
431 | $returnProperties[$fieldName] = 1; | |
6a488035 TO |
432 | } |
433 | } | |
434 | } | |
0dc29086 | 435 | if (!empty(self::defaultReturnProperty($exportMode))) { |
436 | $returnProperties[self::defaultReturnProperty($exportMode)] = 1; | |
437 | } | |
919eddec | 438 | } |
6a488035 TO |
439 | else { |
440 | $primary = TRUE; | |
441 | $fields = CRM_Contact_BAO_Contact::exportableFields('All', TRUE, TRUE); | |
442 | foreach ($fields as $key => $var) { | |
443 | if ($key && (substr($key, 0, 6) != 'custom')) { | |
444 | //for CRM=952 | |
445 | $returnProperties[$key] = 1; | |
446 | } | |
447 | } | |
448 | ||
449 | if ($primary) { | |
450 | $returnProperties['location_type'] = 1; | |
451 | $returnProperties['im_provider'] = 1; | |
452 | $returnProperties['phone_type_id'] = 1; | |
453 | $returnProperties['provider_id'] = 1; | |
454 | $returnProperties['current_employer'] = 1; | |
455 | } | |
456 | ||
f1ff3965 | 457 | $extraProperties = self::defineExtraProperties($queryMode); |
748450ad SL |
458 | $paymentFields = $extraProperties['paymentFields']; |
459 | $extraReturnProperties = $extraProperties['extraReturnProperties']; | |
ee027e3b | 460 | $paymentTableId = $extraProperties['paymentTableId']; |
6a488035 TO |
461 | |
462 | if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) { | |
463 | $componentReturnProperties = CRM_Contact_BAO_Query::defaultReturnProperties($queryMode); | |
81ec6180 | 464 | if ($queryMode == CRM_Contact_BAO_Query::MODE_CONTRIBUTE) { |
4f3846df | 465 | // soft credit columns are not automatically populated, because contribution search doesn't require them by default |
317fceb4 | 466 | $componentReturnProperties = array_merge( |
6c8f6e67 | 467 | $componentReturnProperties, |
526bdd5e | 468 | CRM_Contribute_BAO_Query::softCreditReturnProperties(TRUE)); |
81ec6180 | 469 | } |
6a488035 TO |
470 | $returnProperties = array_merge($returnProperties, $componentReturnProperties); |
471 | ||
472 | if (!empty($extraReturnProperties)) { | |
473 | $returnProperties = array_merge($returnProperties, $extraReturnProperties); | |
474 | } | |
475 | ||
476 | // unset non exportable fields for components | |
477 | $nonExpoFields = array( | |
97f6897c TO |
478 | 'groups', |
479 | 'tags', | |
480 | 'notes', | |
481 | 'contribution_status_id', | |
482 | 'pledge_status_id', | |
483 | 'pledge_payment_status_id', | |
6a488035 TO |
484 | ); |
485 | foreach ($nonExpoFields as $value) { | |
486 | unset($returnProperties[$value]); | |
487 | } | |
488 | } | |
489 | } | |
490 | ||
491 | if ($mergeSameAddress) { | |
492 | //make sure the addressee fields are selected | |
493 | //while using merge same address feature | |
494 | $returnProperties['addressee'] = 1; | |
495 | $returnProperties['postal_greeting'] = 1; | |
496 | $returnProperties['email_greeting'] = 1; | |
497 | $returnProperties['street_name'] = 1; | |
498 | $returnProperties['household_name'] = 1; | |
499 | $returnProperties['street_address'] = 1; | |
500 | $returnProperties['city'] = 1; | |
501 | $returnProperties['state_province'] = 1; | |
502 | ||
503 | // some columns are required for assistance incase they are not already present | |
504 | $exportParams['merge_same_address']['temp_columns'] = array(); | |
505 | $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id'); | |
506 | foreach ($tempColumns as $column) { | |
507 | if (!array_key_exists($column, $returnProperties)) { | |
508 | $returnProperties[$column] = 1; | |
509 | $column = $column == 'id' ? 'civicrm_primary_id' : $column; | |
510 | $exportParams['merge_same_address']['temp_columns'][$column] = 1; | |
511 | } | |
512 | } | |
513 | } | |
514 | ||
8cc574cf | 515 | if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) { |
6a488035 TO |
516 | // If an Additional Group is selected, then all contacts in that group are |
517 | // added to the export set (filtering out duplicates). | |
518 | $query = " | |
519 | INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_contact gc WHERE gc.group_id = {$exportParams['additional_group']} ON DUPLICATE KEY UPDATE {$componentTable}.contact_id = gc.contact_id"; | |
520 | CRM_Core_DAO::executeQuery($query); | |
521 | } | |
522 | ||
523 | if ($moreReturnProperties) { | |
524 | // fix for CRM-7066 | |
a7488080 | 525 | if (!empty($moreReturnProperties['group'])) { |
6a488035 TO |
526 | unset($moreReturnProperties['group']); |
527 | $moreReturnProperties['groups'] = 1; | |
528 | } | |
529 | $returnProperties = array_merge($returnProperties, $moreReturnProperties); | |
530 | } | |
531 | ||
532 | $exportParams['postal_mailing_export']['temp_columns'] = array(); | |
533 | if ($exportParams['exportOption'] == 2 && | |
534 | isset($exportParams['postal_mailing_export']) && | |
535 | CRM_Utils_Array::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1 | |
536 | ) { | |
537 | $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1'); | |
538 | foreach ($postalColumns as $column) { | |
539 | if (!array_key_exists($column, $returnProperties)) { | |
540 | $returnProperties[$column] = 1; | |
541 | $exportParams['postal_mailing_export']['temp_columns'][$column] = 1; | |
542 | } | |
543 | } | |
544 | } | |
545 | ||
9e49a7b8 PJ |
546 | // rectify params to what proximity search expects if there is a value for prox_distance |
547 | // CRM-7021 | |
548 | if (!empty($params)) { | |
549 | CRM_Contact_BAO_ProximityQuery::fixInputParams($params); | |
550 | } | |
551 | ||
fdb9cf51 | 552 | $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL, |
6a488035 TO |
553 | FALSE, FALSE, $queryMode, |
554 | FALSE, TRUE, TRUE, NULL, $queryOperator | |
555 | ); | |
556 | ||
33a5a53d | 557 | //sort by state |
558 | //CRM-15301 | |
559 | $query->_sort = $order; | |
6a488035 TO |
560 | list($select, $from, $where, $having) = $query->query(); |
561 | ||
562 | if ($mergeSameHousehold == 1) { | |
0dc29086 | 563 | if (empty($returnProperties['id'])) { |
6a488035 TO |
564 | $returnProperties['id'] = 1; |
565 | } | |
566 | ||
567 | //also merge Head of Household | |
568 | $relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes); | |
569 | $relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes); | |
570 | ||
571 | foreach ($returnProperties as $key => $value) { | |
572 | if (!array_key_exists($key, $contactRelationshipTypes)) { | |
573 | $returnProperties[$relationKeyMOH][$key] = $value; | |
574 | $returnProperties[$relationKeyHOH][$key] = $value; | |
575 | } | |
576 | } | |
577 | ||
578 | unset($returnProperties[$relationKeyMOH]['location_type']); | |
579 | unset($returnProperties[$relationKeyMOH]['im_provider']); | |
580 | unset($returnProperties[$relationKeyHOH]['location_type']); | |
581 | unset($returnProperties[$relationKeyHOH]['im_provider']); | |
582 | } | |
583 | ||
584 | $allRelContactArray = $relationQuery = array(); | |
585 | ||
586 | foreach ($contactRelationshipTypes as $rel => $dnt) { | |
587 | if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) { | |
588 | $allRelContactArray[$rel] = array(); | |
589 | // build Query for each relationship | |
590 | $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties, | |
591 | NULL, FALSE, FALSE, $queryMode | |
592 | ); | |
593 | list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query(); | |
594 | ||
595 | list($id, $direction) = explode('_', $rel, 2); | |
596 | // identify the relationship direction | |
597 | $contactA = 'contact_id_a'; | |
598 | $contactB = 'contact_id_b'; | |
599 | if ($direction == 'b_a') { | |
600 | $contactA = 'contact_id_b'; | |
601 | $contactB = 'contact_id_a'; | |
602 | } | |
603 | if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) { | |
604 | $relIDs = $ids; | |
605 | } | |
606 | elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) { | |
ad7695c2 | 607 | $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source'); |
b4eac1e9 | 608 | $query = "SELECT contact_id FROM civicrm_activity_contact |
609 | WHERE activity_id IN ( " . implode(',', $ids) . ") AND | |
610 | record_type_id = {$sourceID}"; | |
6a488035 TO |
611 | $dao = CRM_Core_DAO::executeQuery($query); |
612 | while ($dao->fetch()) { | |
b4eac1e9 | 613 | $relIDs[] = $dao->contact_id; |
6a488035 TO |
614 | } |
615 | } | |
616 | else { | |
919eddec | 617 | $component = self::exportComponent($exportMode); |
040898fe | 618 | |
619 | if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) { | |
620 | $relIDs = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids); | |
621 | } | |
622 | else { | |
623 | $relIDs = CRM_Core_DAO::getContactIDsFromComponent($ids, $component); | |
624 | } | |
6a488035 TO |
625 | } |
626 | ||
627 | $relationshipJoin = $relationshipClause = ''; | |
34b773b7 | 628 | if (!$selectAll && $componentTable) { |
629 | $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}"; | |
6a488035 | 630 | } |
34b773b7 | 631 | elseif (!empty($relIDs)) { |
6a488035 TO |
632 | $relID = implode(',', $relIDs); |
633 | $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )"; | |
634 | } | |
635 | ||
636 | $relationFrom = " {$relationFrom} | |
637 | INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id} | |
638 | {$relationshipJoin} "; | |
639 | ||
640 | //check for active relationship status only | |
97f6897c TO |
641 | $today = date('Ymd'); |
642 | $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )"; | |
643 | $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}"; | |
644 | $relationGroupBy = " GROUP BY crel.{$contactA}"; | |
645 | $relationSelect = "{$relationSelect}, {$contactA} as refContact "; | |
6a488035 TO |
646 | $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy"; |
647 | ||
648 | $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString); | |
649 | while ($allRelContactDAO->fetch()) { | |
650 | //FIX Me: Migrate this to table rather than array | |
651 | // build the array of all related contacts | |
652 | $allRelContactArray[$rel][$allRelContactDAO->refContact] = clone($allRelContactDAO); | |
653 | } | |
654 | $allRelContactDAO->free(); | |
655 | } | |
656 | } | |
657 | ||
658 | // make sure the groups stuff is included only if specifically specified | |
659 | // by the fields param (CRM-1969), else we limit the contacts outputted to only | |
660 | // ones that are part of a group | |
a7488080 | 661 | if (!empty($returnProperties['groups'])) { |
6a488035 TO |
662 | $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )"; |
663 | $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )"; | |
664 | // total hack for export, CRM-3618 | |
665 | $from = str_replace($oldClause, | |
666 | $newClause, | |
667 | $from | |
668 | ); | |
669 | } | |
670 | ||
34b773b7 | 671 | if (!$selectAll && $componentTable) { |
6a488035 TO |
672 | $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id "; |
673 | } | |
674 | elseif ($componentClause) { | |
675 | if (empty($where)) { | |
676 | $where = "WHERE $componentClause"; | |
677 | } | |
678 | else { | |
679 | $where .= " AND $componentClause"; | |
680 | } | |
681 | } | |
682 | ||
14a08308 | 683 | // CRM-13982 - check if is deleted |
684 | $excludeTrashed = TRUE; | |
685 | foreach ($params as $value) { | |
686 | if ($value[0] == 'contact_is_deleted') { | |
687 | $excludeTrashed = FALSE; | |
688 | } | |
689 | } | |
17bc4f1b SL |
690 | $trashClause = $excludeTrashed ? "contact_a.is_deleted != 1" : "( 1 )"; |
691 | ||
0b02cdf2 | 692 | if (empty($where)) { |
17bc4f1b | 693 | $where = "WHERE $trashClause"; |
14a08308 | 694 | } |
17bc4f1b SL |
695 | else { |
696 | $where .= " AND $trashClause"; | |
14a08308 | 697 | } |
698 | ||
6a488035 TO |
699 | $queryString = "$select $from $where $having"; |
700 | ||
0cc9927d | 701 | $groupBy = self::getGroupBy($exportMode, $queryMode, $returnProperties, $query); |
8a13a745 | 702 | |
6a488035 | 703 | $queryString .= $groupBy; |
33a5a53d | 704 | |
705 | // always add contact_a.id to the ORDER clause | |
706 | // so the order is deterministic | |
707 | //CRM-15301 | |
708 | if (strpos('contact_a.id', $order) === FALSE) { | |
709 | $order .= ", contact_a.id"; | |
710 | } | |
711 | ||
6a488035 TO |
712 | if ($order) { |
713 | list($field, $dir) = explode(' ', $order, 2); | |
714 | $field = trim($field); | |
a7488080 | 715 | if (!empty($returnProperties[$field])) { |
33a5a53d | 716 | //CRM-15301 |
717 | $queryString .= " ORDER BY $order"; | |
6a488035 TO |
718 | } |
719 | } | |
720 | ||
721 | $multipleSelectFields = array('preferred_communication_method' => 1); | |
722 | ||
723 | $addPaymentHeader = FALSE; | |
724 | ||
725 | $paymentDetails = array(); | |
d77aba4b | 726 | if ($paymentFields || $selectedPaymentFields) { |
6a488035 TO |
727 | |
728 | // get payment related in for event and members | |
729 | $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids); | |
d77aba4b | 730 | //get all payment headers. |
7460c131 AS |
731 | // If we haven't selected specific payment fields, load in all the |
732 | // payment headers. | |
d77aba4b AS |
733 | if (!$selectedPaymentFields) { |
734 | $paymentHeaders = self::componentPaymentFields(); | |
735 | if (!empty($paymentDetails)) { | |
736 | $addPaymentHeader = TRUE; | |
737 | } | |
6a488035 | 738 | } |
55f37718 | 739 | // If we have selected specific payment fields, leave the payment headers |
7460c131 AS |
740 | // as an empty array; the headers for each selected field will be added |
741 | // elsewhere. | |
742 | else { | |
743 | $paymentHeaders = array(); | |
744 | } | |
6a488035 TO |
745 | $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL); |
746 | } | |
747 | ||
12a36993 | 748 | $componentDetails = array(); |
6a488035 TO |
749 | $setHeader = TRUE; |
750 | ||
751 | $rowCount = self::EXPORT_ROW_COUNT; | |
752 | $offset = 0; | |
753 | // we write to temp table often to avoid using too much memory | |
754 | $tempRowCount = 100; | |
755 | ||
756 | $count = -1; | |
757 | ||
758 | // for CRM-3157 purposes | |
759 | $i18n = CRM_Core_I18n::singleton(); | |
12a36993 | 760 | list($outputColumns, $headerRows, $sqlColumns, $metadata) = self::getExportStructureArrays($returnProperties, $query, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields); |
761 | ||
6a488035 TO |
762 | while (1) { |
763 | $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}"; | |
764 | $dao = CRM_Core_DAO::executeQuery($limitQuery); | |
765 | if ($dao->N <= 0) { | |
766 | break; | |
767 | } | |
768 | ||
769 | while ($dao->fetch()) { | |
770 | $count++; | |
771 | $row = array(); | |
772 | ||
b23943b8 | 773 | //convert the pseudo constants |
62835cac EM |
774 | // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned |
775 | // temporary iterationDAO object to get around it. | |
776 | // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object | |
777 | // these additional properties are NOT reset when the $dao cycles through the while loop | |
778 | // nor are they overwritten as they are not in the loop | |
779 | // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the | |
780 | // relevant property is set. | |
781 | // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the | |
782 | // export class before tackling a better architectural fix | |
783 | $iterationDAO = clone $dao; | |
784 | $query->convertToPseudoNames($iterationDAO); | |
d9ab802d | 785 | |
55f37718 | 786 | //first loop through output columns so that we return what is required, and in same order. |
6a488035 | 787 | $relationshipField = 0; |
55f37718 | 788 | foreach ($outputColumns as $field => $value) { |
6a488035 TO |
789 | |
790 | // add im_provider to $dao object | |
62835cac EM |
791 | if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) { |
792 | $iterationDAO->im_provider = $iterationDAO->provider_id; | |
6a488035 TO |
793 | } |
794 | ||
795 | //build row values (data) | |
796 | $fieldValue = NULL; | |
62835cac EM |
797 | if (property_exists($iterationDAO, $field)) { |
798 | $fieldValue = $iterationDAO->$field; | |
6a488035 TO |
799 | // to get phone type from phone type id |
800 | if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) { | |
801 | $fieldValue = $phoneTypes[$fieldValue]; | |
802 | } | |
803 | elseif ($field == 'provider_id' || $field == 'im_provider') { | |
804 | $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders); | |
805 | } | |
6a488035 TO |
806 | elseif ($field == 'master_id') { |
807 | $masterAddressId = NULL; | |
62835cac EM |
808 | if (isset($iterationDAO->master_id)) { |
809 | $masterAddressId = $iterationDAO->master_id; | |
6a488035 TO |
810 | } |
811 | // get display name of contact that address is shared. | |
62835cac | 812 | $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $iterationDAO->contact_id); |
6a488035 TO |
813 | } |
814 | } | |
815 | ||
816 | if ($field == 'id') { | |
62835cac | 817 | $row[$field] = $iterationDAO->contact_id; |
6a488035 TO |
818 | // special case for calculated field |
819 | } | |
d4a280d8 | 820 | elseif ($field == 'source_contact_id') { |
62835cac | 821 | $row[$field] = $iterationDAO->contact_id; |
d4a280d8 | 822 | } |
6a488035 | 823 | elseif ($field == 'pledge_balance_amount') { |
62835cac | 824 | $row[$field] = $iterationDAO->pledge_amount - $iterationDAO->pledge_total_paid; |
6a488035 TO |
825 | // special case for calculated field |
826 | } | |
827 | elseif ($field == 'pledge_next_pay_amount') { | |
62835cac | 828 | $row[$field] = $iterationDAO->pledge_next_pay_amount + $iterationDAO->pledge_outstanding_amount; |
6a488035 | 829 | } |
6a488035 | 830 | elseif (array_key_exists($field, $contactRelationshipTypes)) { |
62835cac | 831 | $relDAO = CRM_Utils_Array::value($iterationDAO->contact_id, $allRelContactArray[$field]); |
02709b11 | 832 | $relationQuery[$field]->convertToPseudoNames($relDAO); |
6a488035 TO |
833 | foreach ($value as $relationField => $relationValue) { |
834 | if (is_object($relDAO) && property_exists($relDAO, $relationField)) { | |
835 | $fieldValue = $relDAO->$relationField; | |
836 | if ($relationField == 'phone_type_id') { | |
837 | $fieldValue = $phoneTypes[$relationValue]; | |
838 | } | |
839 | elseif ($relationField == 'provider_id') { | |
840 | $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders); | |
841 | } | |
36ae0094 JL |
842 | // CRM-13995 |
843 | elseif (is_object($relDAO) && in_array($relationField, array( | |
844 | 'email_greeting', | |
845 | 'postal_greeting', | |
846 | 'addressee', | |
847 | )) | |
848 | ) { | |
849 | //special case for greeting replacement | |
850 | $fldValue = "{$relationField}_display"; | |
851 | $fieldValue = $relDAO->$fldValue; | |
852 | } | |
2bf55c30 | 853 | } |
97f6897c | 854 | elseif (is_object($relDAO) && $relationField == 'state_province') { |
2bf55c30 BS |
855 | $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id); |
856 | } | |
97f6897c | 857 | elseif (is_object($relDAO) && $relationField == 'country') { |
b07c1873 DG |
858 | $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id); |
859 | } | |
6a488035 TO |
860 | else { |
861 | $fieldValue = ''; | |
862 | } | |
863 | $field = $field . '_'; | |
2bf55c30 | 864 | |
02709b11 | 865 | if (array_key_exists($relationField, $multipleSelectFields)) { |
866 | $param = array($relationField => $fieldValue); | |
867 | $names = array($relationField => array('newName' => $relationField, 'groupName' => $relationField)); | |
868 | CRM_Core_OptionGroup::lookupValues($param, $names, FALSE); | |
869 | $fieldValue = $param[$relationField]; | |
870 | } | |
6a488035 TO |
871 | if (is_object($relDAO) && $relationField == 'id') { |
872 | $row[$field . $relationField] = $relDAO->contact_id; | |
2bf55c30 | 873 | } |
97f6897c | 874 | elseif (is_array($relationValue) && $relationField == 'location') { |
6a488035 TO |
875 | foreach ($relationValue as $ltype => $val) { |
876 | foreach (array_keys($val) as $fld) { | |
877 | $type = explode('-', $fld); | |
878 | $fldValue = "{$ltype}-" . $type[0]; | |
a7488080 | 879 | if (!empty($type[1])) { |
6a488035 TO |
880 | $fldValue .= "-" . $type[1]; |
881 | } | |
882 | // CRM-3157: localise country, region (both have ‘country’ context) | |
883 | // and state_province (‘province’ context) | |
884 | switch (TRUE) { | |
97f6897c | 885 | case (!is_object($relDAO)): |
6a488035 TO |
886 | $row[$field . '_' . $fldValue] = ''; |
887 | break; | |
888 | ||
889 | case in_array('country', $type): | |
890 | case in_array('world_region', $type): | |
891 | $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue, | |
892 | array('context' => 'country') | |
893 | ); | |
894 | break; | |
895 | ||
896 | case in_array('state_province', $type): | |
897 | $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue, | |
898 | array('context' => 'province') | |
899 | ); | |
900 | break; | |
901 | ||
902 | default: | |
903 | $row[$field . '_' . $fldValue] = $relDAO->$fldValue; | |
904 | break; | |
905 | } | |
906 | } | |
907 | } | |
908 | } | |
909 | elseif (isset($fieldValue) && $fieldValue != '') { | |
910 | //check for custom data | |
911 | if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) { | |
8cee0c70 | 912 | $row[$field . $relationField] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID); |
6a488035 | 913 | } |
6a488035 TO |
914 | else { |
915 | //normal relationship fields | |
916 | // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context) | |
917 | switch ($relationField) { | |
918 | case 'country': | |
919 | case 'world_region': | |
920 | $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country')); | |
921 | break; | |
922 | ||
923 | case 'state_province': | |
924 | $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province')); | |
925 | break; | |
926 | ||
927 | default: | |
928 | $row[$field . $relationField] = $fieldValue; | |
929 | break; | |
930 | } | |
931 | } | |
932 | } | |
933 | else { | |
934 | // if relation field is empty or null | |
935 | $row[$field . $relationField] = ''; | |
936 | } | |
937 | } | |
938 | } | |
939 | elseif (isset($fieldValue) && | |
940 | $fieldValue != '' | |
941 | ) { | |
942 | //check for custom data | |
943 | if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) { | |
8cee0c70 | 944 | $row[$field] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID); |
6a488035 TO |
945 | } |
946 | elseif (array_key_exists($field, $multipleSelectFields)) { | |
947 | //option group fixes | |
948 | $paramsNew = array($field => $fieldValue); | |
949 | if ($field == 'test_tutoring') { | |
950 | $name = array($field => array('newName' => $field, 'groupName' => 'test')); | |
951 | // for readers group | |
952 | } | |
953 | elseif (substr($field, 0, 4) == 'cmr_') { | |
954 | $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3))); | |
955 | } | |
956 | else { | |
957 | $name = array($field => array('newName' => $field, 'groupName' => $field)); | |
958 | } | |
959 | CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE); | |
960 | $row[$field] = $paramsNew[$field]; | |
961 | } | |
55f37718 | 962 | |
6a488035 | 963 | elseif (in_array($field, array( |
97f6897c TO |
964 | 'email_greeting', |
965 | 'postal_greeting', | |
21dfd5f5 | 966 | 'addressee', |
97f6897c | 967 | ))) { |
6a488035 TO |
968 | //special case for greeting replacement |
969 | $fldValue = "{$field}_display"; | |
62835cac | 970 | $row[$field] = $iterationDAO->$fldValue; |
6a488035 TO |
971 | } |
972 | else { | |
973 | //normal fields with a touch of CRM-3157 | |
974 | switch ($field) { | |
975 | case 'country': | |
976 | case 'world_region': | |
977 | $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country')); | |
978 | break; | |
979 | ||
980 | case 'state_province': | |
981 | $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province')); | |
982 | break; | |
983 | ||
984 | case 'gender': | |
985 | case 'preferred_communication_method': | |
986 | case 'preferred_mail_format': | |
aa62b355 | 987 | case 'communication_style': |
6a488035 TO |
988 | $row[$field] = $i18n->crm_translate($fieldValue); |
989 | break; | |
990 | ||
991 | default: | |
12a36993 | 992 | if (isset($metadata[$field])) { |
993 | // No I don't know why we do it this way & whether we could | |
994 | // make better use of pseudoConstants. | |
995 | if (!empty($metadata[$field]['context'])) { | |
996 | $row[$field] = $i18n->crm_translate($fieldValue, $metadata[$field]); | |
997 | break; | |
998 | } | |
999 | if (!empty($metadata[$field]['pseudoconstant'])) { | |
1000 | // This is not our normal syntax for pseudoconstants but I am a bit loath to | |
1001 | // call an external function until sure it is not increasing php processing given this | |
1002 | // may be iterated 100,000 times & we already have the $imProvider var loaded. | |
1003 | // That can be next refactor... | |
1004 | // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness | |
1005 | // but I have to reach a stable point.... | |
1006 | $varName = $metadata[$field]['pseudoconstant']['var']; | |
1007 | $labels = $$varName; | |
1008 | $row[$field] = $labels[$fieldValue]; | |
1009 | break; | |
1010 | } | |
1011 | ||
1012 | } | |
6a488035 TO |
1013 | $row[$field] = $fieldValue; |
1014 | break; | |
1015 | } | |
1016 | } | |
1017 | } | |
d77aba4b | 1018 | elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) { |
62835cac | 1019 | $paymentData = CRM_Utils_Array::value($iterationDAO->$paymentTableId, $paymentDetails); |
d77aba4b | 1020 | $payFieldMapper = array( |
97f6897c | 1021 | 'componentPaymentField_total_amount' => 'total_amount', |
d77aba4b | 1022 | 'componentPaymentField_contribution_status' => 'contribution_status', |
97f6897c TO |
1023 | 'componentPaymentField_payment_instrument' => 'pay_instru', |
1024 | 'componentPaymentField_transaction_id' => 'trxn_id', | |
1025 | 'componentPaymentField_received_date' => 'receive_date', | |
d77aba4b AS |
1026 | ); |
1027 | $row[$field] = CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, ''); | |
1028 | } | |
6a488035 TO |
1029 | else { |
1030 | // if field is empty or null | |
1031 | $row[$field] = ''; | |
1032 | } | |
1033 | } | |
1034 | ||
1035 | // add payment headers if required | |
1036 | if ($addPaymentHeader && $paymentFields) { | |
12a36993 | 1037 | // @todo rather than do this for every single row do it before the loop starts. |
1038 | // where other header definitions take place. | |
6a488035 TO |
1039 | $headerRows = array_merge($headerRows, $paymentHeaders); |
1040 | foreach (array_keys($paymentHeaders) as $paymentHdr) { | |
1041 | self::sqlColumnDefn($query, $sqlColumns, $paymentHdr); | |
1042 | } | |
6a488035 TO |
1043 | } |
1044 | ||
1045 | if ($setHeader) { | |
1046 | $exportTempTable = self::createTempTable($sqlColumns); | |
1047 | } | |
1048 | ||
1049 | //build header only once | |
1050 | $setHeader = FALSE; | |
1051 | ||
e026db3c | 1052 | // If specific payment fields have been selected for export, payment |
545285b8 | 1053 | // data will already be in $row. Otherwise, add payment related |
e026db3c | 1054 | // information, if appropriate. |
fc33177b | 1055 | if ($addPaymentHeader) { |
1056 | if (!$selectedPaymentFields) { | |
1057 | if ($paymentFields) { | |
1058 | $paymentData = CRM_Utils_Array::value($row[$paymentTableId], $paymentDetails); | |
1059 | if (!is_array($paymentData) || empty($paymentData)) { | |
1060 | $paymentData = $nullContributionDetails; | |
1061 | } | |
1062 | $row = array_merge($row, $paymentData); | |
1063 | } | |
1064 | elseif (!empty($paymentDetails)) { | |
1065 | $row = array_merge($row, $nullContributionDetails); | |
e026db3c | 1066 | } |
e026db3c | 1067 | } |
6a488035 | 1068 | } |
6a488035 | 1069 | //remove organization name for individuals if it is set for current employer |
a7488080 | 1070 | if (!empty($row['contact_type']) && |
6a488035 TO |
1071 | $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row) |
1072 | ) { | |
1073 | $row['organization_name'] = ''; | |
1074 | } | |
1075 | ||
1076 | // add component info | |
1077 | // write the row to a file | |
1078 | $componentDetails[] = $row; | |
1079 | ||
1080 | // output every $tempRowCount rows | |
1081 | if ($count % $tempRowCount == 0) { | |
1082 | self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns); | |
1083 | $componentDetails = array(); | |
1084 | } | |
1085 | } | |
1086 | $dao->free(); | |
1087 | $offset += $rowCount; | |
1088 | } | |
1089 | ||
1090 | if ($exportTempTable) { | |
1091 | self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns); | |
1092 | ||
1093 | // do merge same address and merge same household processing | |
1094 | if ($mergeSameAddress) { | |
1095 | self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams); | |
1096 | } | |
1097 | ||
1098 | // merge the records if they have corresponding households | |
1099 | if ($mergeSameHousehold) { | |
1100 | self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH); | |
1101 | self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH); | |
1102 | } | |
1103 | ||
6a488035 TO |
1104 | // if postalMailing option is checked, exclude contacts who are deceased, have |
1105 | // "Do not mail" privacy setting, or have no street address | |
1106 | if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) && | |
1107 | $exportParams['postal_mailing_export']['postal_mailing_export'] == 1 | |
1108 | ) { | |
1109 | self::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode); | |
1110 | } | |
1111 | ||
1112 | // call export hook | |
1113 | CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode); | |
1114 | ||
ef51caa8 | 1115 | // In order to be able to write a unit test against this function we need to suppress |
1116 | // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions. | |
1117 | if (empty($exportParams['suppress_csv_for_testing'])) { | |
1118 | self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode); | |
1119 | } | |
6a488035 TO |
1120 | |
1121 | // delete the export temp table and component table | |
1122 | $sql = "DROP TABLE IF EXISTS {$exportTempTable}"; | |
1123 | CRM_Core_DAO::executeQuery($sql); | |
ef51caa8 | 1124 | // Do not exit in test context. |
1125 | if (empty($exportParams['suppress_csv_for_testing'])) { | |
1126 | CRM_Utils_System::civiExit(); | |
1127 | } | |
6a488035 TO |
1128 | } |
1129 | else { | |
1130 | CRM_Core_Error::fatal(ts('No records to export')); | |
1131 | } | |
1132 | } | |
1133 | ||
1134 | /** | |
fe482240 | 1135 | * Name of the export file based on mode. |
6a488035 | 1136 | * |
b9add4b3 TO |
1137 | * @param string $output |
1138 | * Type of output. | |
1139 | * @param int $mode | |
1140 | * Export mode. | |
6a488035 | 1141 | * |
a6c01b45 CW |
1142 | * @return string |
1143 | * name of the file | |
6a488035 | 1144 | */ |
00be9182 | 1145 | public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select::CONTACT_EXPORT) { |
6a488035 TO |
1146 | switch ($mode) { |
1147 | case CRM_Export_Form_Select::CONTACT_EXPORT: | |
1148 | return ts('CiviCRM Contact Search'); | |
1149 | ||
1150 | case CRM_Export_Form_Select::CONTRIBUTE_EXPORT: | |
1151 | return ts('CiviCRM Contribution Search'); | |
1152 | ||
1153 | case CRM_Export_Form_Select::MEMBER_EXPORT: | |
1154 | return ts('CiviCRM Member Search'); | |
1155 | ||
1156 | case CRM_Export_Form_Select::EVENT_EXPORT: | |
1157 | return ts('CiviCRM Participant Search'); | |
1158 | ||
1159 | case CRM_Export_Form_Select::PLEDGE_EXPORT: | |
1160 | return ts('CiviCRM Pledge Search'); | |
1161 | ||
1162 | case CRM_Export_Form_Select::CASE_EXPORT: | |
1163 | return ts('CiviCRM Case Search'); | |
1164 | ||
1165 | case CRM_Export_Form_Select::GRANT_EXPORT: | |
1166 | return ts('CiviCRM Grant Search'); | |
1167 | ||
1168 | case CRM_Export_Form_Select::ACTIVITY_EXPORT: | |
1169 | return ts('CiviCRM Activity Search'); | |
1170 | } | |
1171 | } | |
1172 | ||
1173 | /** | |
100fef9d | 1174 | * Handle import error file creation. |
6a488035 | 1175 | */ |
00be9182 | 1176 | public static function invoke() { |
6a488035 TO |
1177 | $type = CRM_Utils_Request::retrieve('type', 'Positive', CRM_Core_DAO::$_nullObject); |
1178 | $parserName = CRM_Utils_Request::retrieve('parser', 'String', CRM_Core_DAO::$_nullObject); | |
1179 | if (empty($parserName) || empty($type)) { | |
1180 | return; | |
1181 | } | |
1182 | ||
1183 | // clean and ensure parserName is a valid string | |
1184 | $parserName = CRM_Utils_String::munge($parserName); | |
1185 | $parserClass = explode('_', $parserName); | |
1186 | ||
1187 | // make sure parserClass is in the CRM namespace and | |
1188 | // at least 3 levels deep | |
1189 | if ($parserClass[0] == 'CRM' && | |
1190 | count($parserClass) >= 3 | |
1191 | ) { | |
d3e86119 | 1192 | require_once str_replace('_', DIRECTORY_SEPARATOR, $parserName) . ".php"; |
6a488035 TO |
1193 | // ensure the functions exists |
1194 | if (method_exists($parserName, 'errorFileName') && | |
1195 | method_exists($parserName, 'saveFileName') | |
1196 | ) { | |
1197 | $errorFileName = $parserName::errorFileName($type); | |
1198 | $saveFileName = $parserName::saveFileName($type); | |
1199 | if (!empty($errorFileName) && !empty($saveFileName)) { | |
d42a224c CW |
1200 | CRM_Utils_System::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0'); |
1201 | CRM_Utils_System::setHttpHeader('Content-Description', 'File Transfer'); | |
1202 | CRM_Utils_System::setHttpHeader('Content-Type', 'text/csv'); | |
1203 | CRM_Utils_System::setHttpHeader('Content-Length', filesize($errorFileName)); | |
1204 | CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName); | |
6a488035 TO |
1205 | |
1206 | readfile($errorFileName); | |
1207 | } | |
1208 | } | |
1209 | } | |
1210 | CRM_Utils_System::civiExit(); | |
1211 | } | |
1212 | ||
e0ef6999 EM |
1213 | /** |
1214 | * @param $customSearchClass | |
1215 | * @param $formValues | |
1216 | * @param $order | |
1217 | */ | |
00be9182 | 1218 | public static function exportCustom($customSearchClass, $formValues, $order) { |
6a488035 TO |
1219 | $ext = CRM_Extension_System::singleton()->getMapper(); |
1220 | if (!$ext->isExtensionClass($customSearchClass)) { | |
d3e86119 | 1221 | require_once str_replace('_', DIRECTORY_SEPARATOR, $customSearchClass) . '.php'; |
6a488035 TO |
1222 | } |
1223 | else { | |
d3e86119 | 1224 | require_once $ext->classToPath($customSearchClass); |
6a488035 TO |
1225 | } |
1226 | $search = new $customSearchClass($formValues); | |
1227 | ||
1228 | $includeContactIDs = FALSE; | |
1229 | if ($formValues['radio_ts'] == 'ts_sel') { | |
1230 | $includeContactIDs = TRUE; | |
1231 | } | |
1232 | ||
1233 | $sql = $search->all(0, 0, $order, $includeContactIDs); | |
1234 | ||
1235 | $columns = $search->columns(); | |
1236 | ||
1237 | $header = array_keys($columns); | |
1238 | $fields = array_values($columns); | |
1239 | ||
97f6897c TO |
1240 | $rows = array(); |
1241 | $dao = CRM_Core_DAO::executeQuery($sql); | |
6a488035 TO |
1242 | $alterRow = FALSE; |
1243 | if (method_exists($search, 'alterRow')) { | |
1244 | $alterRow = TRUE; | |
1245 | } | |
1246 | while ($dao->fetch()) { | |
1247 | $row = array(); | |
1248 | ||
1249 | foreach ($fields as $field) { | |
37990ecd JV |
1250 | $unqualified_field = CRM_Utils_Array::First(array_slice(explode('.', $field), -1)); |
1251 | $row[$field] = $dao->$unqualified_field; | |
6a488035 TO |
1252 | } |
1253 | if ($alterRow) { | |
1254 | $search->alterRow($row); | |
1255 | } | |
1256 | $rows[] = $row; | |
1257 | } | |
1258 | ||
1259 | CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName(), $header, $rows); | |
1260 | CRM_Utils_System::civiExit(); | |
1261 | } | |
1262 | ||
e0ef6999 EM |
1263 | /** |
1264 | * @param $query | |
1265 | * @param $sqlColumns | |
1266 | * @param $field | |
1267 | */ | |
12a36993 | 1268 | public static function sqlColumnDefn($query, &$sqlColumns, $field) { |
0944820d | 1269 | if (substr($field, -4) == '_a_b' || substr($field, -4) == '_b_a') { |
6a488035 TO |
1270 | return; |
1271 | } | |
1272 | ||
1273 | $fieldName = CRM_Utils_String::munge(strtolower($field), '_', 64); | |
1274 | if ($fieldName == 'id') { | |
1275 | $fieldName = 'civicrm_primary_id'; | |
1276 | } | |
1277 | ||
0944820d DL |
1278 | // early exit for master_id, CRM-12100 |
1279 | // in the DB it is an ID, but in the export, we retrive the display_name of the master record | |
86eef7b6 J |
1280 | // also for current_employer, CRM-16939 |
1281 | if ($fieldName == 'master_id' || $fieldName == 'current_employer') { | |
0944820d DL |
1282 | $sqlColumns[$fieldName] = "$fieldName varchar(128)"; |
1283 | return; | |
1284 | } | |
1285 | ||
55f37718 EM |
1286 | if (substr($fieldName, -11) == 'campaign_id') { |
1287 | // CRM-14398 | |
1288 | $sqlColumns[$fieldName] = "$fieldName varchar(128)"; | |
55f37718 EM |
1289 | return; |
1290 | } | |
1291 | ||
4f2997e2 | 1292 | $lookUp = array('prefix_id', 'suffix_id'); |
6a488035 TO |
1293 | // set the sql columns |
1294 | if (isset($query->_fields[$field]['type'])) { | |
1295 | switch ($query->_fields[$field]['type']) { | |
1296 | case CRM_Utils_Type::T_INT: | |
6a488035 | 1297 | case CRM_Utils_Type::T_BOOLEAN: |
a6332b16 | 1298 | if (in_array($field, $lookUp)) { |
4f2997e2 | 1299 | $sqlColumns[$fieldName] = "$fieldName varchar(255)"; |
1300 | } | |
1301 | else { | |
1302 | $sqlColumns[$fieldName] = "$fieldName varchar(16)"; | |
1303 | } | |
6a488035 TO |
1304 | break; |
1305 | ||
1306 | case CRM_Utils_Type::T_STRING: | |
1307 | if (isset($query->_fields[$field]['maxlength'])) { | |
1308 | $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})"; | |
1309 | } | |
1310 | else { | |
fe66d6ea | 1311 | $sqlColumns[$fieldName] = "$fieldName varchar(255)"; |
6a488035 TO |
1312 | } |
1313 | break; | |
1314 | ||
1315 | case CRM_Utils_Type::T_TEXT: | |
1316 | case CRM_Utils_Type::T_LONGTEXT: | |
1317 | case CRM_Utils_Type::T_BLOB: | |
1318 | case CRM_Utils_Type::T_MEDIUMBLOB: | |
1319 | $sqlColumns[$fieldName] = "$fieldName longtext"; | |
1320 | break; | |
1321 | ||
1322 | case CRM_Utils_Type::T_FLOAT: | |
1323 | case CRM_Utils_Type::T_ENUM: | |
1324 | case CRM_Utils_Type::T_DATE: | |
1325 | case CRM_Utils_Type::T_TIME: | |
1326 | case CRM_Utils_Type::T_TIMESTAMP: | |
1327 | case CRM_Utils_Type::T_MONEY: | |
1328 | case CRM_Utils_Type::T_EMAIL: | |
1329 | case CRM_Utils_Type::T_URL: | |
1330 | case CRM_Utils_Type::T_CCNUM: | |
1331 | default: | |
1332 | $sqlColumns[$fieldName] = "$fieldName varchar(32)"; | |
1333 | break; | |
1334 | } | |
1335 | } | |
1336 | else { | |
1337 | if (substr($fieldName, -3, 3) == '_id') { | |
1338f0b1 | 1338 | // for trxn_id and its variants use a longer buffer |
b44e3f84 | 1339 | // to accommodate different systems - CRM-13739 |
1338f0b1 DL |
1340 | static $notRealIDFields = NULL; |
1341 | if ($notRealIDFields == NULL) { | |
97f6897c | 1342 | $notRealIDFields = array('trxn_id', 'componentpaymentfield_transaction_id'); |
1338f0b1 DL |
1343 | } |
1344 | ||
1345 | if (in_array($fieldName, $notRealIDFields)) { | |
1346 | $sqlColumns[$fieldName] = "$fieldName varchar(255)"; | |
1347 | } | |
1348 | else { | |
1349 | $sqlColumns[$fieldName] = "$fieldName varchar(16)"; | |
1350 | } | |
6a488035 | 1351 | } |
c05a91c9 | 1352 | elseif (substr($fieldName, -5, 5) == '_note') { |
1353 | $sqlColumns[$fieldName] = "$fieldName text"; | |
1354 | } | |
6a488035 TO |
1355 | else { |
1356 | $changeFields = array( | |
1357 | 'groups', | |
1358 | 'tags', | |
21dfd5f5 | 1359 | 'notes', |
6a488035 TO |
1360 | ); |
1361 | ||
1362 | if (in_array($fieldName, $changeFields)) { | |
1363 | $sqlColumns[$fieldName] = "$fieldName text"; | |
1364 | } | |
1365 | else { | |
1366 | // set the sql columns for custom data | |
1367 | if (isset($query->_fields[$field]['data_type'])) { | |
1368 | ||
1369 | switch ($query->_fields[$field]['data_type']) { | |
26509325 CW |
1370 | case 'String': |
1371 | $length = empty($query->_fields[$field]['text_length']) ? 255 : $query->_fields[$field]['text_length']; | |
1372 | $sqlColumns[$fieldName] = "$fieldName varchar($length)"; | |
1373 | break; | |
1374 | ||
6a488035 TO |
1375 | case 'Country': |
1376 | case 'StateProvince': | |
1377 | case 'Link': | |
6a488035 TO |
1378 | $sqlColumns[$fieldName] = "$fieldName varchar(255)"; |
1379 | break; | |
1380 | ||
1381 | case 'Memo': | |
1382 | $sqlColumns[$fieldName] = "$fieldName text"; | |
1383 | break; | |
1384 | ||
1385 | default: | |
fe4afc7b | 1386 | $sqlColumns[$fieldName] = "$fieldName varchar(255)"; |
6a488035 TO |
1387 | break; |
1388 | } | |
1389 | } | |
1390 | else { | |
e9f85685 | 1391 | $sqlColumns[$fieldName] = "$fieldName text"; |
6a488035 TO |
1392 | } |
1393 | } | |
1394 | } | |
1395 | } | |
1396 | } | |
1397 | ||
e0ef6999 | 1398 | /** |
100fef9d | 1399 | * @param string $tableName |
e0ef6999 EM |
1400 | * @param $details |
1401 | * @param $sqlColumns | |
1402 | */ | |
00be9182 | 1403 | public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) { |
6a488035 TO |
1404 | if (empty($details)) { |
1405 | return; | |
1406 | } | |
1407 | ||
1408 | $sql = " | |
1409 | SELECT max(id) | |
1410 | FROM $tableName | |
1411 | "; | |
1412 | ||
1413 | $id = CRM_Core_DAO::singleValueQuery($sql); | |
1414 | if (!$id) { | |
1415 | $id = 0; | |
1416 | } | |
1417 | ||
1418 | $sqlClause = array(); | |
1419 | ||
1420 | foreach ($details as $dontCare => $row) { | |
1421 | $id++; | |
1422 | $valueString = array($id); | |
1423 | foreach ($row as $dontCare => $value) { | |
1424 | if (empty($value)) { | |
1425 | $valueString[] = "''"; | |
1426 | } | |
1427 | else { | |
1428 | $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'"; | |
1429 | } | |
1430 | } | |
1431 | $sqlClause[] = '(' . implode(',', $valueString) . ')'; | |
1432 | } | |
1433 | ||
1434 | $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')'; | |
1435 | ||
1436 | $sqlValueString = implode(",\n", $sqlClause); | |
1437 | ||
1438 | $sql = " | |
1439 | INSERT INTO $tableName $sqlColumnString | |
1440 | VALUES $sqlValueString | |
1441 | "; | |
1442 | ||
1443 | CRM_Core_DAO::executeQuery($sql); | |
1444 | } | |
1445 | ||
e0ef6999 EM |
1446 | /** |
1447 | * @param $sqlColumns | |
1448 | * | |
1449 | * @return string | |
1450 | */ | |
00be9182 | 1451 | public static function createTempTable(&$sqlColumns) { |
6a488035 TO |
1452 | //creating a temporary table for the search result that need be exported |
1453 | $exportTempTable = CRM_Core_DAO::createTempTableName('civicrm_export', TRUE); | |
1454 | ||
1455 | // also create the sql table | |
1456 | $sql = "DROP TABLE IF EXISTS {$exportTempTable}"; | |
1457 | CRM_Core_DAO::executeQuery($sql); | |
1458 | ||
1459 | $sql = " | |
1460 | CREATE TABLE {$exportTempTable} ( | |
1461 | id int unsigned NOT NULL AUTO_INCREMENT, | |
1462 | "; | |
1463 | $sql .= implode(",\n", array_values($sqlColumns)); | |
1464 | ||
1465 | $sql .= ", | |
1466 | PRIMARY KEY ( id ) | |
1467 | "; | |
1468 | // add indexes for street_address and household_name if present | |
1469 | $addIndices = array( | |
1470 | 'street_address', | |
1471 | 'household_name', | |
1472 | 'civicrm_primary_id', | |
1473 | ); | |
1474 | ||
1475 | foreach ($addIndices as $index) { | |
1476 | if (isset($sqlColumns[$index])) { | |
1477 | $sql .= ", | |
1478 | INDEX index_{$index}( $index ) | |
1479 | "; | |
1480 | } | |
1481 | } | |
1482 | ||
1483 | $sql .= " | |
1484 | ) ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci | |
1485 | "; | |
1486 | ||
1487 | CRM_Core_DAO::executeQuery($sql); | |
1488 | return $exportTempTable; | |
1489 | } | |
1490 | ||
e0ef6999 | 1491 | /** |
100fef9d | 1492 | * @param string $tableName |
e0ef6999 EM |
1493 | * @param $headerRows |
1494 | * @param $sqlColumns | |
100fef9d | 1495 | * @param array $exportParams |
e0ef6999 | 1496 | */ |
00be9182 | 1497 | public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) { |
6a488035 TO |
1498 | // check if any records are present based on if they have used shared address feature, |
1499 | // and not based on if city / state .. matches. | |
1500 | $sql = " | |
1501 | SELECT r1.id as copy_id, | |
1502 | r1.civicrm_primary_id as copy_contact_id, | |
1503 | r1.addressee as copy_addressee, | |
1504 | r1.addressee_id as copy_addressee_id, | |
1505 | r1.postal_greeting as copy_postal_greeting, | |
1506 | r1.postal_greeting_id as copy_postal_greeting_id, | |
1507 | r2.id as master_id, | |
1508 | r2.civicrm_primary_id as master_contact_id, | |
1509 | r2.postal_greeting as master_postal_greeting, | |
1510 | r2.postal_greeting_id as master_postal_greeting_id, | |
1511 | r2.addressee as master_addressee, | |
1512 | r2.addressee_id as master_addressee_id | |
1513 | FROM $tableName r1 | |
1514 | INNER JOIN civicrm_address adr ON r1.master_id = adr.id | |
1515 | INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id | |
1516 | ORDER BY r1.id"; | |
1517 | $linkedMerge = self::_buildMasterCopyArray($sql, $exportParams, TRUE); | |
1518 | ||
1519 | // find all the records that have the same street address BUT not in a household | |
1520 | // require match on city and state as well | |
1521 | $sql = " | |
1522 | SELECT r1.id as master_id, | |
1523 | r1.civicrm_primary_id as master_contact_id, | |
1524 | r1.postal_greeting as master_postal_greeting, | |
1525 | r1.postal_greeting_id as master_postal_greeting_id, | |
1526 | r1.addressee as master_addressee, | |
1527 | r1.addressee_id as master_addressee_id, | |
1528 | r2.id as copy_id, | |
1529 | r2.civicrm_primary_id as copy_contact_id, | |
1530 | r2.postal_greeting as copy_postal_greeting, | |
1531 | r2.postal_greeting_id as copy_postal_greeting_id, | |
1532 | r2.addressee as copy_addressee, | |
1533 | r2.addressee_id as copy_addressee_id | |
1534 | FROM $tableName r1 | |
1535 | LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND | |
1536 | r1.city = r2.city AND | |
1537 | r1.state_province_id = r2.state_province_id ) | |
1538 | WHERE ( r1.household_name IS NULL OR r1.household_name = '' ) | |
1539 | AND ( r2.household_name IS NULL OR r2.household_name = '' ) | |
1540 | AND ( r1.street_address != '' ) | |
1541 | AND r2.id > r1.id | |
1542 | ORDER BY r1.id | |
1543 | "; | |
1544 | $merge = self::_buildMasterCopyArray($sql, $exportParams); | |
1545 | ||
1546 | // unset ids from $merge already present in $linkedMerge | |
1547 | foreach ($linkedMerge as $masterID => $values) { | |
1548 | $keys = array($masterID); | |
1549 | $keys = array_merge($keys, array_keys($values['copy'])); | |
1550 | foreach ($merge as $mid => $vals) { | |
1551 | if (in_array($mid, $keys)) { | |
1552 | unset($merge[$mid]); | |
1553 | } | |
1554 | else { | |
1555 | foreach ($values['copy'] as $copyId) { | |
1556 | if (in_array($copyId, $keys)) { | |
1557 | unset($merge[$mid]['copy'][$copyId]); | |
1558 | } | |
1559 | } | |
1560 | } | |
1561 | } | |
1562 | } | |
1563 | $merge = $merge + $linkedMerge; | |
1564 | ||
1565 | foreach ($merge as $masterID => $values) { | |
1566 | $sql = " | |
1567 | UPDATE $tableName | |
1568 | SET addressee = %1, postal_greeting = %2, email_greeting = %3 | |
1569 | WHERE id = %4 | |
1570 | "; | |
97f6897c TO |
1571 | $params = array( |
1572 | 1 => array($values['addressee'], 'String'), | |
6a488035 TO |
1573 | 2 => array($values['postalGreeting'], 'String'), |
1574 | 3 => array($values['emailGreeting'], 'String'), | |
1575 | 4 => array($masterID, 'Integer'), | |
1576 | ); | |
1577 | CRM_Core_DAO::executeQuery($sql, $params); | |
1578 | ||
1579 | // delete all copies | |
97f6897c | 1580 | $deleteIDs = array_keys($values['copy']); |
6a488035 | 1581 | $deleteIDString = implode(',', $deleteIDs); |
97f6897c | 1582 | $sql = " |
6a488035 TO |
1583 | DELETE FROM $tableName |
1584 | WHERE id IN ( $deleteIDString ) | |
1585 | "; | |
1586 | CRM_Core_DAO::executeQuery($sql); | |
1587 | } | |
1588 | ||
1589 | // unset temporary columns that were added for postal mailing format | |
1590 | if (!empty($exportParams['merge_same_address']['temp_columns'])) { | |
1591 | $unsetKeys = array_keys($sqlColumns); | |
1592 | foreach ($unsetKeys as $headerKey => $sqlColKey) { | |
1593 | if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) { | |
1594 | unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]); | |
1595 | } | |
1596 | } | |
1597 | } | |
1598 | } | |
1599 | ||
e0ef6999 | 1600 | /** |
100fef9d CW |
1601 | * @param int $contactId |
1602 | * @param array $exportParams | |
e0ef6999 EM |
1603 | * |
1604 | * @return array | |
1605 | */ | |
00be9182 | 1606 | public static function _replaceMergeTokens($contactId, $exportParams) { |
6a488035 TO |
1607 | $greetings = array(); |
1608 | $contact = NULL; | |
1609 | ||
1610 | $greetingFields = array( | |
1611 | 'postal_greeting', | |
1612 | 'addressee', | |
1613 | ); | |
1614 | foreach ($greetingFields as $greeting) { | |
a7488080 | 1615 | if (!empty($exportParams[$greeting])) { |
6a488035 TO |
1616 | $greetingLabel = $exportParams[$greeting]; |
1617 | if (empty($contact)) { | |
1618 | $values = array( | |
1619 | 'id' => $contactId, | |
1620 | 'version' => 3, | |
1621 | ); | |
1622 | $contact = civicrm_api('contact', 'get', $values); | |
1623 | ||
a7488080 | 1624 | if (!empty($contact['is_error'])) { |
6a488035 TO |
1625 | return $greetings; |
1626 | } | |
1627 | $contact = $contact['values'][$contact['id']]; | |
1628 | } | |
1629 | ||
1630 | $tokens = array('contact' => $greetingLabel); | |
1631 | $greetings[$greeting] = CRM_Utils_Token::replaceContactTokens($greetingLabel, $contact, NULL, $tokens); | |
1632 | } | |
1633 | } | |
1634 | return $greetings; | |
1635 | } | |
1636 | ||
1637 | /** | |
1638 | * The function unsets static part of the string, if token is the dynamic part. | |
54957108 | 1639 | * |
6a488035 TO |
1640 | * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}' |
1641 | * i.e 'Hello Alan' => converted to => 'Alan' | |
54957108 | 1642 | * |
1643 | * @param string $parsedString | |
1644 | * @param string $defaultGreeting | |
1645 | * @param bool $addressMergeGreetings | |
1646 | * @param string $greetingType | |
1647 | * | |
1648 | * @return mixed | |
6a488035 | 1649 | */ |
317fceb4 | 1650 | public static function _trimNonTokens( |
97f6897c | 1651 | &$parsedString, $defaultGreeting, |
353ffa53 | 1652 | $addressMergeGreetings, $greetingType = 'postal_greeting' |
6a488035 | 1653 | ) { |
a7488080 | 1654 | if (!empty($addressMergeGreetings[$greetingType])) { |
6a488035 TO |
1655 | $greetingLabel = $addressMergeGreetings[$greetingType]; |
1656 | } | |
1657 | $greetingLabel = empty($greetingLabel) ? $defaultGreeting : $greetingLabel; | |
1658 | ||
1659 | $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel); | |
1660 | $stringsToBeReplaced = explode(';;', $stringsToBeReplaced); | |
1661 | foreach ($stringsToBeReplaced as $key => $string) { | |
1662 | // to keep one space | |
1663 | $stringsToBeReplaced[$key] = ltrim($string); | |
1664 | } | |
1665 | $parsedString = str_replace($stringsToBeReplaced, "", $parsedString); | |
1666 | ||
1667 | return $parsedString; | |
1668 | } | |
1669 | ||
e0ef6999 EM |
1670 | /** |
1671 | * @param $sql | |
100fef9d | 1672 | * @param array $exportParams |
e0ef6999 EM |
1673 | * @param bool $sharedAddress |
1674 | * | |
1675 | * @return array | |
1676 | */ | |
00be9182 | 1677 | public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) { |
6a488035 TO |
1678 | static $contactGreetingTokens = array(); |
1679 | ||
1680 | $addresseeOptions = CRM_Core_OptionGroup::values('addressee'); | |
1681 | $postalOptions = CRM_Core_OptionGroup::values('postal_greeting'); | |
1682 | ||
1683 | $merge = $parents = array(); | |
1684 | $dao = CRM_Core_DAO::executeQuery($sql); | |
1685 | ||
1686 | while ($dao->fetch()) { | |
1687 | $masterID = $dao->master_id; | |
1688 | $copyID = $dao->copy_id; | |
1689 | $masterPostalGreeting = $dao->master_postal_greeting; | |
1690 | $masterAddressee = $dao->master_addressee; | |
1691 | $copyAddressee = $dao->copy_addressee; | |
1692 | ||
1693 | if (!$sharedAddress) { | |
1694 | if (!isset($contactGreetingTokens[$dao->master_contact_id])) { | |
1695 | $contactGreetingTokens[$dao->master_contact_id] = self::_replaceMergeTokens($dao->master_contact_id, $exportParams); | |
1696 | } | |
1697 | $masterPostalGreeting = CRM_Utils_Array::value('postal_greeting', | |
1698 | $contactGreetingTokens[$dao->master_contact_id], $dao->master_postal_greeting | |
1699 | ); | |
1700 | $masterAddressee = CRM_Utils_Array::value('addressee', | |
1701 | $contactGreetingTokens[$dao->master_contact_id], $dao->master_addressee | |
1702 | ); | |
1703 | ||
1704 | if (!isset($contactGreetingTokens[$dao->copy_contact_id])) { | |
1705 | $contactGreetingTokens[$dao->copy_contact_id] = self::_replaceMergeTokens($dao->copy_contact_id, $exportParams); | |
1706 | } | |
1707 | $copyPostalGreeting = CRM_Utils_Array::value('postal_greeting', | |
1708 | $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_postal_greeting | |
1709 | ); | |
1710 | $copyAddressee = CRM_Utils_Array::value('addressee', | |
1711 | $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_addressee | |
1712 | ); | |
1713 | } | |
1714 | ||
1715 | if (!isset($merge[$masterID])) { | |
1716 | // check if this is an intermediate child | |
1717 | // this happens if there are 3 or more matches a,b, c | |
1718 | // the above query will return a, b / a, c / b, c | |
1719 | // we might be doing a bit more work, but for now its ok, unless someone | |
1720 | // knows how to fix the query above | |
1721 | if (isset($parents[$masterID])) { | |
1722 | $masterID = $parents[$masterID]; | |
1723 | } | |
1724 | else { | |
1725 | $merge[$masterID] = array( | |
1726 | 'addressee' => $masterAddressee, | |
1727 | 'copy' => array(), | |
1728 | 'postalGreeting' => $masterPostalGreeting, | |
1729 | ); | |
1730 | $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting']; | |
1731 | } | |
1732 | } | |
1733 | $parents[$copyID] = $masterID; | |
1734 | ||
1735 | if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) { | |
1736 | ||
a7488080 | 1737 | if (!empty($exportParams['postal_greeting_other']) && |
6a488035 TO |
1738 | count($merge[$masterID]['copy']) >= 1 |
1739 | ) { | |
1740 | // use static greetings specified if no of contacts > 2 | |
1741 | $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other']; | |
1742 | } | |
1743 | elseif ($copyPostalGreeting) { | |
1744 | self::_trimNonTokens($copyPostalGreeting, | |
1745 | $postalOptions[$dao->copy_postal_greeting_id], | |
1746 | $exportParams | |
1747 | ); | |
1748 | $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}"; | |
1749 | // if there happens to be a duplicate, remove it | |
1750 | $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']); | |
1751 | } | |
1752 | ||
a7488080 | 1753 | if (!empty($exportParams['addressee_other']) && |
6a488035 TO |
1754 | count($merge[$masterID]['copy']) >= 1 |
1755 | ) { | |
1756 | // use static greetings specified if no of contacts > 2 | |
1757 | $merge[$masterID]['addressee'] = $exportParams['addressee_other']; | |
1758 | } | |
1759 | elseif ($copyAddressee) { | |
1760 | self::_trimNonTokens($copyAddressee, | |
1761 | $addresseeOptions[$dao->copy_addressee_id], | |
1762 | $exportParams, 'addressee' | |
1763 | ); | |
1764 | $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee); | |
1765 | } | |
1766 | } | |
1767 | $merge[$masterID]['copy'][$copyID] = $copyAddressee; | |
1768 | } | |
1769 | ||
1770 | return $merge; | |
1771 | } | |
1772 | ||
1773 | /** | |
100fef9d | 1774 | * Merge household record into the individual record |
6a488035 TO |
1775 | * if exists |
1776 | * | |
b9add4b3 TO |
1777 | * @param string $exportTempTable |
1778 | * Temporary temp table that stores the records. | |
1779 | * @param array $headerRows | |
1780 | * Array of headers for the export file. | |
1781 | * @param array $sqlColumns | |
1782 | * Array of names of the table columns of the temp table. | |
1783 | * @param string $prefix | |
1784 | * Name of the relationship type that is prefixed to the table columns. | |
6a488035 | 1785 | */ |
00be9182 | 1786 | public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) { |
6a488035 | 1787 | $prefixColumn = $prefix . '_'; |
97f6897c TO |
1788 | $allKeys = array_keys($sqlColumns); |
1789 | $replaced = array(); | |
1790 | $headerRows = array_values($headerRows); | |
6a488035 TO |
1791 | |
1792 | // name map of the non standard fields in header rows & sql columns | |
1793 | $mappingFields = array( | |
1794 | 'civicrm_primary_id' => 'id', | |
1795 | 'contact_source' => 'source', | |
1796 | 'current_employer_id' => 'employer_id', | |
1797 | 'contact_is_deleted' => 'is_deleted', | |
1798 | 'name' => 'address_name', | |
1799 | 'provider_id' => 'im_service_provider', | |
21dfd5f5 | 1800 | 'phone_type_id' => 'phone_type', |
6a488035 TO |
1801 | ); |
1802 | ||
1803 | //figure out which columns are to be replaced by which ones | |
1804 | foreach ($sqlColumns as $columnNames => $dontCare) { | |
1805 | if ($rep = CRM_Utils_Array::value($columnNames, $mappingFields)) { | |
1806 | $replaced[$columnNames] = CRM_Utils_String::munge($prefixColumn . $rep, '_', 64); | |
1807 | } | |
1808 | else { | |
1809 | $householdColName = CRM_Utils_String::munge($prefixColumn . $columnNames, '_', 64); | |
1810 | ||
a7488080 | 1811 | if (!empty($sqlColumns[$householdColName])) { |
6a488035 TO |
1812 | $replaced[$columnNames] = $householdColName; |
1813 | } | |
1814 | } | |
1815 | } | |
1816 | $query = "UPDATE $exportTempTable SET "; | |
1817 | ||
1818 | $clause = array(); | |
1819 | foreach ($replaced as $from => $to) { | |
1820 | $clause[] = "$from = $to "; | |
1821 | unset($sqlColumns[$to]); | |
1822 | if ($key = CRM_Utils_Array::key($to, $allKeys)) { | |
1823 | unset($headerRows[$key]); | |
1824 | } | |
1825 | } | |
1826 | $query .= implode(",\n", $clause); | |
1827 | $query .= " WHERE {$replaced['civicrm_primary_id']} != ''"; | |
1828 | ||
1829 | CRM_Core_DAO::executeQuery($query); | |
1830 | ||
1831 | //drop the table columns that store redundant household info | |
1832 | $dropQuery = "ALTER TABLE $exportTempTable "; | |
1833 | foreach ($replaced as $householdColumns) { | |
1834 | $dropClause[] = " DROP $householdColumns "; | |
1835 | } | |
1836 | $dropQuery .= implode(",\n", $dropClause); | |
1837 | ||
1838 | CRM_Core_DAO::executeQuery($dropQuery); | |
1839 | ||
1840 | // also drop the temp table if exists | |
1841 | $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp"; | |
1842 | CRM_Core_DAO::executeQuery($sql); | |
1843 | ||
1844 | // clean up duplicate records | |
1845 | $query = " | |
1846 | CREATE TABLE {$exportTempTable}_temp SELECT * | |
1847 | FROM {$exportTempTable} | |
1848 | GROUP BY civicrm_primary_id "; | |
1849 | ||
1850 | CRM_Core_DAO::executeQuery($query); | |
1851 | ||
1852 | $query = "DROP TABLE $exportTempTable"; | |
1853 | CRM_Core_DAO::executeQuery($query); | |
1854 | ||
1855 | $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}"; | |
1856 | CRM_Core_DAO::executeQuery($query); | |
1857 | } | |
1858 | ||
e0ef6999 EM |
1859 | /** |
1860 | * @param $exportTempTable | |
1861 | * @param $headerRows | |
1862 | * @param $sqlColumns | |
1863 | * @param $exportMode | |
1864 | * @param null $saveFile | |
1865 | * @param string $batchItems | |
1866 | */ | |
97f6897c | 1867 | public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') { |
6a488035 | 1868 | $writeHeader = TRUE; |
97f6897c TO |
1869 | $offset = 0; |
1870 | $limit = self::EXPORT_ROW_COUNT; | |
6a488035 TO |
1871 | |
1872 | $query = "SELECT * FROM $exportTempTable"; | |
1873 | ||
1874 | while (1) { | |
1875 | $limitQuery = $query . " | |
1876 | LIMIT $offset, $limit | |
1877 | "; | |
1878 | $dao = CRM_Core_DAO::executeQuery($limitQuery); | |
1879 | ||
1880 | if ($dao->N <= 0) { | |
1881 | break; | |
1882 | } | |
1883 | ||
1884 | $componentDetails = array(); | |
1885 | while ($dao->fetch()) { | |
1886 | $row = array(); | |
1887 | ||
1888 | foreach ($sqlColumns as $column => $dontCare) { | |
1889 | $row[$column] = $dao->$column; | |
1890 | } | |
1891 | $componentDetails[] = $row; | |
1892 | } | |
97f6897c | 1893 | if ($exportMode == 'financial') { |
6a488035 TO |
1894 | $getExportFileName = 'CiviCRM Contribution Search'; |
1895 | } | |
1896 | else { | |
97f6897c | 1897 | $getExportFileName = self::getExportFileName('csv', $exportMode); |
6a488035 | 1898 | } |
97f6897c | 1899 | $csvRows = CRM_Core_Report_Excel::writeCSVFile($getExportFileName, |
6a488035 TO |
1900 | $headerRows, |
1901 | $componentDetails, | |
97f6897c | 1902 | NULL, |
6a488035 | 1903 | $writeHeader, |
97f6897c | 1904 | $saveFile); |
6a488035 TO |
1905 | |
1906 | if ($saveFile && !empty($csvRows)) { | |
1907 | $batchItems .= $csvRows; | |
1908 | } | |
1909 | ||
97f6897c | 1910 | $writeHeader = FALSE; |
6a488035 TO |
1911 | $offset += $limit; |
1912 | } | |
1913 | } | |
1914 | ||
1915 | /** | |
fe482240 | 1916 | * Manipulate header rows for relationship fields. |
ca87146b EM |
1917 | * |
1918 | * @param $headerRows | |
1919 | * @param $contactRelationshipTypes | |
6a488035 | 1920 | */ |
1571c7e7 | 1921 | public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) { |
6a488035 TO |
1922 | foreach ($headerRows as & $header) { |
1923 | $split = explode('-', $header); | |
1924 | if ($relationTypeName = CRM_Utils_Array::value($split[0], $contactRelationshipTypes)) { | |
1925 | $split[0] = $relationTypeName; | |
1926 | $header = implode('-', $split); | |
1927 | } | |
1928 | } | |
1929 | } | |
1930 | ||
1931 | /** | |
100fef9d | 1932 | * Exclude contacts who are deceased, have "Do not mail" privacy setting, |
6a488035 | 1933 | * or have no street address |
ca87146b EM |
1934 | * @param $exportTempTable |
1935 | * @param $headerRows | |
1936 | * @param $sqlColumns | |
1937 | * @param $exportParams | |
6a488035 | 1938 | */ |
00be9182 | 1939 | public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) { |
6a488035 TO |
1940 | $whereClause = array(); |
1941 | ||
1942 | if (array_key_exists('is_deceased', $sqlColumns)) { | |
1943 | $whereClause[] = 'is_deceased = 1'; | |
1944 | } | |
1945 | ||
1946 | if (array_key_exists('do_not_mail', $sqlColumns)) { | |
1947 | $whereClause[] = 'do_not_mail = 1'; | |
1948 | } | |
1949 | ||
1950 | if (array_key_exists('street_address', $sqlColumns)) { | |
1951 | $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) "; | |
1952 | ||
1953 | // check for supplemental_address_1 | |
1954 | if (array_key_exists('supplemental_address_1', $sqlColumns)) { | |
1955 | $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, | |
1956 | 'address_options', TRUE, NULL, TRUE | |
1957 | ); | |
a7488080 | 1958 | if (!empty($addressOptions['supplemental_address_1'])) { |
6a488035 TO |
1959 | $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) "; |
1960 | // enclose it again, since we are doing an AND in between a set of ORs | |
1961 | $addressWhereClause = "( $addressWhereClause )"; | |
1962 | } | |
1963 | } | |
1964 | ||
1965 | $whereClause[] = $addressWhereClause; | |
1966 | } | |
1967 | ||
1968 | if (!empty($whereClause)) { | |
1969 | $whereClause = implode(' OR ', $whereClause); | |
1970 | $query = " | |
1971 | DELETE | |
1972 | FROM $exportTempTable | |
1973 | WHERE {$whereClause}"; | |
1974 | CRM_Core_DAO::singleValueQuery($query); | |
1975 | } | |
1976 | ||
1977 | // unset temporary columns that were added for postal mailing format | |
1978 | if (!empty($exportParams['postal_mailing_export']['temp_columns'])) { | |
1979 | $unsetKeys = array_keys($sqlColumns); | |
1980 | foreach ($unsetKeys as $headerKey => $sqlColKey) { | |
1981 | if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) { | |
1982 | unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]); | |
1983 | } | |
1984 | } | |
1985 | } | |
1986 | } | |
d77aba4b AS |
1987 | |
1988 | /** | |
1989 | * Build componentPayment fields. | |
1990 | */ | |
00be9182 | 1991 | public static function componentPaymentFields() { |
d77aba4b | 1992 | static $componentPaymentFields; |
97f6897c | 1993 | if (!isset($componentPaymentFields)) { |
d77aba4b | 1994 | $componentPaymentFields = array( |
97f6897c | 1995 | 'componentPaymentField_total_amount' => ts('Total Amount'), |
d77aba4b | 1996 | 'componentPaymentField_contribution_status' => ts('Contribution Status'), |
7bc6b5bb | 1997 | 'componentPaymentField_received_date' => ts('Date Received'), |
536f0e02 | 1998 | 'componentPaymentField_payment_instrument' => ts('Payment Method'), |
97f6897c | 1999 | 'componentPaymentField_transaction_id' => ts('Transaction ID'), |
d77aba4b AS |
2000 | ); |
2001 | } | |
2002 | return $componentPaymentFields; | |
2003 | } | |
96025800 | 2004 | |
12a36993 | 2005 | /** |
2006 | * Set the definition for the header rows and sql columns based on the field to output. | |
2007 | * | |
2008 | * @param string $field | |
2009 | * @param array $headerRows | |
2010 | * @param array $sqlColumns | |
2011 | * Columns to go in the temp table. | |
2012 | * @param CRM_Contact_BAO_Query $query | |
2013 | * @param array|string $value | |
2014 | * @param array $phoneTypes | |
2015 | * @param array $imProviders | |
2016 | * @param array $contactRelationshipTypes | |
2017 | * @param string $relationQuery | |
2018 | * @param array $selectedPaymentFields | |
2019 | * @return array | |
2020 | */ | |
2021 | public static function setHeaderRows($field, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields) { | |
2022 | ||
2023 | // Split campaign into 2 fields for id and title | |
2024 | if (substr($field, -14) == 'campaign_title') { | |
2025 | $headerRows[] = ts('Campaign Title'); | |
2026 | } | |
2027 | elseif (substr($field, -11) == 'campaign_id') { | |
2028 | $headerRows[] = ts('Campaign ID'); | |
2029 | } | |
2030 | elseif (isset($query->_fields[$field]['title'])) { | |
2031 | $headerRows[] = $query->_fields[$field]['title']; | |
2032 | } | |
2033 | elseif ($field == 'phone_type_id') { | |
2034 | $headerRows[] = ts('Phone Type'); | |
2035 | } | |
2036 | elseif ($field == 'provider_id') { | |
2037 | $headerRows[] = ts('IM Service Provider'); | |
2038 | } | |
2039 | elseif (substr($field, 0, 5) == 'case_') { | |
2040 | if ($query->_fields['case'][$field]['title']) { | |
2041 | $headerRows[] = $query->_fields['case'][$field]['title']; | |
2042 | } | |
2043 | elseif ($query->_fields['activity'][$field]['title']) { | |
2044 | $headerRows[] = $query->_fields['activity'][$field]['title']; | |
2045 | } | |
2046 | } | |
2047 | elseif (array_key_exists($field, $contactRelationshipTypes)) { | |
2048 | self::manipulateHeaderRows($headerRows, $contactRelationshipTypes); | |
2049 | foreach ($value as $relationField => $relationValue) { | |
2050 | // below block is same as primary block (duplicate) | |
2051 | if (isset($relationQuery[$field]->_fields[$relationField]['title'])) { | |
2052 | if ($relationQuery[$field]->_fields[$relationField]['name'] == 'name') { | |
2053 | $headerName = $field . '-' . $relationField; | |
2054 | } | |
2055 | else { | |
2056 | if ($relationField == 'current_employer') { | |
2057 | $headerName = $field . '-' . 'current_employer'; | |
2058 | } | |
2059 | else { | |
2060 | $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['name']; | |
2061 | } | |
2062 | } | |
2063 | ||
2064 | $headerRows[] = $headerName; | |
2065 | ||
2066 | self::sqlColumnDefn($query, $sqlColumns, $headerName); | |
2067 | } | |
2068 | elseif ($relationField == 'phone_type_id') { | |
2069 | $headerName = $field . '-' . 'Phone Type'; | |
2070 | $headerRows[] = $headerName; | |
2071 | self::sqlColumnDefn($query, $sqlColumns, $headerName); | |
2072 | } | |
2073 | elseif ($relationField == 'provider_id') { | |
2074 | $headerName = $field . '-' . 'Im Service Provider'; | |
2075 | $headerRows[] = $headerName; | |
2076 | self::sqlColumnDefn($query, $sqlColumns, $headerName); | |
2077 | } | |
2078 | elseif ($relationField == 'state_province_id') { | |
2079 | $headerName = $field . '-' . 'state_province_id'; | |
2080 | $headerRows[] = $headerName; | |
2081 | self::sqlColumnDefn($query, $sqlColumns, $headerName); | |
2082 | } | |
2083 | elseif (is_array($relationValue) && $relationField == 'location') { | |
2084 | // fix header for location type case | |
2085 | foreach ($relationValue as $ltype => $val) { | |
2086 | foreach (array_keys($val) as $fld) { | |
2087 | $type = explode('-', $fld); | |
2088 | ||
2089 | $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title']; | |
2090 | ||
2091 | if (!empty($type[1])) { | |
2092 | if (CRM_Utils_Array::value(0, $type) == 'phone') { | |
2093 | $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes); | |
2094 | } | |
2095 | elseif (CRM_Utils_Array::value(0, $type) == 'im') { | |
2096 | $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders); | |
2097 | } | |
2098 | } | |
2099 | $headerName = $field . '-' . $hdr; | |
2100 | $headerRows[] = $headerName; | |
2101 | self::sqlColumnDefn($query, $sqlColumns, $headerName); | |
2102 | } | |
2103 | } | |
2104 | } | |
2105 | } | |
2106 | } | |
2107 | elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) { | |
2108 | $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields()); | |
2109 | } | |
2110 | else { | |
2111 | $headerRows[] = $field; | |
2112 | } | |
2113 | ||
2114 | self::sqlColumnDefn($query, $sqlColumns, $field); | |
2115 | ||
2116 | return array($headerRows, $sqlColumns); | |
2117 | } | |
2118 | ||
2119 | /** | |
2120 | * Get the various arrays that we use to structure our output. | |
2121 | * | |
2122 | * The extraction of these has been moved to a separate function for clarity and so that | |
2123 | * tests can be added - in particular on the $outputHeaders array. | |
2124 | * | |
2125 | * However it still feels a bit like something that I'm too polite to write down and this should be seen | |
2126 | * as a step on the refactoring path rather than how it should be. | |
2127 | * | |
2128 | * @param array $returnProperties | |
2129 | * @param CRM_Contact_BAO_Contact $query | |
2130 | * @param array $phoneTypes | |
2131 | * @param array $imProviders | |
2132 | * @param array $contactRelationshipTypes | |
2133 | * @param string $relationQuery | |
2134 | * @param array $selectedPaymentFields | |
2135 | * @return array | |
2136 | * - outputColumns Array of columns to be exported. The values don't matter but the key must match the | |
2137 | * alias for the field generated by BAO_Query object. | |
2138 | * - headerRows Array of the column header strings to put in the csv header - non-associative. | |
2139 | * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here. | |
2140 | * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution | |
2141 | * I'm too embarassed to discuss here. | |
2142 | * The keys need | |
2143 | * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values | |
2144 | * we could use does suggest further refactors. However, you future improver, do remember that every check you do | |
2145 | * in the main DAO loop is done once per row & that coule be 100,000 times.) | |
2146 | * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because | |
2147 | * - a) the function used is more efficient or | |
2148 | * - b) this code is old & outdated. Submit your answers to circular bin or better | |
2149 | * yet find a way to comment them for posterity. | |
2150 | */ | |
2151 | public static function getExportStructureArrays($returnProperties, $query, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields) { | |
2152 | $metadata = $headerRows = $outputColumns = $sqlColumns = array(); | |
2153 | ||
2154 | foreach ($returnProperties as $key => $value) { | |
2155 | if ($key != 'location' || !is_array($value)) { | |
2156 | $outputColumns[$key] = $value; | |
2157 | list($headerRows, $sqlColumns) = self::setHeaderRows($key, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields); | |
2158 | } | |
2159 | else { | |
2160 | foreach ($value as $locationType => $locationFields) { | |
2161 | foreach (array_keys($locationFields) as $locationFieldName) { | |
2162 | $type = explode('-', $locationFieldName); | |
2163 | ||
2164 | $actualDBFieldName = $type[0]; | |
2165 | $outputFieldName = $locationType . '-' . $query->_fields[$actualDBFieldName]['title']; | |
2166 | $daoFieldName = CRM_Utils_String::munge($locationType) . '-' . $actualDBFieldName; | |
2167 | ||
2168 | if (!empty($type[1])) { | |
2169 | $daoFieldName .= "-" . $type[1]; | |
2170 | if ($actualDBFieldName == 'phone') { | |
2171 | $outputFieldName .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes); | |
2172 | } | |
2173 | elseif ($actualDBFieldName == 'im') { | |
2174 | $outputFieldName .= "-" . CRM_Utils_Array::value($type[1], $imProviders); | |
2175 | } | |
2176 | } | |
2177 | if ($type[0] == 'im_provider') { | |
2178 | // Warning: shame inducing hack. | |
2179 | $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders'; | |
2180 | } | |
2181 | self::sqlColumnDefn($query, $sqlColumns, $outputFieldName); | |
2182 | list($headerRows, $sqlColumns) = self::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields); | |
2183 | if ($actualDBFieldName == 'country' || $actualDBFieldName == 'world_region') { | |
2184 | $metadata[$daoFieldName] = array('context' => 'country'); | |
2185 | } | |
2186 | if ($actualDBFieldName == 'state_province') { | |
2187 | $metadata[$daoFieldName] = array('context' => 'province'); | |
2188 | } | |
2189 | $outputColumns[$daoFieldName] = TRUE; | |
2190 | } | |
2191 | } | |
2192 | } | |
2193 | } | |
2194 | return array($outputColumns, $headerRows, $sqlColumns, $metadata); | |
2195 | } | |
2196 | ||
6a488035 | 2197 | } |