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