Merge pull request #24117 from civicrm/5.52
[civicrm-core.git] / CRM / Export / BAO / ExportProcessor.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * Class CRM_Export_BAO_ExportProcessor
20 *
21 * Class to handle logic of export.
22 */
23 class CRM_Export_BAO_ExportProcessor {
24
25 /**
26 * @var int
27 */
28 protected $queryMode;
29
30 /**
31 * @var int
32 */
33 protected $exportMode;
34
35 /**
36 * Array of fields in the main query.
37 *
38 * @var array
39 */
40 protected $queryFields = [];
41
42 /**
43 * Either AND or OR.
44 *
45 * @var string
46 */
47 protected $queryOperator;
48
49 /**
50 * Requested output fields.
51 *
52 * If set to NULL then it is 'primary fields only'
53 * which actually means pretty close to all fields!
54 *
55 * @var array|null
56 */
57 protected $requestedFields;
58
59 /**
60 * Is the contact being merged into a single household.
61 *
62 * @var bool
63 */
64 protected $isMergeSameHousehold;
65
66 /**
67 * Should contacts with the same address be merged.
68 *
69 * @var bool
70 */
71 protected $isMergeSameAddress = FALSE;
72
73 /**
74 * Fields that need to be retrieved for address merge purposes but should not be in output.
75 *
76 * @var array
77 */
78 protected $additionalFieldsForSameAddressMerge = [];
79
80 /**
81 * Fields used for merging same contacts.
82 *
83 * @var array
84 */
85 protected $contactGreetingFields = [];
86
87 /**
88 * An array of primary IDs of the entity being exported.
89 *
90 * @var array
91 */
92 protected $ids = [];
93
94 /**
95 * Greeting options mapping to various greeting ids.
96 *
97 * This stores the option values for the addressee, postal_greeting & email_greeting
98 * option groups.
99 *
100 * @var array
101 */
102 protected $greetingOptions = [];
103
104 /**
105 * Get additional non-visible fields for address merge purposes.
106 *
107 * @return array
108 */
109 public function getAdditionalFieldsForSameAddressMerge(): array {
110 return $this->additionalFieldsForSameAddressMerge;
111 }
112
113 /**
114 * Set additional non-visible fields for address merge purposes.
115 */
116 public function setAdditionalFieldsForSameAddressMerge() {
117 if ($this->isMergeSameAddress) {
118 $fields = ['id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id'];
119 foreach ($fields as $index => $field) {
120 if (!empty($this->getReturnProperties()[$field])) {
121 unset($fields[$index]);
122 }
123 }
124 $this->additionalFieldsForSameAddressMerge = array_fill_keys($fields, 1);
125 }
126 }
127
128 /**
129 * Should contacts with the same address be merged.
130 *
131 * @return bool
132 */
133 public function isMergeSameAddress(): bool {
134 return $this->isMergeSameAddress;
135 }
136
137 /**
138 * Set same address is to be merged.
139 *
140 * @param bool $isMergeSameAddress
141 */
142 public function setIsMergeSameAddress(bool $isMergeSameAddress) {
143 $this->isMergeSameAddress = $isMergeSameAddress;
144 }
145
146 /**
147 * Additional fields required to export postal fields.
148 *
149 * @var array
150 */
151 protected $additionalFieldsForPostalExport = [];
152
153 /**
154 * Get additional fields required to do a postal export.
155 *
156 * @return array
157 */
158 public function getAdditionalFieldsForPostalExport() {
159 return $this->additionalFieldsForPostalExport;
160 }
161
162 /**
163 * Set additional fields required for a postal export.
164 */
165 public function setAdditionalFieldsForPostalExport() {
166 if ($this->getRequestedFields() && $this->isPostalableOnly()) {
167 $fields = ['is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1'];
168 foreach ($fields as $index => $field) {
169 if (!empty($this->getReturnProperties()[$field])) {
170 unset($fields[$index]);
171 }
172 }
173 $this->additionalFieldsForPostalExport = array_fill_keys($fields, 1);
174 }
175 }
176
177 /**
178 * Only export contacts that can receive postal mail.
179 *
180 * Includes being alive, having an address & not having do_not_mail.
181 *
182 * @var bool
183 */
184 protected $isPostalableOnly;
185
186 /**
187 * Key representing the head of household in the relationship array.
188 *
189 * e.g. ['8_b_a' => 'Household Member Is', '8_a_b = 'Household Member Of'.....]
190 *
191 * @var array
192 */
193 protected $relationshipTypes = [];
194
195 /**
196 * Array of properties to retrieve for relationships.
197 *
198 * @var array
199 */
200 protected $relationshipReturnProperties = [];
201
202 /**
203 * IDs of households that have already been exported.
204 *
205 * @var array
206 */
207 protected $exportedHouseholds = [];
208
209 /**
210 * Contacts to be merged by virtue of their shared address.
211 *
212 * @var array
213 */
214 protected $contactsToMerge = [];
215
216 /**
217 * Households to skip during export as they will be exported via their relationships anyway.
218 *
219 * @var array
220 */
221 protected $householdsToSkip = [];
222
223 /**
224 * Additional fields to return.
225 *
226 * This doesn't make much sense when we have a fields set but search build add it's own onto
227 * the 'Primary fields' (all) option.
228 *
229 * @var array
230 */
231 protected $additionalRequestedReturnProperties = [];
232
233 /**
234 * Get additional return properties.
235 *
236 * @return array
237 */
238 public function getAdditionalRequestedReturnProperties() {
239 return $this->additionalRequestedReturnProperties;
240 }
241
242 /**
243 * Set additional return properties.
244 *
245 * @param array $value
246 */
247 public function setAdditionalRequestedReturnProperties($value) {
248 // fix for CRM-7066
249 if (!empty($value['group'])) {
250 unset($value['group']);
251 $value['groups'] = 1;
252 }
253 $this->additionalRequestedReturnProperties = $value;
254 }
255
256 /**
257 * Get return properties by relationship.
258 * @return array
259 */
260 public function getRelationshipReturnProperties() {
261 return $this->relationshipReturnProperties;
262 }
263
264 /**
265 * Export values for related contacts.
266 *
267 * @var array
268 */
269 protected $relatedContactValues = [];
270
271 /**
272 * @var array
273 */
274 protected $returnProperties = [];
275
276 /**
277 * @var array
278 */
279 protected $outputSpecification = [];
280
281 /**
282 * @var string
283 */
284 protected $componentTable = '';
285
286 /**
287 * @return string
288 */
289 public function getComponentTable() {
290 return $this->componentTable;
291 }
292
293 /**
294 * Set the component table (if any).
295 *
296 * @param string $componentTable
297 */
298 public function setComponentTable($componentTable) {
299 $this->componentTable = $componentTable;
300 }
301
302 /**
303 * Clause from component search.
304 *
305 * @var string
306 */
307 protected $componentClause = '';
308
309 /**
310 * @return string
311 */
312 public function getComponentClause() {
313 return $this->componentClause;
314 }
315
316 /**
317 * @param string $componentClause
318 */
319 public function setComponentClause($componentClause) {
320 $this->componentClause = $componentClause;
321 }
322
323 /**
324 * Name of a temporary table created to hold the results.
325 *
326 * Current decision making on when to create a temp table is kinda bad so this might change
327 * a bit as it is reviewed but basically we need a temp table or similar to calculate merging
328 * addresses. Merging households is handled in php. We create a temp table even when we don't need them.
329 *
330 * @var string
331 */
332 protected $temporaryTable;
333
334 /**
335 * @return string
336 */
337 public function getTemporaryTable(): string {
338 return $this->temporaryTable;
339 }
340
341 /**
342 * @param string $temporaryTable
343 */
344 public function setTemporaryTable(string $temporaryTable) {
345 $this->temporaryTable = $temporaryTable;
346 }
347
348 protected $postalGreetingTemplate;
349
350 /**
351 * @return mixed
352 */
353 public function getPostalGreetingTemplate() {
354 return $this->postalGreetingTemplate;
355 }
356
357 /**
358 * @param mixed $postalGreetingTemplate
359 */
360 public function setPostalGreetingTemplate($postalGreetingTemplate) {
361 $this->postalGreetingTemplate = $postalGreetingTemplate;
362 }
363
364 /**
365 * @return mixed
366 */
367 public function getAddresseeGreetingTemplate() {
368 return $this->addresseeGreetingTemplate;
369 }
370
371 /**
372 * @param mixed $addresseeGreetingTemplate
373 */
374 public function setAddresseeGreetingTemplate($addresseeGreetingTemplate) {
375 $this->addresseeGreetingTemplate = $addresseeGreetingTemplate;
376 }
377
378 protected $addresseeGreetingTemplate;
379
380 /**
381 * CRM_Export_BAO_ExportProcessor constructor.
382 *
383 * @param int $exportMode
384 * @param array|null $requestedFields
385 * @param string $queryOperator
386 * @param bool $isMergeSameHousehold
387 * @param bool $isPostalableOnly
388 * @param bool $isMergeSameAddress
389 * @param array $formValues
390 * Values from the export options form on contact export. We currently support these keys
391 * - postal_greeting
392 * - postal_other
393 * - addresee_greeting
394 * - addressee_other
395 */
396 public function __construct($exportMode, $requestedFields, $queryOperator, $isMergeSameHousehold = FALSE, $isPostalableOnly = FALSE, $isMergeSameAddress = FALSE, $formValues = []) {
397 $this->setExportMode($exportMode);
398 $this->setQueryMode();
399 $this->setQueryOperator($queryOperator);
400 $this->setRequestedFields($requestedFields);
401 $this->setRelationshipTypes();
402 $this->setIsMergeSameHousehold($isMergeSameHousehold || $isMergeSameAddress);
403 $this->setIsPostalableOnly($isPostalableOnly);
404 $this->setIsMergeSameAddress($isMergeSameAddress);
405 $this->setReturnProperties($this->determineReturnProperties());
406 $this->setAdditionalFieldsForSameAddressMerge();
407 $this->setAdditionalFieldsForPostalExport();
408 $this->setHouseholdMergeReturnProperties();
409 $this->setGreetingStringsForSameAddressMerge($formValues);
410 $this->setGreetingOptions();
411 }
412
413 /**
414 * Set the greeting options, if relevant.
415 */
416 public function setGreetingOptions() {
417 if ($this->isMergeSameAddress()) {
418 $this->greetingOptions['addressee'] = CRM_Core_OptionGroup::values('addressee');
419 $this->greetingOptions['postal_greeting'] = CRM_Core_OptionGroup::values('postal_greeting');
420 }
421 }
422
423 /**
424 * @return bool
425 */
426 public function isPostalableOnly() {
427 return $this->isPostalableOnly;
428 }
429
430 /**
431 * @param bool $isPostalableOnly
432 */
433 public function setIsPostalableOnly($isPostalableOnly) {
434 $this->isPostalableOnly = $isPostalableOnly;
435 }
436
437 /**
438 * @return array|null
439 */
440 public function getRequestedFields() {
441 return empty($this->requestedFields) ? NULL : $this->requestedFields;
442 }
443
444 /**
445 * @param array|null $requestedFields
446 */
447 public function setRequestedFields($requestedFields) {
448 $this->requestedFields = $requestedFields;
449 }
450
451 /**
452 * @return array
453 */
454 public function getReturnProperties() {
455 return array_merge($this->returnProperties, $this->getAdditionalRequestedReturnProperties(), $this->getAdditionalFieldsForSameAddressMerge(), $this->getAdditionalFieldsForPostalExport());
456 }
457
458 /**
459 * @param array $returnProperties
460 */
461 public function setReturnProperties($returnProperties) {
462 $this->returnProperties = $returnProperties;
463 }
464
465 /**
466 * @return array
467 */
468 public function getRelationshipTypes() {
469 return $this->relationshipTypes;
470 }
471
472 /**
473 */
474 public function setRelationshipTypes() {
475 $this->relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(
476 NULL,
477 NULL,
478 NULL,
479 NULL,
480 TRUE,
481 'name',
482 FALSE
483 );
484 }
485
486 /**
487 * Set the value for a relationship type field.
488 *
489 * In this case we are building up an array of properties for a related contact.
490 *
491 * These may be used for direct exporting or for merge to household depending on the
492 * options selected.
493 *
494 * @param string $relationshipType
495 * @param int $contactID
496 * @param string $field
497 * @param string $value
498 */
499 public function setRelationshipValue($relationshipType, $contactID, $field, $value) {
500 $this->relatedContactValues[$relationshipType][$contactID][$field] = $value;
501 if ($field === 'id' && $this->isHouseholdMergeRelationshipTypeKey($relationshipType)) {
502 $this->householdsToSkip[] = $value;
503 }
504 }
505
506 /**
507 * Get the value for a relationship type field.
508 *
509 * In this case we are building up an array of properties for a related contact.
510 *
511 * These may be used for direct exporting or for merge to household depending on the
512 * options selected.
513 *
514 * @param string $relationshipType
515 * @param int $contactID
516 * @param string $field
517 *
518 * @return string
519 */
520 public function getRelationshipValue($relationshipType, $contactID, $field) {
521 return $this->relatedContactValues[$relationshipType][$contactID][$field] ?? '';
522 }
523
524 /**
525 * Get the id of the related household.
526 *
527 * @param int $contactID
528 * @param string $relationshipType
529 *
530 * @return int
531 */
532 public function getRelatedHouseholdID($contactID, $relationshipType) {
533 return $this->relatedContactValues[$relationshipType][$contactID]['id'];
534 }
535
536 /**
537 * Has the household already been exported.
538 *
539 * @param int $housholdContactID
540 *
541 * @return bool
542 */
543 public function isHouseholdExported($housholdContactID) {
544 return isset($this->exportedHouseholds[$housholdContactID]);
545
546 }
547
548 /**
549 * @return bool
550 */
551 public function isMergeSameHousehold() {
552 return $this->isMergeSameHousehold;
553 }
554
555 /**
556 * @param bool $isMergeSameHousehold
557 */
558 public function setIsMergeSameHousehold($isMergeSameHousehold) {
559 $this->isMergeSameHousehold = $isMergeSameHousehold;
560 }
561
562 /**
563 * Return relationship types for household merge.
564 *
565 * @return mixed
566 */
567 public function getHouseholdRelationshipTypes() {
568 if (!$this->isMergeSameHousehold()) {
569 return [];
570 }
571 return [
572 CRM_Utils_Array::key('Household Member of', $this->getRelationshipTypes()),
573 CRM_Utils_Array::key('Head of Household for', $this->getRelationshipTypes()),
574 ];
575 }
576
577 /**
578 * @param $fieldName
579 * @return bool
580 */
581 public function isRelationshipTypeKey($fieldName) {
582 return array_key_exists($fieldName, $this->relationshipTypes);
583 }
584
585 /**
586 * @param $fieldName
587 * @return bool
588 */
589 public function isHouseholdMergeRelationshipTypeKey($fieldName) {
590 return in_array($fieldName, $this->getHouseholdRelationshipTypes());
591 }
592
593 /**
594 * @return string
595 */
596 public function getQueryOperator() {
597 return $this->queryOperator;
598 }
599
600 /**
601 * @param string $queryOperator
602 */
603 public function setQueryOperator($queryOperator) {
604 $this->queryOperator = $queryOperator;
605 }
606
607 /**
608 * @return array
609 */
610 public function getIds() {
611 return $this->ids;
612 }
613
614 /**
615 * @param array $ids
616 */
617 public function setIds($ids) {
618 $this->ids = $ids;
619 }
620
621 /**
622 * @return array
623 */
624 public function getQueryFields() {
625 return array_merge(
626 $this->queryFields,
627 $this->getComponentPaymentFields()
628 );
629 }
630
631 /**
632 * @param array $queryFields
633 */
634 public function setQueryFields($queryFields) {
635 // legacy hacks - we add these to queryFields because this
636 // pseudometadata is currently required.
637 $queryFields['im_provider']['pseudoconstant']['var'] = 'imProviders';
638 $queryFields['country']['context'] = 'country';
639 $queryFields['world_region']['context'] = 'country';
640 $queryFields['state_province']['context'] = 'province';
641 $queryFields['contact_id'] = ['title' => ts('Contact ID'), 'type' => CRM_Utils_Type::T_INT];
642 $queryFields['tags']['type'] = CRM_Utils_Type::T_LONGTEXT;
643 $queryFields['groups']['type'] = CRM_Utils_Type::T_LONGTEXT;
644 $queryFields['notes']['type'] = CRM_Utils_Type::T_LONGTEXT;
645 // Set the label to gender for gender_id as we it's ... magic (not in a good way).
646 // In other places the query object offers e.g contribution_status & contribution_status_id
647 $queryFields['gender_id']['title'] = ts('Gender');
648 $this->queryFields = $queryFields;
649 }
650
651 /**
652 * @return int
653 */
654 public function getQueryMode() {
655 return $this->queryMode;
656 }
657
658 /**
659 * Set the query mode based on the export mode.
660 */
661 public function setQueryMode() {
662
663 switch ($this->getExportMode()) {
664 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
665 $this->queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
666 break;
667
668 case CRM_Export_Form_Select::EVENT_EXPORT:
669 $this->queryMode = CRM_Contact_BAO_Query::MODE_EVENT;
670 break;
671
672 case CRM_Export_Form_Select::MEMBER_EXPORT:
673 $this->queryMode = CRM_Contact_BAO_Query::MODE_MEMBER;
674 break;
675
676 case CRM_Export_Form_Select::PLEDGE_EXPORT:
677 $this->queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE;
678 break;
679
680 case CRM_Export_Form_Select::CASE_EXPORT:
681 $this->queryMode = CRM_Contact_BAO_Query::MODE_CASE;
682 break;
683
684 case CRM_Export_Form_Select::GRANT_EXPORT:
685 $this->queryMode = CRM_Contact_BAO_Query::MODE_GRANT;
686 break;
687
688 case CRM_Export_Form_Select::ACTIVITY_EXPORT:
689 $this->queryMode = CRM_Contact_BAO_Query::MODE_ACTIVITY;
690 break;
691
692 default:
693 $this->queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
694 }
695 }
696
697 /**
698 * @return int
699 */
700 public function getExportMode() {
701 return $this->exportMode;
702 }
703
704 /**
705 * @param int $exportMode
706 */
707 public function setExportMode($exportMode) {
708 $this->exportMode = $exportMode;
709 }
710
711 /**
712 * Get the name for the export file.
713 *
714 * @return string
715 */
716 public function getExportFileName() {
717 switch ($this->getExportMode()) {
718 case CRM_Export_Form_Select::CONTACT_EXPORT:
719 return ts('CiviCRM Contact Search');
720
721 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
722 return ts('CiviCRM Contribution Search');
723
724 case CRM_Export_Form_Select::MEMBER_EXPORT:
725 return ts('CiviCRM Member Search');
726
727 case CRM_Export_Form_Select::EVENT_EXPORT:
728 return ts('CiviCRM Participant Search');
729
730 case CRM_Export_Form_Select::PLEDGE_EXPORT:
731 return ts('CiviCRM Pledge Search');
732
733 case CRM_Export_Form_Select::CASE_EXPORT:
734 return ts('CiviCRM Case Search');
735
736 case CRM_Export_Form_Select::GRANT_EXPORT:
737 return ts('CiviCRM Grant Search');
738
739 case CRM_Export_Form_Select::ACTIVITY_EXPORT:
740 return ts('CiviCRM Activity Search');
741
742 default:
743 // Legacy code suggests the value could be 'financial' - ie. something
744 // other than what should be accepted. However, I suspect that this line is
745 // never hit.
746 return ts('CiviCRM Search');
747 }
748 }
749
750 /**
751 * Get the label for the header row based on the field to output.
752 *
753 * @param string $field
754 *
755 * @return string
756 */
757 public function getHeaderForRow($field) {
758 if (substr($field, -11) === 'campaign_id') {
759 // @todo - set this correctly in the xml rather than here.
760 // This will require a generalised handling cleanup
761 return ts('Campaign ID');
762 }
763 if ($this->isMergeSameHousehold() && !$this->isMergeSameAddress() && $field === 'id') {
764 // This is weird - even if we are merging households not every contact in the export is a household so this would not be accurate.
765 return ts('Household ID');
766 }
767 elseif (isset($this->getQueryFields()[$field]['title'])) {
768 return $this->getQueryFields()[$field]['title'];
769 }
770 elseif ($this->isExportPaymentFields() && array_key_exists($field, $this->getcomponentPaymentFields())) {
771 return CRM_Utils_Array::value($field, $this->getcomponentPaymentFields())['title'];
772 }
773 else {
774 return $field;
775 }
776 }
777
778 /**
779 * @param $params
780 * @param $order
781 *
782 * @return array
783 */
784 public function runQuery($params, $order) {
785 $returnProperties = $this->getReturnProperties();
786 $params = array_merge($params, $this->getWhereParams());
787
788 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
789 FALSE, FALSE, $this->getQueryMode(),
790 FALSE, TRUE, TRUE, NULL, $this->getQueryOperator(),
791 NULL, TRUE
792 );
793
794 //sort by state
795 //CRM-15301
796 $query->_sort = $order;
797 [$select, $from, $where, $having] = $query->query();
798 $this->setQueryFields($query->_fields);
799 $whereClauses = ['trash_clause' => "contact_a.is_deleted != 1"];
800 if ($this->getComponentClause()) {
801 $whereClauses[] = $this->getComponentClause();
802 }
803 elseif ($this->getRequestedFields() && $this->getComponentTable() && $this->getComponentTable() !== 'civicrm_contact') {
804 $from .= " INNER JOIN " . $this->getComponentTable() . " ctTable ON ctTable.contact_id = contact_a.id ";
805 }
806
807 // CRM-13982 - check if is deleted
808 foreach ($params as $value) {
809 if ($value[0] === 'contact_is_deleted') {
810 unset($whereClauses['trash_clause']);
811 }
812 }
813
814 if ($this->isPostalableOnly) {
815 if (array_key_exists('street_address', $returnProperties)) {
816 $addressWhere = " civicrm_address.street_address <> ''";
817 if (array_key_exists('supplemental_address_1', $returnProperties)) {
818 // We need this to be an OR rather than AND on the street_address so, hack it in.
819 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
820 'address_options', TRUE, NULL, TRUE
821 );
822 if (!empty($addressOptions['supplemental_address_1'])) {
823 $addressWhere .= " OR civicrm_address.supplemental_address_1 <> ''";
824 }
825 }
826 $whereClauses['address'] = '(' . $addressWhere . ')';
827 }
828 }
829
830 if (empty($where)) {
831 $where = 'WHERE ' . implode(' AND ', $whereClauses);
832 }
833 else {
834 $where .= ' AND ' . implode(' AND ', $whereClauses);
835 }
836
837 $groupBy = $this->getGroupBy($query);
838 $queryString = "$select $from $where $having $groupBy";
839 if ($order) {
840 // always add contact_a.id to the ORDER clause
841 // so the order is deterministic
842 //CRM-15301
843 if (strpos('contact_a.id', $order) === FALSE) {
844 $order .= ", contact_a.id";
845 }
846
847 [$field, $dir] = explode(' ', $order, 2);
848 $field = trim($field);
849 if (!empty($this->getReturnProperties()[$field])) {
850 //CRM-15301
851 $queryString .= " ORDER BY $order";
852 }
853 }
854 return [$query, $queryString];
855 }
856
857 /**
858 * Add a row to the specification for how to output data.
859 *
860 * @param string $key
861 * @param string $relationshipType
862 * @param string $locationType
863 * @param int $entityTypeID phone_type_id or provider_id for phone or im fields.
864 */
865 public function addOutputSpecification($key, $relationshipType = NULL, $locationType = NULL, $entityTypeID = NULL) {
866 $entityLabel = '';
867 if ($entityTypeID) {
868 if ($key === 'phone') {
869 $entityLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', $entityTypeID);
870 }
871 if ($key === 'im') {
872 $entityLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_IM', 'provider_id', $entityTypeID);
873 }
874 }
875
876 // These oddly constructed keys are for legacy reasons. Altering them will affect test success
877 // but in time it may be good to rationalise them.
878 $label = $this->getOutputSpecificationLabel($key, $relationshipType, $locationType, $entityLabel);
879 $index = $this->getOutputSpecificationIndex($key, $relationshipType, $locationType, $entityTypeID);
880 $fieldKey = $this->getOutputSpecificationFieldKey($key, $relationshipType, $locationType, $entityTypeID);
881
882 $this->outputSpecification[$index]['header'] = $label;
883 $this->outputSpecification[$index]['sql_columns'] = $this->getSqlColumnDefinition($fieldKey, $key);
884
885 if ($relationshipType && $this->isHouseholdMergeRelationshipTypeKey($relationshipType)) {
886 $this->setColumnAsCalculationOnly($index);
887 }
888 $this->outputSpecification[$index]['metadata'] = $this->getMetaDataForField($key);
889 }
890
891 /**
892 * Get the metadata for the given field.
893 *
894 * @param $key
895 *
896 * @return array
897 */
898 public function getMetaDataForField($key) {
899 $mappings = ['contact_id' => 'id'];
900 if (isset($this->getQueryFields()[$key])) {
901 return $this->getQueryFields()[$key];
902 }
903 if (isset($mappings[$key])) {
904 return $this->getQueryFields()[$mappings[$key]];
905 }
906 return [];
907 }
908
909 /**
910 * @param $key
911 */
912 public function setSqlColumnDefn($key) {
913 $this->outputSpecification[$this->getMungedFieldName($key)]['sql_columns'] = $this->getSqlColumnDefinition($key, $this->getMungedFieldName($key));
914 }
915
916 /**
917 * Mark a column as only required for calculations.
918 *
919 * Do not include the row with headers.
920 *
921 * @param string $column
922 */
923 public function setColumnAsCalculationOnly($column) {
924 $this->outputSpecification[$column]['do_not_output_to_csv'] = TRUE;
925 }
926
927 /**
928 * @return array
929 */
930 public function getHeaderRows() {
931 $headerRows = [];
932 foreach ($this->outputSpecification as $key => $spec) {
933 if (empty($spec['do_not_output_to_csv'])) {
934 $headerRows[] = $spec['header'];
935 }
936 }
937 return $headerRows;
938 }
939
940 /**
941 * @return array
942 */
943 public function getSQLColumns() {
944 $sqlColumns = [];
945 foreach ($this->outputSpecification as $key => $spec) {
946 if (empty($spec['do_not_output_to_sql'])) {
947 $sqlColumns[$key] = $spec['sql_columns'];
948 }
949 }
950 return $sqlColumns;
951 }
952
953 /**
954 * @return array
955 */
956 public function getMetadata() {
957 $metadata = [];
958 foreach ($this->outputSpecification as $key => $spec) {
959 $metadata[$key] = $spec['metadata'];
960 }
961 return $metadata;
962 }
963
964 /**
965 * Build the row for output.
966 *
967 * @param \CRM_Contact_BAO_Query $query
968 * @param CRM_Core_DAO $iterationDAO
969 * @param array $outputColumns
970 * @param $paymentDetails
971 * @param $addPaymentHeader
972 *
973 * @return array|bool
974 */
975 public function buildRow($query, $iterationDAO, $outputColumns, $paymentDetails, $addPaymentHeader) {
976 $paymentTableId = $this->getPaymentTableID();
977 if ($this->isHouseholdToSkip($iterationDAO->contact_id)) {
978 return FALSE;
979 }
980 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
981
982 $row = [];
983 $householdMergeRelationshipType = $this->getHouseholdMergeTypeForRow($iterationDAO->contact_id);
984 if ($householdMergeRelationshipType) {
985 $householdID = $this->getRelatedHouseholdID($iterationDAO->contact_id, $householdMergeRelationshipType);
986 if ($this->isHouseholdExported($householdID)) {
987 return FALSE;
988 }
989 foreach (array_keys($outputColumns) as $column) {
990 $row[$column] = $this->getRelationshipValue($householdMergeRelationshipType, $iterationDAO->contact_id, $column);
991 }
992 $this->markHouseholdExported($householdID);
993 return $row;
994 }
995
996 $query->convertToPseudoNames($iterationDAO);
997
998 //first loop through output columns so that we return what is required, and in same order.
999 foreach ($outputColumns as $field => $value) {
1000 // add im_provider to $dao object
1001 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
1002 $iterationDAO->im_provider = $iterationDAO->provider_id;
1003 }
1004
1005 //build row values (data)
1006 $fieldValue = NULL;
1007 if (property_exists($iterationDAO, $field)) {
1008 $fieldValue = $iterationDAO->$field;
1009 // to get phone type from phone type id
1010 if ($field == 'provider_id' || $field == 'im_provider') {
1011 $fieldValue = $imProviders[$fieldValue] ?? NULL;
1012 }
1013 elseif (strstr($field, 'master_id')) {
1014 // @todo - why not just $field === 'master_id' - what else would it be?
1015 $masterAddressId = $iterationDAO->$field ?? NULL;
1016 // get display name of contact that address is shared.
1017 $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId);
1018 }
1019 }
1020
1021 if ($this->isRelationshipTypeKey($field)) {
1022 $this->buildRelationshipFieldsForRow($row, $iterationDAO->contact_id, $value, $field);
1023 }
1024 else {
1025 $row[$field] = $this->getTransformedFieldValue($field, $iterationDAO, $fieldValue, $paymentDetails);
1026 }
1027 }
1028
1029 // If specific payment fields have been selected for export, payment
1030 // data will already be in $row. Otherwise, add payment related
1031 // information, if appropriate.
1032 if ($addPaymentHeader) {
1033 if (!$this->isExportSpecifiedPaymentFields()) {
1034 $nullContributionDetails = array_fill_keys(array_keys($this->getPaymentHeaders()), NULL);
1035 if ($this->isExportPaymentFields()) {
1036 $paymentData = $paymentDetails[$row[$paymentTableId]] ?? NULL;
1037 if (!is_array($paymentData) || empty($paymentData)) {
1038 $paymentData = $nullContributionDetails;
1039 }
1040 $row = array_merge($row, $paymentData);
1041 }
1042 elseif (!empty($paymentDetails)) {
1043 $row = array_merge($row, $nullContributionDetails);
1044 }
1045 }
1046 }
1047 //remove organization name for individuals if it is set for current employer
1048 if (!empty($row['contact_type']) &&
1049 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1050 ) {
1051 $row['organization_name'] = '';
1052 }
1053 return $row;
1054 }
1055
1056 /**
1057 * If this row has a household whose details we should use get the relationship type key.
1058 *
1059 * @param $contactID
1060 *
1061 * @return bool
1062 */
1063 public function getHouseholdMergeTypeForRow($contactID) {
1064 if (!$this->isMergeSameHousehold()) {
1065 return FALSE;
1066 }
1067 foreach ($this->getHouseholdRelationshipTypes() as $relationshipType) {
1068 if (isset($this->relatedContactValues[$relationshipType][$contactID])) {
1069 return $relationshipType;
1070 }
1071 }
1072 }
1073
1074 /**
1075 * Mark the given household as already exported.
1076 *
1077 * @param $householdID
1078 */
1079 public function markHouseholdExported($householdID) {
1080 $this->exportedHouseholds[$householdID] = $householdID;
1081 }
1082
1083 /**
1084 * @param $field
1085 * @param $iterationDAO
1086 * @param $fieldValue
1087 * @param $paymentDetails
1088 *
1089 * @return string
1090 * @throws \CRM_Core_Exception
1091 * @throws \CiviCRM_API3_Exception
1092 */
1093 public function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $paymentDetails) {
1094
1095 $i18n = CRM_Core_I18n::singleton();
1096 if ($field == 'id') {
1097 return $iterationDAO->contact_id;
1098 // special case for calculated field
1099 }
1100 elseif ($field == 'source_contact_id') {
1101 return $iterationDAO->contact_id;
1102 }
1103 elseif ($field == 'pledge_balance_amount') {
1104 return $iterationDAO->pledge_amount - $iterationDAO->pledge_total_paid;
1105 // special case for calculated field
1106 }
1107 elseif ($field == 'pledge_next_pay_amount') {
1108 return $iterationDAO->pledge_next_pay_amount + $iterationDAO->pledge_outstanding_amount;
1109 }
1110 elseif (isset($fieldValue) &&
1111 $fieldValue != ''
1112 ) {
1113 //check for custom data
1114 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
1115 $html_type = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'html_type');
1116
1117 //need to calculate the link to the file for file custom data
1118 if ($html_type === 'File' && $fieldValue) {
1119 $result = civicrm_api3('attachment', 'get', ['return' => ['url'], 'id' => $fieldValue]);
1120 return $result['values'][$result['id']]['url'];
1121 }
1122
1123 // Do not export HTML markup for links
1124 if ($html_type === 'Link' && $fieldValue) {
1125 return $fieldValue;
1126 }
1127
1128 return CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
1129 }
1130 elseif (in_array($field, [
1131 'email_greeting',
1132 'postal_greeting',
1133 'addressee',
1134 ])) {
1135 //special case for greeting replacement
1136 $fldValue = "{$field}_display";
1137 return $iterationDAO->$fldValue;
1138 }
1139 else {
1140 //normal fields with a touch of CRM-3157
1141 switch ($field) {
1142 case 'country':
1143 case 'world_region':
1144 return $i18n->crm_translate($fieldValue, ['context' => 'country']);
1145
1146 case 'state_province':
1147 return $i18n->crm_translate($fieldValue, ['context' => 'province']);
1148
1149 case 'gender':
1150 case 'preferred_communication_method':
1151 case 'preferred_mail_format':
1152 case 'communication_style':
1153 return $i18n->crm_translate($fieldValue);
1154
1155 default:
1156 $fieldSpec = $this->outputSpecification[$this->getMungedFieldName($field)]['metadata'];
1157 // No I don't know why we do it this way & whether we could
1158 // make better use of pseudoConstants.
1159 if (!empty($fieldSpec['context'])) {
1160 return $i18n->crm_translate($fieldValue, $fieldSpec);
1161 }
1162 if (!empty($fieldSpec['pseudoconstant']) && !empty($fieldSpec['hasLocationType']) && $fieldSpec['name'] !== 'phone_type_id') {
1163 if (!empty($fieldSpec['bao'])) {
1164 $transformedValue = CRM_Core_PseudoConstant::getLabel($fieldSpec['bao'], $fieldSpec['name'], $fieldValue);
1165 if ($transformedValue) {
1166 return $transformedValue;
1167 }
1168 return $fieldValue;
1169 }
1170 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
1171 // but I have to reach a stable point....
1172 $varName = $fieldSpec['pseudoconstant']['var'];
1173 if ($varName === 'imProviders') {
1174 return CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
1175 }
1176 }
1177 return $fieldValue;
1178 }
1179 }
1180 }
1181 elseif ($this->isExportSpecifiedPaymentFields() && array_key_exists($field, $this->getcomponentPaymentFields())) {
1182 $paymentTableId = $this->getPaymentTableID();
1183 $paymentData = $paymentDetails[$iterationDAO->$paymentTableId] ?? NULL;
1184 $payFieldMapper = [
1185 'componentPaymentField_total_amount' => 'total_amount',
1186 'componentPaymentField_contribution_status' => 'contribution_status',
1187 'componentPaymentField_payment_instrument' => 'pay_instru',
1188 'componentPaymentField_transaction_id' => 'trxn_id',
1189 'componentPaymentField_received_date' => 'receive_date',
1190 ];
1191 return CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, '');
1192 }
1193 else {
1194 // if field is empty or null
1195 return '';
1196 }
1197 }
1198
1199 /**
1200 * Get array of fields to return, over & above those defined in the main contact exportable fields.
1201 *
1202 * These include export mode specific fields & some fields apparently required as 'exportableFields'
1203 * but not returned by the function of the same name.
1204 *
1205 * @return array
1206 * Array of fields to return in the format ['field_name' => 1,...]
1207 */
1208 public function getAdditionalReturnProperties() {
1209 if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_CONTACTS) {
1210 $componentSpecificFields = [];
1211 }
1212 else {
1213 $componentSpecificFields = CRM_Contact_BAO_Query::defaultReturnProperties($this->getQueryMode());
1214 }
1215 if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_PLEDGE) {
1216 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Pledge_BAO_Query::extraReturnProperties($this->getQueryMode()));
1217 unset($componentSpecificFields['contribution_status_id']);
1218 unset($componentSpecificFields['pledge_status_id']);
1219 unset($componentSpecificFields['pledge_payment_status_id']);
1220 }
1221 if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_CASE) {
1222 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Case_BAO_Query::extraReturnProperties($this->getQueryMode()));
1223 }
1224 if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
1225 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Contribute_BAO_Query::softCreditReturnProperties(TRUE));
1226 unset($componentSpecificFields['contribution_status_id']);
1227 }
1228 return $componentSpecificFields;
1229 }
1230
1231 /**
1232 * Should payment fields be appended to the export.
1233 *
1234 * (This is pretty hacky so hopefully this function won't last long - notice
1235 * how obviously it should be part of the above function!).
1236 */
1237 public function isExportPaymentFields() {
1238 if ($this->getRequestedFields() === NULL
1239 && in_array($this->getQueryMode(), [
1240 CRM_Contact_BAO_Query::MODE_EVENT,
1241 CRM_Contact_BAO_Query::MODE_MEMBER,
1242 CRM_Contact_BAO_Query::MODE_PLEDGE,
1243 ])) {
1244 return TRUE;
1245 }
1246 elseif ($this->isExportSpecifiedPaymentFields()) {
1247 return TRUE;
1248 }
1249 return FALSE;
1250 }
1251
1252 /**
1253 * Has specific payment fields been requested (as opposed to via all fields).
1254 *
1255 * If specific fields have been requested then they get added at various points.
1256 *
1257 * @return bool
1258 */
1259 public function isExportSpecifiedPaymentFields() {
1260 if ($this->getRequestedFields() !== NULL && $this->hasRequestedComponentPaymentFields()) {
1261 return TRUE;
1262 }
1263 }
1264
1265 /**
1266 * Get the name of the id field in the table that connects contributions to the export entity.
1267 */
1268 public function getPaymentTableID() {
1269 if ($this->getRequestedFields() === NULL) {
1270 $mapping = [
1271 CRM_Contact_BAO_Query::MODE_EVENT => 'participant_id',
1272 CRM_Contact_BAO_Query::MODE_MEMBER => 'membership_id',
1273 CRM_Contact_BAO_Query::MODE_PLEDGE => 'pledge_payment_id',
1274 ];
1275 return isset($mapping[$this->getQueryMode()]) ? $mapping[$this->getQueryMode()] : '';
1276 }
1277 elseif ($this->hasRequestedComponentPaymentFields()) {
1278 return 'participant_id';
1279 }
1280 return FALSE;
1281 }
1282
1283 /**
1284 * Have component payment fields been requested.
1285 *
1286 * @return bool
1287 */
1288 protected function hasRequestedComponentPaymentFields() {
1289 if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_EVENT) {
1290 $participantPaymentFields = array_intersect_key($this->getComponentPaymentFields(), $this->getReturnProperties());
1291 if (!empty($participantPaymentFields)) {
1292 return TRUE;
1293 }
1294 }
1295 return FALSE;
1296 }
1297
1298 /**
1299 * Get fields that indicate payment fields have been requested for a component.
1300 *
1301 * Ideally this should be protected but making it temporarily public helps refactoring..
1302 *
1303 * @return array
1304 */
1305 public function getComponentPaymentFields() {
1306 return [
1307 'componentPaymentField_total_amount' => ['title' => ts('Total Amount'), 'type' => CRM_Utils_Type::T_MONEY],
1308 'componentPaymentField_contribution_status' => ['title' => ts('Contribution Status'), 'type' => CRM_Utils_Type::T_STRING],
1309 'componentPaymentField_received_date' => ['title' => ts('Date Received'), 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME],
1310 'componentPaymentField_payment_instrument' => ['title' => ts('Payment Method'), 'type' => CRM_Utils_Type::T_STRING],
1311 'componentPaymentField_transaction_id' => ['title' => ts('Transaction ID'), 'type' => CRM_Utils_Type::T_STRING],
1312 ];
1313 }
1314
1315 /**
1316 * Get headers for payment fields.
1317 *
1318 * Returns an array of contribution fields when the entity supports payment fields and specific fields
1319 * are not specified. This is a transitional function for refactoring legacy code.
1320 */
1321 public function getPaymentHeaders() {
1322 if ($this->isExportPaymentFields() && !$this->isExportSpecifiedPaymentFields()) {
1323 return CRM_Utils_Array::collect('title', $this->getcomponentPaymentFields());
1324 }
1325 return [];
1326 }
1327
1328 /**
1329 * Get the default properties when not specified.
1330 *
1331 * In the UI this appears as 'Primary fields only' but in practice it's
1332 * most of the kitchen sink and the hallway closet thrown in.
1333 *
1334 * Since CRM-952 custom fields are excluded, but no other form of mercy is shown.
1335 *
1336 * @return array
1337 */
1338 public function getDefaultReturnProperties() {
1339 $returnProperties = [];
1340 $fields = CRM_Contact_BAO_Contact::exportableFields('All', TRUE, TRUE);
1341 $skippedFields = ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_CONTACTS) ? [] : [
1342 'groups',
1343 'tags',
1344 'notes',
1345 ];
1346
1347 foreach ($fields as $key => $var) {
1348 if ($key && (substr($key, 0, 6) != 'custom') && !in_array($key, $skippedFields)) {
1349 $returnProperties[$key] = 1;
1350 }
1351 }
1352 $returnProperties = array_merge($returnProperties, $this->getAdditionalReturnProperties());
1353 return $returnProperties;
1354 }
1355
1356 /**
1357 * Add the field to relationship return properties & return it.
1358 *
1359 * This function is doing both setting & getting which is yuck but it is an interim
1360 * refactor.
1361 *
1362 * @param array $value
1363 * @param string $relationshipKey
1364 *
1365 * @return array
1366 */
1367 public function setRelationshipReturnProperties($value, $relationshipKey) {
1368 $relationField = $value['name'];
1369 $relIMProviderId = NULL;
1370 $relLocTypeId = $value['location_type_id'] ?? NULL;
1371 $locationName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_Address', 'location_type_id', $relLocTypeId);
1372 $relPhoneTypeId = CRM_Utils_Array::value('phone_type_id', $value, ($locationName ? 'Primary' : NULL));
1373 $relIMProviderId = CRM_Utils_Array::value('im_provider_id', $value, ($locationName ? 'Primary' : NULL));
1374 if (in_array($relationField, $this->getValidLocationFields()) && $locationName) {
1375 if ($relationField === 'phone') {
1376 $this->relationshipReturnProperties[$relationshipKey]['location'][$locationName]['phone-' . $relPhoneTypeId] = 1;
1377 }
1378 elseif ($relationField === 'im') {
1379 $this->relationshipReturnProperties[$relationshipKey]['location'][$locationName]['im-' . $relIMProviderId] = 1;
1380 }
1381 else {
1382 $this->relationshipReturnProperties[$relationshipKey]['location'][$locationName][$relationField] = 1;
1383 }
1384 }
1385 else {
1386 $this->relationshipReturnProperties[$relationshipKey][$relationField] = 1;
1387 }
1388 return $this->relationshipReturnProperties[$relationshipKey];
1389 }
1390
1391 /**
1392 * Add the main return properties to the household merge properties if needed for merging.
1393 *
1394 * If we are using household merge we need to add these to the relationship properties to
1395 * be retrieved.
1396 */
1397 public function setHouseholdMergeReturnProperties() {
1398 if ($this->isMergeSameHousehold()) {
1399 $returnProperties = $this->getReturnProperties();
1400 $returnProperties = array_diff_key($returnProperties, array_fill_keys(['location_type', 'im_provider'], 1));
1401 foreach ($this->getHouseholdRelationshipTypes() as $householdRelationshipType) {
1402 $this->relationshipReturnProperties[$householdRelationshipType] = $returnProperties;
1403 }
1404 }
1405 }
1406
1407 /**
1408 * Get the default location fields to request.
1409 *
1410 * @return array
1411 */
1412 public function getValidLocationFields() {
1413 return [
1414 'street_address',
1415 'supplemental_address_1',
1416 'supplemental_address_2',
1417 'supplemental_address_3',
1418 'city',
1419 'postal_code',
1420 'postal_code_suffix',
1421 'geo_code_1',
1422 'geo_code_2',
1423 'state_province',
1424 'country',
1425 'phone',
1426 'email',
1427 'im',
1428 ];
1429 }
1430
1431 /**
1432 * Get the sql column definition for the given field.
1433 *
1434 * @param string $fieldName
1435 * @param string $columnName
1436 *
1437 * @return mixed
1438 */
1439 public function getSqlColumnDefinition($fieldName, $columnName) {
1440
1441 // early exit for master_id, CRM-12100
1442 // in the DB it is an ID, but in the export, we retrieve the display_name of the master record
1443 if ($columnName === 'master_id') {
1444 return "`$fieldName` varchar(128)";
1445 }
1446
1447 $queryFields = $this->getQueryFields();
1448 // @todo remove the e-notice avoidance here, ensure all columns are declared.
1449 // tests will fail on the enotices until they all are & then all the 'else'
1450 // below can go.
1451 $fieldSpec = $queryFields[$columnName] ?? [];
1452 $type = $fieldSpec['type'] ?? ($fieldSpec['data_type'] ?? '');
1453 // set the sql columns
1454 if ($type) {
1455 switch ($type) {
1456 case CRM_Utils_Type::T_INT:
1457 case CRM_Utils_Type::T_BOOLEAN:
1458 if (in_array(CRM_Utils_Array::value('data_type', $fieldSpec), ['Country', 'StateProvince', 'ContactReference'])) {
1459 return "`$fieldName` text";
1460 }
1461 // some of those will be exported as a (localisable) string
1462 // @see https://lab.civicrm.org/dev/core/-/issues/2164
1463 return "`$fieldName` varchar(64)";
1464
1465 case CRM_Utils_Type::T_STRING:
1466 if (isset($fieldSpec['maxlength'])) {
1467 // A localized string for the preferred_mail_format does not fit
1468 // into the varchar(8) field.
1469 // @see https://lab.civicrm.org/dev/core/-/issues/2645
1470 switch ($fieldName) {
1471 case 'preferred_mail_format':
1472 return "`$fieldName` text(16)";
1473
1474 default:
1475 return "`$fieldName` varchar({$fieldSpec['maxlength']})";
1476 }
1477 }
1478 $dataType = $fieldSpec['data_type'] ?? '';
1479 // set the sql columns for custom data
1480 switch ($dataType) {
1481 case 'String':
1482 // May be option labels, which could be up to 512 characters
1483 $length = max(512, CRM_Utils_Array::value('text_length', $fieldSpec));
1484 return "`$fieldName` varchar($length)";
1485
1486 case 'Memo':
1487 return "`$fieldName` text";
1488
1489 default:
1490 return "`$fieldName` varchar(255)";
1491 }
1492
1493 case CRM_Utils_Type::T_TEXT:
1494 case CRM_Utils_Type::T_LONGTEXT:
1495 case CRM_Utils_Type::T_BLOB:
1496 case CRM_Utils_Type::T_MEDIUMBLOB:
1497 return "`$fieldName` longtext";
1498
1499 case CRM_Utils_Type::T_FLOAT:
1500 case CRM_Utils_Type::T_ENUM:
1501 case CRM_Utils_Type::T_DATE:
1502 case CRM_Utils_Type::T_TIME:
1503 case CRM_Utils_Type::T_TIMESTAMP:
1504 case CRM_Utils_Type::T_MONEY:
1505 case CRM_Utils_Type::T_EMAIL:
1506 case CRM_Utils_Type::T_URL:
1507 case CRM_Utils_Type::T_CCNUM:
1508 default:
1509 return "`$fieldName` varchar(32)";
1510 }
1511 }
1512 else {
1513 if (substr($fieldName, -3, 3) === '_id') {
1514 return "`$fieldName` varchar(255)";
1515 }
1516 return "`$fieldName` text";
1517 }
1518 }
1519
1520 /**
1521 * Get the munged field name.
1522 *
1523 * @param string $field
1524 * @return string
1525 */
1526 public function getMungedFieldName($field) {
1527 $fieldName = CRM_Utils_String::munge(strtolower($field), '_', 64);
1528 if ($fieldName == 'id') {
1529 $fieldName = 'civicrm_primary_id';
1530 }
1531 return $fieldName;
1532 }
1533
1534 /**
1535 * In order to respect the history of this class we need to index kinda illogically.
1536 *
1537 * On the bright side - this stuff is tested within a nano-byte of it's life.
1538 *
1539 * e.g '2-a-b_Home-City'
1540 *
1541 * @param string $key
1542 * @param string $relationshipType
1543 * @param string $locationType
1544 * @param $entityLabel
1545 *
1546 * @return string
1547 */
1548 protected function getOutputSpecificationIndex($key, $relationshipType, $locationType, $entityLabel) {
1549 if (!$relationshipType || $key !== 'id') {
1550 $key = $this->getMungedFieldName($key);
1551 }
1552 return $this->getMungedFieldName(
1553 ($relationshipType ? ($relationshipType . '_') : '')
1554 . ($locationType ? ($locationType . '_') : '')
1555 . $key
1556 . ($entityLabel ? ('_' . $entityLabel) : '')
1557 );
1558 }
1559
1560 /**
1561 * Get the compiled label for the column.
1562 *
1563 * e.g 'Gender', 'Employee Of-Home-city'
1564 *
1565 * @param string $key
1566 * @param string $relationshipType
1567 * @param string $locationType
1568 * @param string $entityLabel
1569 *
1570 * @return string
1571 */
1572 protected function getOutputSpecificationLabel($key, $relationshipType, $locationType, $entityLabel) {
1573 return ($relationshipType ? $this->getRelationshipTypes()[$relationshipType] . '-' : '')
1574 . ($locationType ? $locationType . '-' : '')
1575 . $this->getHeaderForRow($key)
1576 . ($entityLabel ? '-' . $entityLabel : '');
1577 }
1578
1579 /**
1580 * Get the mysql field name key.
1581 *
1582 * This key is locked in by tests but the reasons for the specific conventions -
1583 * ie. headings are used for keying fields in some cases, are likely
1584 * accidental rather than deliberate.
1585 *
1586 * This key is used for the output sql array.
1587 *
1588 * @param string $key
1589 * @param $relationshipType
1590 * @param $locationType
1591 * @param $entityLabel
1592 *
1593 * @return string
1594 */
1595 protected function getOutputSpecificationFieldKey($key, $relationshipType, $locationType, $entityLabel) {
1596 if (!$relationshipType || $key !== 'id') {
1597 $key = $this->getMungedFieldName($key);
1598 }
1599 $fieldKey = $this->getMungedFieldName(
1600 ($relationshipType ? ($relationshipType . '_') : '')
1601 . ($locationType ? ($locationType . '_') : '')
1602 . $key
1603 . ($entityLabel ? ('_' . $entityLabel) : '')
1604 );
1605 return $fieldKey;
1606 }
1607
1608 /**
1609 * Get params for the where criteria.
1610 *
1611 * @return mixed
1612 */
1613 public function getWhereParams() {
1614 if (!$this->isPostalableOnly()) {
1615 return [];
1616 }
1617 $params['is_deceased'] = ['is_deceased', '=', 0, CRM_Contact_BAO_Query::MODE_CONTACTS];
1618 $params['do_not_mail'] = ['do_not_mail', '=', 0, CRM_Contact_BAO_Query::MODE_CONTACTS];
1619 return $params;
1620 }
1621
1622 /**
1623 * @param $row
1624 * @param $contactID
1625 * @param $value
1626 * @param $field
1627 */
1628 protected function buildRelationshipFieldsForRow(&$row, $contactID, $value, $field) {
1629 foreach (array_keys($value) as $property) {
1630 if ($property === 'location') {
1631 // @todo just undo all this nasty location wrangling!
1632 foreach ($value['location'] as $locationKey => $locationFields) {
1633 foreach (array_keys($locationFields) as $locationField) {
1634 $fieldKey = str_replace(' ', '_', $locationKey . '-' . $locationField);
1635 $row[$field . '_' . $fieldKey] = $this->getRelationshipValue($field, $contactID, $fieldKey);
1636 }
1637 }
1638 }
1639 else {
1640 $row[$field . '_' . $property] = $this->getRelationshipValue($field, $contactID, $property);
1641 }
1642 }
1643 }
1644
1645 /**
1646 * Is this contact a household that is already set to be exported by virtue of it's household members.
1647 *
1648 * @param int $contactID
1649 *
1650 * @return bool
1651 */
1652 protected function isHouseholdToSkip($contactID) {
1653 return in_array($contactID, $this->householdsToSkip);
1654 }
1655
1656 /**
1657 * Get the various arrays that we use to structure our output.
1658 *
1659 * The extraction of these has been moved to a separate function for clarity and so that
1660 * tests can be added - in particular on the $outputHeaders array.
1661 *
1662 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1663 * as a step on the refactoring path rather than how it should be.
1664 *
1665 * @return array
1666 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1667 * alias for the field generated by BAO_Query object.
1668 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1669 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1670 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1671 * I'm too embarassed to discuss here.
1672 * The keys need
1673 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1674 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1675 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1676 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1677 * - a) the function used is more efficient or
1678 * - b) this code is old & outdated. Submit your answers to circular bin or better
1679 * yet find a way to comment them for posterity.
1680 */
1681 public function getExportStructureArrays() {
1682 $outputColumns = [];
1683 $queryFields = $this->getQueryFields();
1684 foreach ($this->getReturnProperties() as $key => $value) {
1685 if (($key != 'location' || !is_array($value)) && !$this->isRelationshipTypeKey($key)) {
1686 $outputColumns[$key] = $value;
1687 $this->addOutputSpecification($key);
1688 }
1689 elseif ($this->isRelationshipTypeKey($key)) {
1690 $outputColumns[$key] = $value;
1691 foreach ($value as $relationField => $relationValue) {
1692 // below block is same as primary block (duplicate)
1693 if (isset($queryFields[$relationField]['title'])) {
1694 $this->addOutputSpecification($relationField, $key);
1695 }
1696 elseif (is_array($relationValue) && $relationField == 'location') {
1697 // fix header for location type case
1698 foreach ($relationValue as $ltype => $val) {
1699 foreach (array_keys($val) as $fld) {
1700 $type = explode('-', $fld);
1701 $this->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array::value(1, $type));
1702 }
1703 }
1704 }
1705 }
1706 }
1707 else {
1708 foreach ($value as $locationType => $locationFields) {
1709 foreach (array_keys($locationFields) as $locationFieldName) {
1710 $type = explode('-', $locationFieldName);
1711
1712 $actualDBFieldName = $type[0];
1713 $daoFieldName = CRM_Utils_String::munge($locationType) . '-' . $actualDBFieldName;
1714
1715 if (!empty($type[1])) {
1716 $daoFieldName .= "-" . $type[1];
1717 }
1718 $this->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array::value(1, $type));
1719 $outputColumns[$daoFieldName] = TRUE;
1720 }
1721 }
1722 }
1723 }
1724 return [$outputColumns];
1725 }
1726
1727 /**
1728 * Get default return property for export based on mode
1729 *
1730 * @return string
1731 * Default Return property
1732 */
1733 public function defaultReturnProperty() {
1734 // hack to add default return property based on export mode
1735 $property = NULL;
1736 $exportMode = $this->getExportMode();
1737 if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
1738 $property = 'contribution_id';
1739 }
1740 elseif ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
1741 $property = 'participant_id';
1742 }
1743 elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
1744 $property = 'membership_id';
1745 }
1746 elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
1747 $property = 'pledge_id';
1748 }
1749 elseif ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
1750 $property = 'case_id';
1751 }
1752 elseif ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT) {
1753 $property = 'grant_id';
1754 }
1755 elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
1756 $property = 'activity_id';
1757 }
1758 return $property;
1759 }
1760
1761 /**
1762 * Determine the required return properties from the input parameters.
1763 *
1764 * @return array
1765 */
1766 public function determineReturnProperties() {
1767 if ($this->getRequestedFields()) {
1768 $returnProperties = [];
1769 foreach ($this->getRequestedFields() as $key => $value) {
1770 $fieldName = $value['name'];
1771 $locationName = !empty($value['location_type_id']) ? CRM_Core_PseudoConstant::getName('CRM_Core_BAO_Address', 'location_type_id', $value['location_type_id']) : NULL;
1772 $relationshipTypeKey = !empty($value['relationship_type_id']) ? $value['relationship_type_id'] . '_' . $value['relationship_direction'] : NULL;
1773 if (!$fieldName || $this->isHouseholdMergeRelationshipTypeKey($relationshipTypeKey)) {
1774 continue;
1775 }
1776
1777 if ($this->isRelationshipTypeKey($relationshipTypeKey)) {
1778 $returnProperties[$relationshipTypeKey] = $this->setRelationshipReturnProperties($value, $relationshipTypeKey);
1779 }
1780 elseif ($locationName) {
1781 if ($fieldName === 'phone') {
1782 $returnProperties['location'][$locationName]['phone-' . $value['phone_type_id'] ?? NULL] = 1;
1783 }
1784 elseif ($fieldName === 'im') {
1785 $returnProperties['location'][$locationName]['im-' . $value['im_provider_id'] ?? NULL] = 1;
1786 }
1787 else {
1788 $returnProperties['location'][$locationName][$fieldName] = 1;
1789 }
1790 }
1791 else {
1792 //hack to fix component fields
1793 //revert mix of event_id and title
1794 if ($fieldName == 'event_id') {
1795 $returnProperties['event_id'] = 1;
1796 }
1797 else {
1798 $returnProperties[$fieldName] = 1;
1799 }
1800 }
1801 }
1802 $defaultExportMode = $this->defaultReturnProperty();
1803 if ($defaultExportMode) {
1804 $returnProperties[$defaultExportMode] = 1;
1805 }
1806 }
1807 else {
1808 $returnProperties = $this->getDefaultReturnProperties();
1809 }
1810 if ($this->isMergeSameHousehold()) {
1811 $returnProperties['id'] = 1;
1812 }
1813 if ($this->isMergeSameAddress()) {
1814 $returnProperties['addressee'] = 1;
1815 $returnProperties['postal_greeting'] = 1;
1816 $returnProperties['email_greeting'] = 1;
1817 $returnProperties['street_name'] = 1;
1818 $returnProperties['household_name'] = 1;
1819 $returnProperties['street_address'] = 1;
1820 $returnProperties['city'] = 1;
1821 $returnProperties['state_province'] = 1;
1822
1823 }
1824 return $returnProperties;
1825 }
1826
1827 /**
1828 * @param object $query
1829 * CRM_Contact_BAO_Query
1830 *
1831 * @return string
1832 * Group By Clause
1833 */
1834 public function getGroupBy($query) {
1835 $groupBy = NULL;
1836 $returnProperties = $this->getReturnProperties();
1837 $exportMode = $this->getExportMode();
1838 $queryMode = $this->getQueryMode();
1839 if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) ||
1840 CRM_Utils_Array::value('notes', $returnProperties) ||
1841 // CRM-9552
1842 ($queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy)
1843 ) {
1844 $groupBy = "contact_a.id";
1845 }
1846
1847 switch ($exportMode) {
1848 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
1849 $groupBy = 'civicrm_contribution.id';
1850 if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
1851 // especial group by when soft credit columns are included
1852 $groupBy = ['contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id'];
1853 }
1854 break;
1855
1856 case CRM_Export_Form_Select::EVENT_EXPORT:
1857 $groupBy = 'civicrm_participant.id';
1858 break;
1859
1860 case CRM_Export_Form_Select::MEMBER_EXPORT:
1861 $groupBy = "civicrm_membership.id";
1862 break;
1863 }
1864
1865 if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
1866 $groupBy = "civicrm_activity.id ";
1867 }
1868
1869 return $groupBy ? ' GROUP BY ' . implode(', ', (array) $groupBy) : '';
1870 }
1871
1872 /**
1873 * Replace contact greetings in merged contacts.
1874 *
1875 * @param int $contactID
1876 *
1877 * @return array
1878 * @throws \API_Exception
1879 * @throws \CRM_Core_Exception
1880 */
1881 public function replaceMergeTokens(int $contactID): array {
1882 $messageTemplate = [
1883 'postal_greeting' => $this->getPostalGreetingTemplate() ?? '',
1884 'addressee' => $this->getAddresseeGreetingTemplate() ?? '',
1885 ];
1886 if (array_filter($messageTemplate)) {
1887 return CRM_Core_TokenSmarty::render($messageTemplate, ['contactId' => $contactID]);
1888 }
1889 return $messageTemplate;
1890 }
1891
1892 /**
1893 * Build array for merging same addresses.
1894 *
1895 * @param string $sql
1896 */
1897 public function buildMasterCopyArray($sql) {
1898
1899 $parents = [];
1900 $dao = CRM_Core_DAO::executeQuery($sql);
1901
1902 while ($dao->fetch()) {
1903 $masterID = $dao->master_id;
1904 $copyID = $dao->copy_id;
1905
1906 $this->cacheContactGreetings((int) $dao->master_contact_id);
1907 $this->cacheContactGreetings((int) $dao->copy_contact_id);
1908
1909 if (!isset($this->contactsToMerge[$masterID])) {
1910 // check if this is an intermediate child
1911 // this happens if there are 3 or more matches a,b, c
1912 // the above query will return a, b / a, c / b, c
1913 // we might be doing a bit more work, but for now its ok, unless someone
1914 // knows how to fix the query above
1915 if (isset($parents[$masterID])) {
1916 $masterID = $parents[$masterID];
1917 }
1918 else {
1919 $this->contactsToMerge[$masterID] = [
1920 'addressee' => $this->getContactGreeting((int) $dao->master_contact_id, 'addressee', $dao->master_addressee),
1921 'copy' => [],
1922 'postalGreeting' => $this->getContactGreeting((int) $dao->master_contact_id, 'postal_greeting', $dao->master_postal_greeting),
1923 ];
1924 $this->contactsToMerge[$masterID]['emailGreeting'] = &$this->contactsToMerge[$masterID]['postalGreeting'];
1925 }
1926 }
1927 $parents[$copyID] = $masterID;
1928
1929 if (!array_key_exists($copyID, $this->contactsToMerge[$masterID]['copy'])) {
1930 $copyPostalGreeting = $this->getContactPortionOfGreeting((int) $dao->copy_contact_id, (int) $dao->copy_postal_greeting_id, 'postal_greeting', $dao->copy_postal_greeting);
1931 if ($copyPostalGreeting) {
1932 $this->contactsToMerge[$masterID]['postalGreeting'] = "{$this->contactsToMerge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1933 // if there happens to be a duplicate, remove it
1934 $this->contactsToMerge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $this->contactsToMerge[$masterID]['postalGreeting']);
1935 }
1936
1937 $copyAddressee = $this->getContactPortionOfGreeting((int) $dao->copy_contact_id, (int) $dao->copy_addressee_id, 'addressee', $dao->copy_addressee);
1938 if ($copyAddressee) {
1939 $this->contactsToMerge[$masterID]['addressee'] = "{$this->contactsToMerge[$masterID]['addressee']}, " . trim($copyAddressee);
1940 }
1941 }
1942 if (!isset($this->contactsToMerge[$masterID]['copy'][$copyID])) {
1943 // If it was set in the first run through - share routine, don't subsequently clobber.
1944 $this->contactsToMerge[$masterID]['copy'][$copyID] = $copyAddressee ?? $dao->copy_addressee;
1945 }
1946 }
1947 }
1948
1949 /**
1950 * Merge contacts with the same address.
1951 */
1952 public function mergeSameAddress() {
1953
1954 $tableName = $this->getTemporaryTable();
1955
1956 // find all the records that have the same street address BUT not in a household
1957 // require match on city and state as well
1958 $sql = "
1959 SELECT r1.id as master_id,
1960 r1.civicrm_primary_id as master_contact_id,
1961 r1.postal_greeting as master_postal_greeting,
1962 r1.postal_greeting_id as master_postal_greeting_id,
1963 r1.addressee as master_addressee,
1964 r1.addressee_id as master_addressee_id,
1965 r2.id as copy_id,
1966 r2.civicrm_primary_id as copy_contact_id,
1967 r2.postal_greeting as copy_postal_greeting,
1968 r2.postal_greeting_id as copy_postal_greeting_id,
1969 r2.addressee as copy_addressee,
1970 r2.addressee_id as copy_addressee_id
1971 FROM $tableName r1
1972 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1973 r1.city = r2.city AND
1974 r1.state_province_id = r2.state_province_id )
1975 WHERE ( r1.street_address != '' )
1976 AND r2.id > r1.id
1977 ORDER BY r1.id
1978 ";
1979 $this->buildMasterCopyArray($sql);
1980
1981 foreach ($this->contactsToMerge as $masterID => $values) {
1982 $sql = "
1983 UPDATE $tableName
1984 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1985 WHERE id = %4
1986 ";
1987 $params = [
1988 1 => [CRM_Utils_String::ellipsify($values['addressee'], 255), 'String'],
1989 2 => [$values['postalGreeting'], 'String'],
1990 3 => [$values['emailGreeting'], 'String'],
1991 4 => [$masterID, 'Integer'],
1992 ];
1993 CRM_Core_DAO::executeQuery($sql, $params);
1994
1995 // delete all copies
1996 $deleteIDs = array_keys($values['copy']);
1997 $deleteIDString = implode(',', $deleteIDs);
1998 $sql = "
1999 DELETE FROM $tableName
2000 WHERE id IN ( $deleteIDString )
2001 ";
2002 CRM_Core_DAO::executeQuery($sql);
2003 }
2004 }
2005
2006 /**
2007 * The function unsets static part of the string, if token is the dynamic part.
2008 *
2009 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
2010 * i.e 'Hello Alan' => converted to => 'Alan'
2011 *
2012 * @param string $parsedString
2013 * @param string $defaultGreeting
2014 * @param string $greetingLabel
2015 *
2016 * @return mixed
2017 */
2018 public function trimNonTokensFromAddressString(
2019 &$parsedString, $defaultGreeting,
2020 $greetingLabel
2021 ) {
2022 $greetingLabel = empty($greetingLabel) ? $defaultGreeting : $greetingLabel;
2023
2024 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
2025 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
2026 foreach ($stringsToBeReplaced as $key => $string) {
2027 // to keep one space
2028 $stringsToBeReplaced[$key] = ltrim($string);
2029 }
2030 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
2031
2032 return $parsedString;
2033 }
2034
2035 /**
2036 * Preview export output.
2037 *
2038 * @param int $limit
2039 * @return array
2040 */
2041 public function getPreview($limit) {
2042 $rows = [];
2043 [$outputColumns] = $this->getExportStructureArrays();
2044 $query = $this->runQuery([], '');
2045 CRM_Core_DAO::disableFullGroupByMode();
2046 $result = CRM_Core_DAO::executeQuery($query[1] . ' LIMIT ' . (int) $limit);
2047 CRM_Core_DAO::reenableFullGroupByMode();
2048 while ($result->fetch()) {
2049 $rows[] = $this->buildRow($query[0], $result, $outputColumns, [], []);
2050 }
2051 return $rows;
2052 }
2053
2054 /**
2055 * Set the template strings to be used when merging two contacts with the same address.
2056 *
2057 * @param array $formValues
2058 * Values from first form. In this case we care about the keys
2059 * - postal_greeting
2060 * - postal_other
2061 * - address_greeting
2062 * - addressee_other
2063 *
2064 * @return mixed
2065 */
2066 protected function setGreetingStringsForSameAddressMerge($formValues) {
2067 $greetingOptions = CRM_Export_Form_Select::getGreetingOptions();
2068
2069 if (!empty($greetingOptions)) {
2070 // Greeting options is keyed by 'postal_greeting' or 'addressee'.
2071 foreach ($greetingOptions as $key => $value) {
2072 $option = $formValues[$key] ?? NULL;
2073 if ($option) {
2074 if ($greetingOptions[$key][$option] == ts('Other')) {
2075 $formValues[$key] = $formValues["{$key}_other"];
2076 }
2077 elseif ($greetingOptions[$key][$option] == ts('List of names')) {
2078 $formValues[$key] = '';
2079 }
2080 else {
2081 $formValues[$key] = $greetingOptions[$key][$option];
2082 }
2083 }
2084 }
2085 }
2086 if (!empty($formValues['postal_greeting'])) {
2087 $this->setPostalGreetingTemplate($formValues['postal_greeting']);
2088 }
2089 if (!empty($formValues['addressee'])) {
2090 $this->setAddresseeGreetingTemplate($formValues['addressee']);
2091 }
2092 }
2093
2094 /**
2095 * Create the temporary table for output.
2096 */
2097 public function createTempTable() {
2098 //creating a temporary table for the search result that need be exported
2099 $exportTempTable = CRM_Utils_SQL_TempTable::build()->setDurable()->setCategory('export');
2100 $sqlColumns = $this->getSQLColumns();
2101 // also create the sql table
2102 $exportTempTable->drop();
2103
2104 $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
2105 if (!empty($sqlColumns)) {
2106 $sql .= implode(",\n", array_values($sqlColumns)) . ',';
2107 }
2108
2109 $sql .= "\n PRIMARY KEY ( id )";
2110
2111 // add indexes for street_address and household_name if present
2112 $addIndices = [
2113 'street_address',
2114 'household_name',
2115 'civicrm_primary_id',
2116 ];
2117
2118 foreach ($addIndices as $index) {
2119 if (isset($sqlColumns[$index])) {
2120 $sql .= ",
2121 INDEX index_{$index}( $index )
2122 ";
2123 }
2124 }
2125
2126 $exportTempTable->createWithColumns($sql);
2127 $this->setTemporaryTable($exportTempTable->getName());
2128 }
2129
2130 /**
2131 * Get the values of linked household contact.
2132 *
2133 * @param CRM_Core_DAO $relDAO
2134 * @param array $value
2135 * @param string $field
2136 * @param array $row
2137 *
2138 * @throws \Exception
2139 */
2140 public function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
2141 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
2142 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
2143 $i18n = CRM_Core_I18n::singleton();
2144 $field = $field . '_';
2145
2146 foreach ($value as $relationField => $relationValue) {
2147 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
2148 $fieldValue = $relDAO->$relationField;
2149 if ($relationField == 'provider_id') {
2150 $fieldValue = $imProviders[$relationValue] ?? NULL;
2151 }
2152 // CRM-13995
2153 elseif (is_object($relDAO) && in_array($relationField, [
2154 'email_greeting',
2155 'postal_greeting',
2156 'addressee',
2157 ])) {
2158 //special case for greeting replacement
2159 $fldValue = "{$relationField}_display";
2160 $fieldValue = $relDAO->$fldValue;
2161 }
2162 }
2163 elseif (is_object($relDAO) && $relationField == 'state_province') {
2164 $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
2165 }
2166 elseif (is_object($relDAO) && $relationField == 'country') {
2167 $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
2168 }
2169 else {
2170 $fieldValue = '';
2171 }
2172 $relPrefix = $field . $relationField;
2173
2174 if (is_object($relDAO) && $relationField == 'id') {
2175 $row[$relPrefix] = $relDAO->contact_id;
2176 }
2177 elseif (is_array($relationValue) && $relationField == 'location') {
2178 foreach ($relationValue as $ltype => $val) {
2179 // If the location name has a space in it the we need to handle that. This
2180 // is kinda hacky but specifically covered in the ExportTest so later efforts to
2181 // improve it should be secure in the knowled it will be caught.
2182 $ltype = str_replace(' ', '_', $ltype);
2183 foreach (array_keys($val) as $fld) {
2184 $type = explode('-', $fld);
2185 $fldValue = "{$ltype}-" . $type[0];
2186 if (!empty($type[1])) {
2187 $fldValue .= "-" . $type[1];
2188 }
2189 // CRM-3157: localise country, region (both have ‘country’ context)
2190 // and state_province (‘province’ context)
2191 switch (TRUE) {
2192 case (!is_object($relDAO)):
2193 $row[$field . '_' . $fldValue] = '';
2194 break;
2195
2196 case in_array('country', $type):
2197 case in_array('world_region', $type):
2198 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2199 ['context' => 'country']
2200 );
2201 break;
2202
2203 case in_array('state_province', $type):
2204 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2205 ['context' => 'province']
2206 );
2207 break;
2208
2209 default:
2210 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
2211 break;
2212 }
2213 }
2214 }
2215 }
2216 elseif (isset($fieldValue) && $fieldValue != '') {
2217 //check for custom data
2218 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
2219 $row[$relPrefix] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
2220 }
2221 else {
2222 //normal relationship fields
2223 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
2224 switch ($relationField) {
2225 case 'country':
2226 case 'world_region':
2227 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
2228 break;
2229
2230 case 'state_province':
2231 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
2232 break;
2233
2234 default:
2235 $row[$relPrefix] = $fieldValue;
2236 break;
2237 }
2238 }
2239 }
2240 else {
2241 // if relation field is empty or null
2242 $row[$relPrefix] = '';
2243 }
2244 }
2245 }
2246
2247 /**
2248 * Write to the csv from the temp table.
2249 */
2250 public function writeCSVFromTable() {
2251 // call export hook
2252 $headerRows = $this->getHeaderRows();
2253 $exportTempTable = $this->getTemporaryTable();
2254 $exportMode = $this->getExportMode();
2255 $sqlColumns = $this->getSQLColumns();
2256 $componentTable = $this->getComponentTable();
2257 $ids = $this->getIds();
2258 CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
2259 if ($exportMode !== $this->getExportMode() || $componentTable !== $this->getComponentTable()) {
2260 CRM_Core_Error::deprecatedFunctionWarning('altering the export mode and/or component table in the hook is no longer supported.');
2261 }
2262 if ($ids !== $this->getIds()) {
2263 CRM_Core_Error::deprecatedFunctionWarning('altering the ids in the hook is no longer supported.');
2264 }
2265 if ($exportTempTable !== $this->getTemporaryTable()) {
2266 CRM_Core_Error::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
2267 $this->setTemporaryTable($exportTempTable);
2268 }
2269 $exportTempTable = $this->getTemporaryTable();
2270 $writeHeader = TRUE;
2271 $offset = 0;
2272 // increase this number a lot to avoid making too many queries
2273 // LIMIT is not much faster than a no LIMIT query
2274 // CRM-7675
2275 $limit = 100000;
2276
2277 $query = "SELECT * FROM $exportTempTable";
2278
2279 $this->instantiateTempTable($headerRows);
2280 while (1) {
2281 $limitQuery = $query . "
2282 LIMIT $offset, $limit
2283 ";
2284 $dao = CRM_Core_DAO::executeQuery($limitQuery);
2285
2286 if ($dao->N <= 0) {
2287 break;
2288 }
2289
2290 $componentDetails = [];
2291 while ($dao->fetch()) {
2292 $row = [];
2293
2294 foreach (array_keys($sqlColumns) as $column) {
2295 $row[$column] = $dao->$column;
2296 }
2297 $componentDetails[] = $row;
2298 }
2299 $this->writeRows($headerRows, $componentDetails);
2300
2301 $offset += $limit;
2302 }
2303 }
2304
2305 /**
2306 * Set up the temp table.
2307 *
2308 * @param array $headerRows
2309 */
2310 protected function instantiateTempTable(array $headerRows) {
2311 CRM_Utils_System::download(CRM_Utils_String::munge($this->getExportFileName()),
2312 'text/x-csv',
2313 CRM_Core_DAO::$_nullObject,
2314 'csv',
2315 FALSE
2316 );
2317 // Output UTF BOM so that MS Excel copes with diacritics. This is recommended as
2318 // the Windows variant but is tested with MS Excel for Mac (Office 365 v 16.31)
2319 // and it continues to work on Libre Office, Numbers, Notes etc.
2320 echo "\xEF\xBB\xBF";
2321 CRM_Core_Report_Excel::makeCSVTable($headerRows, [], TRUE);
2322 }
2323
2324 /**
2325 * Write rows to the csv.
2326 *
2327 * @param array $headerRows
2328 * @param array $rows
2329 */
2330 protected function writeRows(array $headerRows, array $rows) {
2331 if (!empty($rows)) {
2332 CRM_Core_Report_Excel::makeCSVTable($headerRows, $rows, FALSE);
2333 }
2334 }
2335
2336 /**
2337 * Cache the greeting fields for the given contact.
2338 *
2339 * @param int $contactID
2340 */
2341 protected function cacheContactGreetings(int $contactID) {
2342 if (!isset($this->contactGreetingFields[$contactID])) {
2343 $this->contactGreetingFields[$contactID] = $this->replaceMergeTokens($contactID);
2344 }
2345 }
2346
2347 /**
2348 * Get the greeting value for the given contact.
2349 *
2350 * The values have already been cached so we are grabbing the value at this point.
2351 *
2352 * @param int $contactID
2353 * @param string $type
2354 * postal_greeting|addressee|email_greeting
2355 * @param string $default
2356 *
2357 * @return string
2358 */
2359 protected function getContactGreeting(int $contactID, string $type, string $default): string {
2360 return empty($this->contactGreetingFields[$contactID][$type]) ? $default : $this->contactGreetingFields[$contactID][$type];
2361 }
2362
2363 /**
2364 * Get the portion of the greeting string that relates to the contact.
2365 *
2366 * For example if the greeting id 'Dear Sarah' we are going to combine it with 'Dear Mike'
2367 * so we want to strip the 'Dear ' and just get 'Sarah
2368 * @param int $contactID
2369 * @param int $greetingID
2370 * @param string $type
2371 * postal_greeting, addressee (email_greeting not currently implemented for unknown reasons.
2372 * @param string $defaultGreeting
2373 *
2374 * @return mixed|string
2375 */
2376 protected function getContactPortionOfGreeting(int $contactID, int $greetingID, string $type, string $defaultGreeting) {
2377 $copyPostalGreeting = $this->getContactGreeting($contactID, $type, $defaultGreeting);
2378 $template = $type === 'postal_greeting' ? $this->getPostalGreetingTemplate() : $this->getAddresseeGreetingTemplate();
2379 if ($copyPostalGreeting) {
2380 $copyPostalGreeting = $this->trimNonTokensFromAddressString($copyPostalGreeting,
2381 $this->greetingOptions[$type][$greetingID],
2382 $template
2383 );
2384 }
2385 return $copyPostalGreeting;
2386 }
2387
2388 }