Merge pull request #17981 from eileenmcnaughton/merge_form
[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 $this->queryFields = $queryFields;
643 }
644
645 /**
646 * @return int
647 */
648 public function getQueryMode() {
649 return $this->queryMode;
650 }
651
652 /**
653 * Set the query mode based on the export mode.
654 */
655 public function setQueryMode() {
656
657 switch ($this->getExportMode()) {
658 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
659 $this->queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
660 break;
661
662 case CRM_Export_Form_Select::EVENT_EXPORT:
663 $this->queryMode = CRM_Contact_BAO_Query::MODE_EVENT;
664 break;
665
666 case CRM_Export_Form_Select::MEMBER_EXPORT:
667 $this->queryMode = CRM_Contact_BAO_Query::MODE_MEMBER;
668 break;
669
670 case CRM_Export_Form_Select::PLEDGE_EXPORT:
671 $this->queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE;
672 break;
673
674 case CRM_Export_Form_Select::CASE_EXPORT:
675 $this->queryMode = CRM_Contact_BAO_Query::MODE_CASE;
676 break;
677
678 case CRM_Export_Form_Select::GRANT_EXPORT:
679 $this->queryMode = CRM_Contact_BAO_Query::MODE_GRANT;
680 break;
681
682 case CRM_Export_Form_Select::ACTIVITY_EXPORT:
683 $this->queryMode = CRM_Contact_BAO_Query::MODE_ACTIVITY;
684 break;
685
686 default:
687 $this->queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
688 }
689 }
690
691 /**
692 * @return int
693 */
694 public function getExportMode() {
695 return $this->exportMode;
696 }
697
698 /**
699 * @param int $exportMode
700 */
701 public function setExportMode($exportMode) {
702 $this->exportMode = $exportMode;
703 }
704
705 /**
706 * Get the name for the export file.
707 *
708 * @return string
709 */
710 public function getExportFileName() {
711 switch ($this->getExportMode()) {
712 case CRM_Export_Form_Select::CONTACT_EXPORT:
713 return ts('CiviCRM Contact Search');
714
715 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
716 return ts('CiviCRM Contribution Search');
717
718 case CRM_Export_Form_Select::MEMBER_EXPORT:
719 return ts('CiviCRM Member Search');
720
721 case CRM_Export_Form_Select::EVENT_EXPORT:
722 return ts('CiviCRM Participant Search');
723
724 case CRM_Export_Form_Select::PLEDGE_EXPORT:
725 return ts('CiviCRM Pledge Search');
726
727 case CRM_Export_Form_Select::CASE_EXPORT:
728 return ts('CiviCRM Case Search');
729
730 case CRM_Export_Form_Select::GRANT_EXPORT:
731 return ts('CiviCRM Grant Search');
732
733 case CRM_Export_Form_Select::ACTIVITY_EXPORT:
734 return ts('CiviCRM Activity Search');
735
736 default:
737 // Legacy code suggests the value could be 'financial' - ie. something
738 // other than what should be accepted. However, I suspect that this line is
739 // never hit.
740 return ts('CiviCRM Search');
741 }
742 }
743
744 /**
745 * Get the label for the header row based on the field to output.
746 *
747 * @param string $field
748 *
749 * @return string
750 */
751 public function getHeaderForRow($field) {
752 if (substr($field, -11) === 'campaign_id') {
753 // @todo - set this correctly in the xml rather than here.
754 // This will require a generalised handling cleanup
755 return ts('Campaign ID');
756 }
757 if ($this->isMergeSameHousehold() && !$this->isMergeSameAddress() && $field === 'id') {
758 // This is weird - even if we are merging households not every contact in the export is a household so this would not be accurate.
759 return ts('Household ID');
760 }
761 elseif (isset($this->getQueryFields()[$field]['title'])) {
762 return $this->getQueryFields()[$field]['title'];
763 }
764 elseif ($this->isExportPaymentFields() && array_key_exists($field, $this->getcomponentPaymentFields())) {
765 return CRM_Utils_Array::value($field, $this->getcomponentPaymentFields())['title'];
766 }
767 else {
768 return $field;
769 }
770 }
771
772 /**
773 * @param $params
774 * @param $order
775 *
776 * @return array
777 */
778 public function runQuery($params, $order) {
779 $returnProperties = $this->getReturnProperties();
780 $params = array_merge($params, $this->getWhereParams());
781
782 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
783 FALSE, FALSE, $this->getQueryMode(),
784 FALSE, TRUE, TRUE, NULL, $this->getQueryOperator(),
785 NULL, TRUE
786 );
787
788 //sort by state
789 //CRM-15301
790 $query->_sort = $order;
791 list($select, $from, $where, $having) = $query->query();
792 $this->setQueryFields($query->_fields);
793 $whereClauses = ['trash_clause' => "contact_a.is_deleted != 1"];
794 if ($this->getRequestedFields() && ($this->getComponentTable())) {
795 $from .= " INNER JOIN " . $this->getComponentTable() . " ctTable ON ctTable.contact_id = contact_a.id ";
796 }
797 elseif ($this->getComponentClause()) {
798 $whereClauses[] = $this->getComponentClause();
799 }
800
801 // CRM-13982 - check if is deleted
802 foreach ($params as $value) {
803 if ($value[0] == 'contact_is_deleted') {
804 unset($whereClauses['trash_clause']);
805 }
806 }
807
808 if ($this->isPostalableOnly) {
809 if (array_key_exists('street_address', $returnProperties)) {
810 $addressWhere = " civicrm_address.street_address <> ''";
811 if (array_key_exists('supplemental_address_1', $returnProperties)) {
812 // We need this to be an OR rather than AND on the street_address so, hack it in.
813 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
814 'address_options', TRUE, NULL, TRUE
815 );
816 if (!empty($addressOptions['supplemental_address_1'])) {
817 $addressWhere .= " OR civicrm_address.supplemental_address_1 <> ''";
818 }
819 }
820 $whereClauses['address'] = '(' . $addressWhere . ')';
821 }
822 }
823
824 if (empty($where)) {
825 $where = "WHERE " . implode(' AND ', $whereClauses);
826 }
827 else {
828 $where .= " AND " . implode(' AND ', $whereClauses);
829 }
830
831 $groupBy = $this->getGroupBy($query);
832 $queryString = "$select $from $where $having $groupBy";
833 if ($order) {
834 // always add contact_a.id to the ORDER clause
835 // so the order is deterministic
836 //CRM-15301
837 if (strpos('contact_a.id', $order) === FALSE) {
838 $order .= ", contact_a.id";
839 }
840
841 list($field, $dir) = explode(' ', $order, 2);
842 $field = trim($field);
843 if (!empty($this->getReturnProperties()[$field])) {
844 //CRM-15301
845 $queryString .= " ORDER BY $order";
846 }
847 }
848 return [$query, $queryString];
849 }
850
851 /**
852 * Add a row to the specification for how to output data.
853 *
854 * @param string $key
855 * @param string $relationshipType
856 * @param string $locationType
857 * @param int $entityTypeID phone_type_id or provider_id for phone or im fields.
858 */
859 public function addOutputSpecification($key, $relationshipType = NULL, $locationType = NULL, $entityTypeID = NULL) {
860 $entityLabel = '';
861 if ($entityTypeID) {
862 if ($key === 'phone') {
863 $entityLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', $entityTypeID);
864 }
865 if ($key === 'im') {
866 $entityLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_IM', 'provider_id', $entityTypeID);
867 }
868 }
869
870 // These oddly constructed keys are for legacy reasons. Altering them will affect test success
871 // but in time it may be good to rationalise them.
872 $label = $this->getOutputSpecificationLabel($key, $relationshipType, $locationType, $entityLabel);
873 $index = $this->getOutputSpecificationIndex($key, $relationshipType, $locationType, $entityTypeID);
874 $fieldKey = $this->getOutputSpecificationFieldKey($key, $relationshipType, $locationType, $entityTypeID);
875
876 $this->outputSpecification[$index]['header'] = $label;
877 $this->outputSpecification[$index]['sql_columns'] = $this->getSqlColumnDefinition($fieldKey, $key);
878
879 if ($relationshipType && $this->isHouseholdMergeRelationshipTypeKey($relationshipType)) {
880 $this->setColumnAsCalculationOnly($index);
881 }
882 $this->outputSpecification[$index]['metadata'] = $this->getMetaDataForField($key);
883 }
884
885 /**
886 * Get the metadata for the given field.
887 *
888 * @param $key
889 *
890 * @return array
891 */
892 public function getMetaDataForField($key) {
893 $mappings = ['contact_id' => 'id'];
894 if (isset($this->getQueryFields()[$key])) {
895 return $this->getQueryFields()[$key];
896 }
897 if (isset($mappings[$key])) {
898 return $this->getQueryFields()[$mappings[$key]];
899 }
900 return [];
901 }
902
903 /**
904 * @param $key
905 */
906 public function setSqlColumnDefn($key) {
907 $this->outputSpecification[$this->getMungedFieldName($key)]['sql_columns'] = $this->getSqlColumnDefinition($key, $this->getMungedFieldName($key));
908 }
909
910 /**
911 * Mark a column as only required for calculations.
912 *
913 * Do not include the row with headers.
914 *
915 * @param string $column
916 */
917 public function setColumnAsCalculationOnly($column) {
918 $this->outputSpecification[$column]['do_not_output_to_csv'] = TRUE;
919 }
920
921 /**
922 * @return array
923 */
924 public function getHeaderRows() {
925 $headerRows = [];
926 foreach ($this->outputSpecification as $key => $spec) {
927 if (empty($spec['do_not_output_to_csv'])) {
928 $headerRows[] = $spec['header'];
929 }
930 }
931 return $headerRows;
932 }
933
934 /**
935 * @return array
936 */
937 public function getSQLColumns() {
938 $sqlColumns = [];
939 foreach ($this->outputSpecification as $key => $spec) {
940 if (empty($spec['do_not_output_to_sql'])) {
941 $sqlColumns[$key] = $spec['sql_columns'];
942 }
943 }
944 return $sqlColumns;
945 }
946
947 /**
948 * @return array
949 */
950 public function getMetadata() {
951 $metadata = [];
952 foreach ($this->outputSpecification as $key => $spec) {
953 $metadata[$key] = $spec['metadata'];
954 }
955 return $metadata;
956 }
957
958 /**
959 * Build the row for output.
960 *
961 * @param \CRM_Contact_BAO_Query $query
962 * @param CRM_Core_DAO $iterationDAO
963 * @param array $outputColumns
964 * @param $paymentDetails
965 * @param $addPaymentHeader
966 *
967 * @return array|bool
968 */
969 public function buildRow($query, $iterationDAO, $outputColumns, $paymentDetails, $addPaymentHeader) {
970 $paymentTableId = $this->getPaymentTableID();
971 if ($this->isHouseholdToSkip($iterationDAO->contact_id)) {
972 return FALSE;
973 }
974 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
975 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
976
977 $row = [];
978 $householdMergeRelationshipType = $this->getHouseholdMergeTypeForRow($iterationDAO->contact_id);
979 if ($householdMergeRelationshipType) {
980 $householdID = $this->getRelatedHouseholdID($iterationDAO->contact_id, $householdMergeRelationshipType);
981 if ($this->isHouseholdExported($householdID)) {
982 return FALSE;
983 }
984 foreach (array_keys($outputColumns) as $column) {
985 $row[$column] = $this->getRelationshipValue($householdMergeRelationshipType, $iterationDAO->contact_id, $column);
986 }
987 $this->markHouseholdExported($householdID);
988 return $row;
989 }
990
991 $query->convertToPseudoNames($iterationDAO);
992
993 //first loop through output columns so that we return what is required, and in same order.
994 foreach ($outputColumns as $field => $value) {
995 // add im_provider to $dao object
996 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
997 $iterationDAO->im_provider = $iterationDAO->provider_id;
998 }
999
1000 //build row values (data)
1001 $fieldValue = NULL;
1002 if (property_exists($iterationDAO, $field)) {
1003 $fieldValue = $iterationDAO->$field;
1004 // to get phone type from phone type id
1005 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
1006 $fieldValue = $phoneTypes[$fieldValue];
1007 }
1008 elseif ($field == 'provider_id' || $field == 'im_provider') {
1009 $fieldValue = $imProviders[$fieldValue] ?? NULL;
1010 }
1011 elseif (strstr($field, 'master_id')) {
1012 // @todo - why not just $field === 'master_id' - what else would it be?
1013 $masterAddressId = $iterationDAO->$field ?? NULL;
1014 // get display name of contact that address is shared.
1015 $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId);
1016 }
1017 }
1018
1019 if ($this->isRelationshipTypeKey($field)) {
1020 $this->buildRelationshipFieldsForRow($row, $iterationDAO->contact_id, $value, $field);
1021 }
1022 else {
1023 $row[$field] = $this->getTransformedFieldValue($field, $iterationDAO, $fieldValue, $paymentDetails);
1024 }
1025 }
1026
1027 // If specific payment fields have been selected for export, payment
1028 // data will already be in $row. Otherwise, add payment related
1029 // information, if appropriate.
1030 if ($addPaymentHeader) {
1031 if (!$this->isExportSpecifiedPaymentFields()) {
1032 $nullContributionDetails = array_fill_keys(array_keys($this->getPaymentHeaders()), NULL);
1033 if ($this->isExportPaymentFields()) {
1034 $paymentData = $paymentDetails[$row[$paymentTableId]] ?? NULL;
1035 if (!is_array($paymentData) || empty($paymentData)) {
1036 $paymentData = $nullContributionDetails;
1037 }
1038 $row = array_merge($row, $paymentData);
1039 }
1040 elseif (!empty($paymentDetails)) {
1041 $row = array_merge($row, $nullContributionDetails);
1042 }
1043 }
1044 }
1045 //remove organization name for individuals if it is set for current employer
1046 if (!empty($row['contact_type']) &&
1047 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1048 ) {
1049 $row['organization_name'] = '';
1050 }
1051 return $row;
1052 }
1053
1054 /**
1055 * If this row has a household whose details we should use get the relationship type key.
1056 *
1057 * @param $contactID
1058 *
1059 * @return bool
1060 */
1061 public function getHouseholdMergeTypeForRow($contactID) {
1062 if (!$this->isMergeSameHousehold()) {
1063 return FALSE;
1064 }
1065 foreach ($this->getHouseholdRelationshipTypes() as $relationshipType) {
1066 if (isset($this->relatedContactValues[$relationshipType][$contactID])) {
1067 return $relationshipType;
1068 }
1069 }
1070 }
1071
1072 /**
1073 * Mark the given household as already exported.
1074 *
1075 * @param $householdID
1076 */
1077 public function markHouseholdExported($householdID) {
1078 $this->exportedHouseholds[$householdID] = $householdID;
1079 }
1080
1081 /**
1082 * @param $field
1083 * @param $iterationDAO
1084 * @param $fieldValue
1085 * @param $paymentDetails
1086 *
1087 * @return string
1088 * @throws \CRM_Core_Exception
1089 * @throws \CiviCRM_API3_Exception
1090 */
1091 public function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $paymentDetails) {
1092
1093 $i18n = CRM_Core_I18n::singleton();
1094 if ($field == 'id') {
1095 return $iterationDAO->contact_id;
1096 // special case for calculated field
1097 }
1098 elseif ($field == 'source_contact_id') {
1099 return $iterationDAO->contact_id;
1100 }
1101 elseif ($field == 'pledge_balance_amount') {
1102 return $iterationDAO->pledge_amount - $iterationDAO->pledge_total_paid;
1103 // special case for calculated field
1104 }
1105 elseif ($field == 'pledge_next_pay_amount') {
1106 return $iterationDAO->pledge_next_pay_amount + $iterationDAO->pledge_outstanding_amount;
1107 }
1108 elseif (isset($fieldValue) &&
1109 $fieldValue != ''
1110 ) {
1111 //check for custom data
1112 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
1113 $html_type = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'html_type');
1114
1115 //need to calculate the link to the file for file custom data
1116 if ($html_type === 'File' && $fieldValue) {
1117 $result = civicrm_api3('attachment', 'get', ['return' => ['url'], 'id' => $fieldValue]);
1118 return $result['values'][$result['id']]['url'];
1119 }
1120
1121 return CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
1122 }
1123 elseif (in_array($field, [
1124 'email_greeting',
1125 'postal_greeting',
1126 'addressee',
1127 ])) {
1128 //special case for greeting replacement
1129 $fldValue = "{$field}_display";
1130 return $iterationDAO->$fldValue;
1131 }
1132 else {
1133 //normal fields with a touch of CRM-3157
1134 switch ($field) {
1135 case 'country':
1136 case 'world_region':
1137 return $i18n->crm_translate($fieldValue, ['context' => 'country']);
1138
1139 case 'state_province':
1140 return $i18n->crm_translate($fieldValue, ['context' => 'province']);
1141
1142 case 'gender':
1143 case 'preferred_communication_method':
1144 case 'preferred_mail_format':
1145 case 'communication_style':
1146 return $i18n->crm_translate($fieldValue);
1147
1148 default:
1149 $fieldSpec = $this->outputSpecification[$this->getMungedFieldName($field)]['metadata'];
1150 // No I don't know why we do it this way & whether we could
1151 // make better use of pseudoConstants.
1152 if (!empty($fieldSpec['context'])) {
1153 return $i18n->crm_translate($fieldValue, $fieldSpec);
1154 }
1155 if (!empty($fieldSpec['pseudoconstant']) && !empty($fieldSpec['hasLocationType'])) {
1156 if (!empty($fieldSpec['bao'])) {
1157 $transformedValue = CRM_Core_PseudoConstant::getLabel($fieldSpec['bao'], $fieldSpec['name'], $fieldValue);
1158 if ($transformedValue) {
1159 return $transformedValue;
1160 }
1161 return $fieldValue;
1162 }
1163 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
1164 // but I have to reach a stable point....
1165 $varName = $fieldSpec['pseudoconstant']['var'];
1166 if ($varName === 'imProviders') {
1167 return CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
1168 }
1169 }
1170 return $fieldValue;
1171 }
1172 }
1173 }
1174 elseif ($this->isExportSpecifiedPaymentFields() && array_key_exists($field, $this->getcomponentPaymentFields())) {
1175 $paymentTableId = $this->getPaymentTableID();
1176 $paymentData = $paymentDetails[$iterationDAO->$paymentTableId] ?? NULL;
1177 $payFieldMapper = [
1178 'componentPaymentField_total_amount' => 'total_amount',
1179 'componentPaymentField_contribution_status' => 'contribution_status',
1180 'componentPaymentField_payment_instrument' => 'pay_instru',
1181 'componentPaymentField_transaction_id' => 'trxn_id',
1182 'componentPaymentField_received_date' => 'receive_date',
1183 ];
1184 return CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, '');
1185 }
1186 else {
1187 // if field is empty or null
1188 return '';
1189 }
1190 }
1191
1192 /**
1193 * Get array of fields to return, over & above those defined in the main contact exportable fields.
1194 *
1195 * These include export mode specific fields & some fields apparently required as 'exportableFields'
1196 * but not returned by the function of the same name.
1197 *
1198 * @return array
1199 * Array of fields to return in the format ['field_name' => 1,...]
1200 */
1201 public function getAdditionalReturnProperties() {
1202 if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_CONTACTS) {
1203 $componentSpecificFields = [];
1204 }
1205 else {
1206 $componentSpecificFields = CRM_Contact_BAO_Query::defaultReturnProperties($this->getQueryMode());
1207 }
1208 if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_PLEDGE) {
1209 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Pledge_BAO_Query::extraReturnProperties($this->getQueryMode()));
1210 unset($componentSpecificFields['contribution_status_id']);
1211 unset($componentSpecificFields['pledge_status_id']);
1212 unset($componentSpecificFields['pledge_payment_status_id']);
1213 }
1214 if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_CASE) {
1215 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Case_BAO_Query::extraReturnProperties($this->getQueryMode()));
1216 }
1217 if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
1218 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Contribute_BAO_Query::softCreditReturnProperties(TRUE));
1219 unset($componentSpecificFields['contribution_status_id']);
1220 }
1221 return $componentSpecificFields;
1222 }
1223
1224 /**
1225 * Should payment fields be appended to the export.
1226 *
1227 * (This is pretty hacky so hopefully this function won't last long - notice
1228 * how obviously it should be part of the above function!).
1229 */
1230 public function isExportPaymentFields() {
1231 if ($this->getRequestedFields() === NULL
1232 && in_array($this->getQueryMode(), [
1233 CRM_Contact_BAO_Query::MODE_EVENT,
1234 CRM_Contact_BAO_Query::MODE_MEMBER,
1235 CRM_Contact_BAO_Query::MODE_PLEDGE,
1236 ])) {
1237 return TRUE;
1238 }
1239 elseif ($this->isExportSpecifiedPaymentFields()) {
1240 return TRUE;
1241 }
1242 return FALSE;
1243 }
1244
1245 /**
1246 * Has specific payment fields been requested (as opposed to via all fields).
1247 *
1248 * If specific fields have been requested then they get added at various points.
1249 *
1250 * @return bool
1251 */
1252 public function isExportSpecifiedPaymentFields() {
1253 if ($this->getRequestedFields() !== NULL && $this->hasRequestedComponentPaymentFields()) {
1254 return TRUE;
1255 }
1256 }
1257
1258 /**
1259 * Get the name of the id field in the table that connects contributions to the export entity.
1260 */
1261 public function getPaymentTableID() {
1262 if ($this->getRequestedFields() === NULL) {
1263 $mapping = [
1264 CRM_Contact_BAO_Query::MODE_EVENT => 'participant_id',
1265 CRM_Contact_BAO_Query::MODE_MEMBER => 'membership_id',
1266 CRM_Contact_BAO_Query::MODE_PLEDGE => 'pledge_payment_id',
1267 ];
1268 return isset($mapping[$this->getQueryMode()]) ? $mapping[$this->getQueryMode()] : '';
1269 }
1270 elseif ($this->hasRequestedComponentPaymentFields()) {
1271 return 'participant_id';
1272 }
1273 return FALSE;
1274 }
1275
1276 /**
1277 * Have component payment fields been requested.
1278 *
1279 * @return bool
1280 */
1281 protected function hasRequestedComponentPaymentFields() {
1282 if ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_EVENT) {
1283 $participantPaymentFields = array_intersect_key($this->getComponentPaymentFields(), $this->getReturnProperties());
1284 if (!empty($participantPaymentFields)) {
1285 return TRUE;
1286 }
1287 }
1288 return FALSE;
1289 }
1290
1291 /**
1292 * Get fields that indicate payment fields have been requested for a component.
1293 *
1294 * Ideally this should be protected but making it temporarily public helps refactoring..
1295 *
1296 * @return array
1297 */
1298 public function getComponentPaymentFields() {
1299 return [
1300 'componentPaymentField_total_amount' => ['title' => ts('Total Amount'), 'type' => CRM_Utils_Type::T_MONEY],
1301 'componentPaymentField_contribution_status' => ['title' => ts('Contribution Status'), 'type' => CRM_Utils_Type::T_STRING],
1302 'componentPaymentField_received_date' => ['title' => ts('Date Received'), 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME],
1303 'componentPaymentField_payment_instrument' => ['title' => ts('Payment Method'), 'type' => CRM_Utils_Type::T_STRING],
1304 'componentPaymentField_transaction_id' => ['title' => ts('Transaction ID'), 'type' => CRM_Utils_Type::T_STRING],
1305 ];
1306 }
1307
1308 /**
1309 * Get headers for payment fields.
1310 *
1311 * Returns an array of contribution fields when the entity supports payment fields and specific fields
1312 * are not specified. This is a transitional function for refactoring legacy code.
1313 */
1314 public function getPaymentHeaders() {
1315 if ($this->isExportPaymentFields() && !$this->isExportSpecifiedPaymentFields()) {
1316 return CRM_Utils_Array::collect('title', $this->getcomponentPaymentFields());
1317 }
1318 return [];
1319 }
1320
1321 /**
1322 * Get the default properties when not specified.
1323 *
1324 * In the UI this appears as 'Primary fields only' but in practice it's
1325 * most of the kitchen sink and the hallway closet thrown in.
1326 *
1327 * Since CRM-952 custom fields are excluded, but no other form of mercy is shown.
1328 *
1329 * @return array
1330 */
1331 public function getDefaultReturnProperties() {
1332 $returnProperties = [];
1333 $fields = CRM_Contact_BAO_Contact::exportableFields('All', TRUE, TRUE);
1334 $skippedFields = ($this->getQueryMode() === CRM_Contact_BAO_Query::MODE_CONTACTS) ? [] : [
1335 'groups',
1336 'tags',
1337 'notes',
1338 ];
1339
1340 foreach ($fields as $key => $var) {
1341 if ($key && (substr($key, 0, 6) != 'custom') && !in_array($key, $skippedFields)) {
1342 $returnProperties[$key] = 1;
1343 }
1344 }
1345 $returnProperties = array_merge($returnProperties, $this->getAdditionalReturnProperties());
1346 return $returnProperties;
1347 }
1348
1349 /**
1350 * Add the field to relationship return properties & return it.
1351 *
1352 * This function is doing both setting & getting which is yuck but it is an interim
1353 * refactor.
1354 *
1355 * @param array $value
1356 * @param string $relationshipKey
1357 *
1358 * @return array
1359 */
1360 public function setRelationshipReturnProperties($value, $relationshipKey) {
1361 $relationField = $value['name'];
1362 $relIMProviderId = NULL;
1363 $relLocTypeId = $value['location_type_id'] ?? NULL;
1364 $locationName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_Address', 'location_type_id', $relLocTypeId);
1365 $relPhoneTypeId = CRM_Utils_Array::value('phone_type_id', $value, ($locationName ? 'Primary' : NULL));
1366 $relIMProviderId = CRM_Utils_Array::value('im_provider_id', $value, ($locationName ? 'Primary' : NULL));
1367 if (in_array($relationField, $this->getValidLocationFields()) && $locationName) {
1368 if ($relationField === 'phone') {
1369 $this->relationshipReturnProperties[$relationshipKey]['location'][$locationName]['phone-' . $relPhoneTypeId] = 1;
1370 }
1371 elseif ($relationField === 'im') {
1372 $this->relationshipReturnProperties[$relationshipKey]['location'][$locationName]['im-' . $relIMProviderId] = 1;
1373 }
1374 else {
1375 $this->relationshipReturnProperties[$relationshipKey]['location'][$locationName][$relationField] = 1;
1376 }
1377 }
1378 else {
1379 $this->relationshipReturnProperties[$relationshipKey][$relationField] = 1;
1380 }
1381 return $this->relationshipReturnProperties[$relationshipKey];
1382 }
1383
1384 /**
1385 * Add the main return properties to the household merge properties if needed for merging.
1386 *
1387 * If we are using household merge we need to add these to the relationship properties to
1388 * be retrieved.
1389 */
1390 public function setHouseholdMergeReturnProperties() {
1391 if ($this->isMergeSameHousehold()) {
1392 $returnProperties = $this->getReturnProperties();
1393 $returnProperties = array_diff_key($returnProperties, array_fill_keys(['location_type', 'im_provider'], 1));
1394 foreach ($this->getHouseholdRelationshipTypes() as $householdRelationshipType) {
1395 $this->relationshipReturnProperties[$householdRelationshipType] = $returnProperties;
1396 }
1397 }
1398 }
1399
1400 /**
1401 * Get the default location fields to request.
1402 *
1403 * @return array
1404 */
1405 public function getValidLocationFields() {
1406 return [
1407 'street_address',
1408 'supplemental_address_1',
1409 'supplemental_address_2',
1410 'supplemental_address_3',
1411 'city',
1412 'postal_code',
1413 'postal_code_suffix',
1414 'geo_code_1',
1415 'geo_code_2',
1416 'state_province',
1417 'country',
1418 'phone',
1419 'email',
1420 'im',
1421 ];
1422 }
1423
1424 /**
1425 * Get the sql column definition for the given field.
1426 *
1427 * @param string $fieldName
1428 * @param string $columnName
1429 *
1430 * @return mixed
1431 */
1432 public function getSqlColumnDefinition($fieldName, $columnName) {
1433
1434 // early exit for master_id, CRM-12100
1435 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1436 // also for current_employer, CRM-16939
1437 if ($columnName == 'master_id' || $columnName == 'current_employer') {
1438 return "`$fieldName` varchar(128)";
1439 }
1440
1441 $queryFields = $this->getQueryFields();
1442 // @todo remove the enotice avoidance here, ensure all columns are declared.
1443 // tests will fail on the enotices until they all are & then all the 'else'
1444 // below can go.
1445 $fieldSpec = $queryFields[$columnName] ?? [];
1446
1447 // set the sql columns
1448 if (isset($fieldSpec['type'])) {
1449 switch ($fieldSpec['type']) {
1450 case CRM_Utils_Type::T_INT:
1451 case CRM_Utils_Type::T_BOOLEAN:
1452 if (in_array(CRM_Utils_Array::value('data_type', $fieldSpec), ['Country', 'StateProvince', 'ContactReference'])) {
1453 return "`$fieldName` varchar(255)";
1454 }
1455 return "`$fieldName` varchar(16)";
1456
1457 case CRM_Utils_Type::T_STRING:
1458 if (isset($queryFields[$columnName]['maxlength'])) {
1459 return "`$fieldName` varchar({$queryFields[$columnName]['maxlength']})";
1460 }
1461 else {
1462 return "`$fieldName` varchar(255)";
1463 }
1464
1465 case CRM_Utils_Type::T_TEXT:
1466 case CRM_Utils_Type::T_LONGTEXT:
1467 case CRM_Utils_Type::T_BLOB:
1468 case CRM_Utils_Type::T_MEDIUMBLOB:
1469 return "`$fieldName` longtext";
1470
1471 case CRM_Utils_Type::T_FLOAT:
1472 case CRM_Utils_Type::T_ENUM:
1473 case CRM_Utils_Type::T_DATE:
1474 case CRM_Utils_Type::T_TIME:
1475 case CRM_Utils_Type::T_TIMESTAMP:
1476 case CRM_Utils_Type::T_MONEY:
1477 case CRM_Utils_Type::T_EMAIL:
1478 case CRM_Utils_Type::T_URL:
1479 case CRM_Utils_Type::T_CCNUM:
1480 default:
1481 return "`$fieldName` varchar(32)";
1482 }
1483 }
1484 else {
1485 if (substr($fieldName, -3, 3) == '_id') {
1486 return "`$fieldName` varchar(255)";
1487 }
1488 elseif (substr($fieldName, -5, 5) == '_note') {
1489 return "`$fieldName` text";
1490 }
1491 else {
1492 $changeFields = [
1493 'groups',
1494 'tags',
1495 'notes',
1496 ];
1497
1498 if (in_array($fieldName, $changeFields)) {
1499 return "`$fieldName` text";
1500 }
1501 else {
1502 // set the sql columns for custom data
1503 if (isset($queryFields[$columnName]['data_type'])) {
1504
1505 switch ($queryFields[$columnName]['data_type']) {
1506 case 'String':
1507 // May be option labels, which could be up to 512 characters
1508 $length = max(512, CRM_Utils_Array::value('text_length', $queryFields[$columnName]));
1509 return "`$fieldName` varchar($length)";
1510
1511 case 'Link':
1512 return "`$fieldName` varchar(255)";
1513
1514 case 'Memo':
1515 return "`$fieldName` text";
1516
1517 default:
1518 return "`$fieldName` varchar(255)";
1519 }
1520 }
1521 else {
1522 return "`$fieldName` text";
1523 }
1524 }
1525 }
1526 }
1527 }
1528
1529 /**
1530 * Get the munged field name.
1531 *
1532 * @param string $field
1533 * @return string
1534 */
1535 public function getMungedFieldName($field) {
1536 $fieldName = CRM_Utils_String::munge(strtolower($field), '_', 64);
1537 if ($fieldName == 'id') {
1538 $fieldName = 'civicrm_primary_id';
1539 }
1540 return $fieldName;
1541 }
1542
1543 /**
1544 * In order to respect the history of this class we need to index kinda illogically.
1545 *
1546 * On the bright side - this stuff is tested within a nano-byte of it's life.
1547 *
1548 * e.g '2-a-b_Home-City'
1549 *
1550 * @param string $key
1551 * @param string $relationshipType
1552 * @param string $locationType
1553 * @param $entityLabel
1554 *
1555 * @return string
1556 */
1557 protected function getOutputSpecificationIndex($key, $relationshipType, $locationType, $entityLabel) {
1558 if (!$relationshipType || $key !== 'id') {
1559 $key = $this->getMungedFieldName($key);
1560 }
1561 return $this->getMungedFieldName(
1562 ($relationshipType ? ($relationshipType . '_') : '')
1563 . ($locationType ? ($locationType . '_') : '')
1564 . $key
1565 . ($entityLabel ? ('_' . $entityLabel) : '')
1566 );
1567 }
1568
1569 /**
1570 * Get the compiled label for the column.
1571 *
1572 * e.g 'Gender', 'Employee Of-Home-city'
1573 *
1574 * @param string $key
1575 * @param string $relationshipType
1576 * @param string $locationType
1577 * @param string $entityLabel
1578 *
1579 * @return string
1580 */
1581 protected function getOutputSpecificationLabel($key, $relationshipType, $locationType, $entityLabel) {
1582 return ($relationshipType ? $this->getRelationshipTypes()[$relationshipType] . '-' : '')
1583 . ($locationType ? $locationType . '-' : '')
1584 . $this->getHeaderForRow($key)
1585 . ($entityLabel ? '-' . $entityLabel : '');
1586 }
1587
1588 /**
1589 * Get the mysql field name key.
1590 *
1591 * This key is locked in by tests but the reasons for the specific conventions -
1592 * ie. headings are used for keying fields in some cases, are likely
1593 * accidental rather than deliberate.
1594 *
1595 * This key is used for the output sql array.
1596 *
1597 * @param string $key
1598 * @param $relationshipType
1599 * @param $locationType
1600 * @param $entityLabel
1601 *
1602 * @return string
1603 */
1604 protected function getOutputSpecificationFieldKey($key, $relationshipType, $locationType, $entityLabel) {
1605 if (!$relationshipType || $key !== 'id') {
1606 $key = $this->getMungedFieldName($key);
1607 }
1608 $fieldKey = $this->getMungedFieldName(
1609 ($relationshipType ? ($relationshipType . '_') : '')
1610 . ($locationType ? ($locationType . '_') : '')
1611 . $key
1612 . ($entityLabel ? ('_' . $entityLabel) : '')
1613 );
1614 return $fieldKey;
1615 }
1616
1617 /**
1618 * Get params for the where criteria.
1619 *
1620 * @return mixed
1621 */
1622 public function getWhereParams() {
1623 if (!$this->isPostalableOnly()) {
1624 return [];
1625 }
1626 $params['is_deceased'] = ['is_deceased', '=', 0, CRM_Contact_BAO_Query::MODE_CONTACTS];
1627 $params['do_not_mail'] = ['do_not_mail', '=', 0, CRM_Contact_BAO_Query::MODE_CONTACTS];
1628 return $params;
1629 }
1630
1631 /**
1632 * @param $row
1633 * @param $contactID
1634 * @param $value
1635 * @param $field
1636 */
1637 protected function buildRelationshipFieldsForRow(&$row, $contactID, $value, $field) {
1638 foreach (array_keys($value) as $property) {
1639 if ($property === 'location') {
1640 // @todo just undo all this nasty location wrangling!
1641 foreach ($value['location'] as $locationKey => $locationFields) {
1642 foreach (array_keys($locationFields) as $locationField) {
1643 $fieldKey = str_replace(' ', '_', $locationKey . '-' . $locationField);
1644 $row[$field . '_' . $fieldKey] = $this->getRelationshipValue($field, $contactID, $fieldKey);
1645 }
1646 }
1647 }
1648 else {
1649 $row[$field . '_' . $property] = $this->getRelationshipValue($field, $contactID, $property);
1650 }
1651 }
1652 }
1653
1654 /**
1655 * Is this contact a household that is already set to be exported by virtue of it's household members.
1656 *
1657 * @param int $contactID
1658 *
1659 * @return bool
1660 */
1661 protected function isHouseholdToSkip($contactID) {
1662 return in_array($contactID, $this->householdsToSkip);
1663 }
1664
1665 /**
1666 * Get the various arrays that we use to structure our output.
1667 *
1668 * The extraction of these has been moved to a separate function for clarity and so that
1669 * tests can be added - in particular on the $outputHeaders array.
1670 *
1671 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1672 * as a step on the refactoring path rather than how it should be.
1673 *
1674 * @return array
1675 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1676 * alias for the field generated by BAO_Query object.
1677 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1678 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1679 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1680 * I'm too embarassed to discuss here.
1681 * The keys need
1682 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1683 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1684 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1685 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1686 * - a) the function used is more efficient or
1687 * - b) this code is old & outdated. Submit your answers to circular bin or better
1688 * yet find a way to comment them for posterity.
1689 */
1690 public function getExportStructureArrays() {
1691 $outputColumns = [];
1692 $queryFields = $this->getQueryFields();
1693 foreach ($this->getReturnProperties() as $key => $value) {
1694 if (($key != 'location' || !is_array($value)) && !$this->isRelationshipTypeKey($key)) {
1695 $outputColumns[$key] = $value;
1696 $this->addOutputSpecification($key);
1697 }
1698 elseif ($this->isRelationshipTypeKey($key)) {
1699 $outputColumns[$key] = $value;
1700 foreach ($value as $relationField => $relationValue) {
1701 // below block is same as primary block (duplicate)
1702 if (isset($queryFields[$relationField]['title'])) {
1703 $this->addOutputSpecification($relationField, $key);
1704 }
1705 elseif (is_array($relationValue) && $relationField == 'location') {
1706 // fix header for location type case
1707 foreach ($relationValue as $ltype => $val) {
1708 foreach (array_keys($val) as $fld) {
1709 $type = explode('-', $fld);
1710 $this->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array::value(1, $type));
1711 }
1712 }
1713 }
1714 }
1715 }
1716 else {
1717 foreach ($value as $locationType => $locationFields) {
1718 foreach (array_keys($locationFields) as $locationFieldName) {
1719 $type = explode('-', $locationFieldName);
1720
1721 $actualDBFieldName = $type[0];
1722 $daoFieldName = CRM_Utils_String::munge($locationType) . '-' . $actualDBFieldName;
1723
1724 if (!empty($type[1])) {
1725 $daoFieldName .= "-" . $type[1];
1726 }
1727 $this->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array::value(1, $type));
1728 $outputColumns[$daoFieldName] = TRUE;
1729 }
1730 }
1731 }
1732 }
1733 return [$outputColumns];
1734 }
1735
1736 /**
1737 * Get default return property for export based on mode
1738 *
1739 * @return string
1740 * Default Return property
1741 */
1742 public function defaultReturnProperty() {
1743 // hack to add default return property based on export mode
1744 $property = NULL;
1745 $exportMode = $this->getExportMode();
1746 if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
1747 $property = 'contribution_id';
1748 }
1749 elseif ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
1750 $property = 'participant_id';
1751 }
1752 elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
1753 $property = 'membership_id';
1754 }
1755 elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
1756 $property = 'pledge_id';
1757 }
1758 elseif ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
1759 $property = 'case_id';
1760 }
1761 elseif ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT) {
1762 $property = 'grant_id';
1763 }
1764 elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
1765 $property = 'activity_id';
1766 }
1767 return $property;
1768 }
1769
1770 /**
1771 * Determine the required return properties from the input parameters.
1772 *
1773 * @return array
1774 */
1775 public function determineReturnProperties() {
1776 if ($this->getRequestedFields()) {
1777 $returnProperties = [];
1778 foreach ($this->getRequestedFields() as $key => $value) {
1779 $fieldName = $value['name'];
1780 $locationName = !empty($value['location_type_id']) ? CRM_Core_PseudoConstant::getName('CRM_Core_BAO_Address', 'location_type_id', $value['location_type_id']) : NULL;
1781 $relationshipTypeKey = !empty($value['relationship_type_id']) ? $value['relationship_type_id'] . '_' . $value['relationship_direction'] : NULL;
1782 if (!$fieldName || $this->isHouseholdMergeRelationshipTypeKey($relationshipTypeKey)) {
1783 continue;
1784 }
1785
1786 if ($this->isRelationshipTypeKey($relationshipTypeKey)) {
1787 $returnProperties[$relationshipTypeKey] = $this->setRelationshipReturnProperties($value, $relationshipTypeKey);
1788 }
1789 elseif ($locationName) {
1790 if ($fieldName === 'phone') {
1791 $returnProperties['location'][$locationName]['phone-' . $value['phone_type_id'] ?? NULL] = 1;
1792 }
1793 elseif ($fieldName === 'im') {
1794 $returnProperties['location'][$locationName]['im-' . $value['im_provider_id'] ?? NULL] = 1;
1795 }
1796 else {
1797 $returnProperties['location'][$locationName][$fieldName] = 1;
1798 }
1799 }
1800 else {
1801 //hack to fix component fields
1802 //revert mix of event_id and title
1803 if ($fieldName == 'event_id') {
1804 $returnProperties['event_id'] = 1;
1805 }
1806 else {
1807 $returnProperties[$fieldName] = 1;
1808 }
1809 }
1810 }
1811 $defaultExportMode = $this->defaultReturnProperty();
1812 if ($defaultExportMode) {
1813 $returnProperties[$defaultExportMode] = 1;
1814 }
1815 }
1816 else {
1817 $returnProperties = $this->getDefaultReturnProperties();
1818 }
1819 if ($this->isMergeSameHousehold()) {
1820 $returnProperties['id'] = 1;
1821 }
1822 if ($this->isMergeSameAddress()) {
1823 $returnProperties['addressee'] = 1;
1824 $returnProperties['postal_greeting'] = 1;
1825 $returnProperties['email_greeting'] = 1;
1826 $returnProperties['street_name'] = 1;
1827 $returnProperties['household_name'] = 1;
1828 $returnProperties['street_address'] = 1;
1829 $returnProperties['city'] = 1;
1830 $returnProperties['state_province'] = 1;
1831
1832 }
1833 return $returnProperties;
1834 }
1835
1836 /**
1837 * @param object $query
1838 * CRM_Contact_BAO_Query
1839 *
1840 * @return string
1841 * Group By Clause
1842 */
1843 public function getGroupBy($query) {
1844 $groupBy = NULL;
1845 $returnProperties = $this->getReturnProperties();
1846 $exportMode = $this->getExportMode();
1847 $queryMode = $this->getQueryMode();
1848 if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) ||
1849 CRM_Utils_Array::value('notes', $returnProperties) ||
1850 // CRM-9552
1851 ($queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy)
1852 ) {
1853 $groupBy = "contact_a.id";
1854 }
1855
1856 switch ($exportMode) {
1857 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
1858 $groupBy = 'civicrm_contribution.id';
1859 if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
1860 // especial group by when soft credit columns are included
1861 $groupBy = ['contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id'];
1862 }
1863 break;
1864
1865 case CRM_Export_Form_Select::EVENT_EXPORT:
1866 $groupBy = 'civicrm_participant.id';
1867 break;
1868
1869 case CRM_Export_Form_Select::MEMBER_EXPORT:
1870 $groupBy = "civicrm_membership.id";
1871 break;
1872 }
1873
1874 if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
1875 $groupBy = "civicrm_activity.id ";
1876 }
1877
1878 return $groupBy ? ' GROUP BY ' . implode(', ', (array) $groupBy) : '';
1879 }
1880
1881 /**
1882 * @param int $contactId
1883 *
1884 * @return array
1885 */
1886 public function replaceMergeTokens($contactId) {
1887 $greetings = [];
1888 $contact = NULL;
1889
1890 $greetingFields = [
1891 'postal_greeting' => $this->getPostalGreetingTemplate(),
1892 'addressee' => $this->getAddresseeGreetingTemplate(),
1893 ];
1894 foreach ($greetingFields as $greeting => $greetingLabel) {
1895 $tokens = CRM_Utils_Token::getTokens($greetingLabel);
1896 if (!empty($tokens)) {
1897 if (empty($contact)) {
1898 $values = [
1899 'id' => $contactId,
1900 'version' => 3,
1901 ];
1902 $contact = civicrm_api('contact', 'get', $values);
1903
1904 if (!empty($contact['is_error'])) {
1905 return $greetings;
1906 }
1907 $contact = $contact['values'][$contact['id']];
1908 }
1909
1910 $tokens = ['contact' => $greetingLabel];
1911 $greetings[$greeting] = CRM_Utils_Token::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1912 }
1913 }
1914 return $greetings;
1915 }
1916
1917 /**
1918 * Build array for merging same addresses.
1919 *
1920 * @param string $sql
1921 */
1922 public function buildMasterCopyArray($sql) {
1923
1924 $parents = [];
1925 $dao = CRM_Core_DAO::executeQuery($sql);
1926
1927 while ($dao->fetch()) {
1928 $masterID = $dao->master_id;
1929 $copyID = $dao->copy_id;
1930
1931 $this->cacheContactGreetings((int) $dao->master_contact_id);
1932 $this->cacheContactGreetings((int) $dao->copy_contact_id);
1933
1934 if (!isset($this->contactsToMerge[$masterID])) {
1935 // check if this is an intermediate child
1936 // this happens if there are 3 or more matches a,b, c
1937 // the above query will return a, b / a, c / b, c
1938 // we might be doing a bit more work, but for now its ok, unless someone
1939 // knows how to fix the query above
1940 if (isset($parents[$masterID])) {
1941 $masterID = $parents[$masterID];
1942 }
1943 else {
1944 $this->contactsToMerge[$masterID] = [
1945 'addressee' => $this->getContactGreeting((int) $dao->master_contact_id, 'addressee', $dao->master_addressee),
1946 'copy' => [],
1947 'postalGreeting' => $this->getContactGreeting((int) $dao->master_contact_id, 'postal_greeting', $dao->master_postal_greeting),
1948 ];
1949 $this->contactsToMerge[$masterID]['emailGreeting'] = &$this->contactsToMerge[$masterID]['postalGreeting'];
1950 }
1951 }
1952 $parents[$copyID] = $masterID;
1953
1954 if (!array_key_exists($copyID, $this->contactsToMerge[$masterID]['copy'])) {
1955 $copyPostalGreeting = $this->getContactPortionOfGreeting((int) $dao->copy_contact_id, (int) $dao->copy_postal_greeting_id, 'postal_greeting', $dao->copy_postal_greeting);
1956 if ($copyPostalGreeting) {
1957 $this->contactsToMerge[$masterID]['postalGreeting'] = "{$this->contactsToMerge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1958 // if there happens to be a duplicate, remove it
1959 $this->contactsToMerge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $this->contactsToMerge[$masterID]['postalGreeting']);
1960 }
1961
1962 $copyAddressee = $this->getContactPortionOfGreeting((int) $dao->copy_contact_id, (int) $dao->copy_addressee_id, 'addressee', $dao->copy_addressee);
1963 if ($copyAddressee) {
1964 $this->contactsToMerge[$masterID]['addressee'] = "{$this->contactsToMerge[$masterID]['addressee']}, " . trim($copyAddressee);
1965 }
1966 }
1967 if (!isset($this->contactsToMerge[$masterID]['copy'][$copyID])) {
1968 // If it was set in the first run through - share routine, don't subsequently clobber.
1969 $this->contactsToMerge[$masterID]['copy'][$copyID] = $copyAddressee ?? $dao->copy_addressee;
1970 }
1971 }
1972 }
1973
1974 /**
1975 * Merge contacts with the same address.
1976 */
1977 public function mergeSameAddress() {
1978
1979 $tableName = $this->getTemporaryTable();
1980
1981 // find all the records that have the same street address BUT not in a household
1982 // require match on city and state as well
1983 $sql = "
1984 SELECT r1.id as master_id,
1985 r1.civicrm_primary_id as master_contact_id,
1986 r1.postal_greeting as master_postal_greeting,
1987 r1.postal_greeting_id as master_postal_greeting_id,
1988 r1.addressee as master_addressee,
1989 r1.addressee_id as master_addressee_id,
1990 r2.id as copy_id,
1991 r2.civicrm_primary_id as copy_contact_id,
1992 r2.postal_greeting as copy_postal_greeting,
1993 r2.postal_greeting_id as copy_postal_greeting_id,
1994 r2.addressee as copy_addressee,
1995 r2.addressee_id as copy_addressee_id
1996 FROM $tableName r1
1997 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1998 r1.city = r2.city AND
1999 r1.state_province_id = r2.state_province_id )
2000 WHERE ( r1.street_address != '' )
2001 AND r2.id > r1.id
2002 ORDER BY r1.id
2003 ";
2004 $this->buildMasterCopyArray($sql);
2005
2006 foreach ($this->contactsToMerge as $masterID => $values) {
2007 $sql = "
2008 UPDATE $tableName
2009 SET addressee = %1, postal_greeting = %2, email_greeting = %3
2010 WHERE id = %4
2011 ";
2012 $params = [
2013 1 => [$values['addressee'], 'String'],
2014 2 => [$values['postalGreeting'], 'String'],
2015 3 => [$values['emailGreeting'], 'String'],
2016 4 => [$masterID, 'Integer'],
2017 ];
2018 CRM_Core_DAO::executeQuery($sql, $params);
2019
2020 // delete all copies
2021 $deleteIDs = array_keys($values['copy']);
2022 $deleteIDString = implode(',', $deleteIDs);
2023 $sql = "
2024 DELETE FROM $tableName
2025 WHERE id IN ( $deleteIDString )
2026 ";
2027 CRM_Core_DAO::executeQuery($sql);
2028 }
2029 }
2030
2031 /**
2032 * The function unsets static part of the string, if token is the dynamic part.
2033 *
2034 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
2035 * i.e 'Hello Alan' => converted to => 'Alan'
2036 *
2037 * @param string $parsedString
2038 * @param string $defaultGreeting
2039 * @param string $greetingLabel
2040 *
2041 * @return mixed
2042 */
2043 public function trimNonTokensFromAddressString(
2044 &$parsedString, $defaultGreeting,
2045 $greetingLabel
2046 ) {
2047 $greetingLabel = empty($greetingLabel) ? $defaultGreeting : $greetingLabel;
2048
2049 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
2050 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
2051 foreach ($stringsToBeReplaced as $key => $string) {
2052 // to keep one space
2053 $stringsToBeReplaced[$key] = ltrim($string);
2054 }
2055 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
2056
2057 return $parsedString;
2058 }
2059
2060 /**
2061 * Preview export output.
2062 *
2063 * @param int $limit
2064 * @return array
2065 */
2066 public function getPreview($limit) {
2067 $rows = [];
2068 list($outputColumns) = $this->getExportStructureArrays();
2069 $query = $this->runQuery([], '');
2070 CRM_Core_DAO::disableFullGroupByMode();
2071 $result = CRM_Core_DAO::executeQuery($query[1] . ' LIMIT ' . (int) $limit);
2072 CRM_Core_DAO::reenableFullGroupByMode();
2073 while ($result->fetch()) {
2074 $rows[] = $this->buildRow($query[0], $result, $outputColumns, [], []);
2075 }
2076 return $rows;
2077 }
2078
2079 /**
2080 * Set the template strings to be used when merging two contacts with the same address.
2081 *
2082 * @param array $formValues
2083 * Values from first form. In this case we care about the keys
2084 * - postal_greeting
2085 * - postal_other
2086 * - address_greeting
2087 * - addressee_other
2088 *
2089 * @return mixed
2090 */
2091 protected function setGreetingStringsForSameAddressMerge($formValues) {
2092 $greetingOptions = CRM_Export_Form_Select::getGreetingOptions();
2093
2094 if (!empty($greetingOptions)) {
2095 // Greeting options is keyed by 'postal_greeting' or 'addressee'.
2096 foreach ($greetingOptions as $key => $value) {
2097 $option = $formValues[$key] ?? NULL;
2098 if ($option) {
2099 if ($greetingOptions[$key][$option] == ts('Other')) {
2100 $formValues[$key] = $formValues["{$key}_other"];
2101 }
2102 elseif ($greetingOptions[$key][$option] == ts('List of names')) {
2103 $formValues[$key] = '';
2104 }
2105 else {
2106 $formValues[$key] = $greetingOptions[$key][$option];
2107 }
2108 }
2109 }
2110 }
2111 if (!empty($formValues['postal_greeting'])) {
2112 $this->setPostalGreetingTemplate($formValues['postal_greeting']);
2113 }
2114 if (!empty($formValues['addressee'])) {
2115 $this->setAddresseeGreetingTemplate($formValues['addressee']);
2116 }
2117 }
2118
2119 /**
2120 * Create the temporary table for output.
2121 */
2122 public function createTempTable() {
2123 //creating a temporary table for the search result that need be exported
2124 $exportTempTable = CRM_Utils_SQL_TempTable::build()->setDurable()->setCategory('export');
2125 $sqlColumns = $this->getSQLColumns();
2126 // also create the sql table
2127 $exportTempTable->drop();
2128
2129 $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
2130 if (!empty($sqlColumns)) {
2131 $sql .= implode(",\n", array_values($sqlColumns)) . ',';
2132 }
2133
2134 $sql .= "\n PRIMARY KEY ( id )";
2135
2136 // add indexes for street_address and household_name if present
2137 $addIndices = [
2138 'street_address',
2139 'household_name',
2140 'civicrm_primary_id',
2141 ];
2142
2143 foreach ($addIndices as $index) {
2144 if (isset($sqlColumns[$index])) {
2145 $sql .= ",
2146 INDEX index_{$index}( $index )
2147 ";
2148 }
2149 }
2150
2151 $exportTempTable->createWithColumns($sql);
2152 $this->setTemporaryTable($exportTempTable->getName());
2153 }
2154
2155 /**
2156 * Get the values of linked household contact.
2157 *
2158 * @param CRM_Core_DAO $relDAO
2159 * @param array $value
2160 * @param string $field
2161 * @param array $row
2162 *
2163 * @throws \Exception
2164 */
2165 public function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
2166 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
2167 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
2168 $i18n = CRM_Core_I18n::singleton();
2169 $field = $field . '_';
2170
2171 foreach ($value as $relationField => $relationValue) {
2172 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
2173 $fieldValue = $relDAO->$relationField;
2174 if ($relationField == 'phone_type_id') {
2175 $fieldValue = $phoneTypes[$relationValue];
2176 }
2177 elseif ($relationField == 'provider_id') {
2178 $fieldValue = $imProviders[$relationValue] ?? NULL;
2179 }
2180 // CRM-13995
2181 elseif (is_object($relDAO) && in_array($relationField, [
2182 'email_greeting',
2183 'postal_greeting',
2184 'addressee',
2185 ])) {
2186 //special case for greeting replacement
2187 $fldValue = "{$relationField}_display";
2188 $fieldValue = $relDAO->$fldValue;
2189 }
2190 }
2191 elseif (is_object($relDAO) && $relationField == 'state_province') {
2192 $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
2193 }
2194 elseif (is_object($relDAO) && $relationField == 'country') {
2195 $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
2196 }
2197 else {
2198 $fieldValue = '';
2199 }
2200 $relPrefix = $field . $relationField;
2201
2202 if (is_object($relDAO) && $relationField == 'id') {
2203 $row[$relPrefix] = $relDAO->contact_id;
2204 }
2205 elseif (is_array($relationValue) && $relationField == 'location') {
2206 foreach ($relationValue as $ltype => $val) {
2207 // If the location name has a space in it the we need to handle that. This
2208 // is kinda hacky but specifically covered in the ExportTest so later efforts to
2209 // improve it should be secure in the knowled it will be caught.
2210 $ltype = str_replace(' ', '_', $ltype);
2211 foreach (array_keys($val) as $fld) {
2212 $type = explode('-', $fld);
2213 $fldValue = "{$ltype}-" . $type[0];
2214 if (!empty($type[1])) {
2215 $fldValue .= "-" . $type[1];
2216 }
2217 // CRM-3157: localise country, region (both have ‘country’ context)
2218 // and state_province (‘province’ context)
2219 switch (TRUE) {
2220 case (!is_object($relDAO)):
2221 $row[$field . '_' . $fldValue] = '';
2222 break;
2223
2224 case in_array('country', $type):
2225 case in_array('world_region', $type):
2226 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2227 ['context' => 'country']
2228 );
2229 break;
2230
2231 case in_array('state_province', $type):
2232 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2233 ['context' => 'province']
2234 );
2235 break;
2236
2237 default:
2238 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
2239 break;
2240 }
2241 }
2242 }
2243 }
2244 elseif (isset($fieldValue) && $fieldValue != '') {
2245 //check for custom data
2246 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
2247 $row[$relPrefix] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
2248 }
2249 else {
2250 //normal relationship fields
2251 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
2252 switch ($relationField) {
2253 case 'country':
2254 case 'world_region':
2255 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
2256 break;
2257
2258 case 'state_province':
2259 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
2260 break;
2261
2262 default:
2263 $row[$relPrefix] = $fieldValue;
2264 break;
2265 }
2266 }
2267 }
2268 else {
2269 // if relation field is empty or null
2270 $row[$relPrefix] = '';
2271 }
2272 }
2273 }
2274
2275 /**
2276 * Write to the csv from the temp table.
2277 */
2278 public function writeCSVFromTable() {
2279 // call export hook
2280 $headerRows = $this->getHeaderRows();
2281 $exportTempTable = $this->getTemporaryTable();
2282 $exportMode = $this->getExportMode();
2283 $sqlColumns = $this->getSQLColumns();
2284 $componentTable = $this->getComponentTable();
2285 $ids = $this->getIds();
2286 CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
2287 if ($exportMode !== $this->getExportMode() || $componentTable !== $this->getComponentTable()) {
2288 CRM_Core_Error::deprecatedFunctionWarning('altering the export mode and/or component table in the hook is no longer supported.');
2289 }
2290 if ($ids !== $this->getIds()) {
2291 CRM_Core_Error::deprecatedFunctionWarning('altering the ids in the hook is no longer supported.');
2292 }
2293 if ($exportTempTable !== $this->getTemporaryTable()) {
2294 CRM_Core_Error::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
2295 $this->setTemporaryTable($exportTempTable);
2296 }
2297 $exportTempTable = $this->getTemporaryTable();
2298 $writeHeader = TRUE;
2299 $offset = 0;
2300 // increase this number a lot to avoid making too many queries
2301 // LIMIT is not much faster than a no LIMIT query
2302 // CRM-7675
2303 $limit = 100000;
2304
2305 $query = "SELECT * FROM $exportTempTable";
2306
2307 $this->instantiateTempTable($headerRows);
2308 while (1) {
2309 $limitQuery = $query . "
2310 LIMIT $offset, $limit
2311 ";
2312 $dao = CRM_Core_DAO::executeQuery($limitQuery);
2313
2314 if ($dao->N <= 0) {
2315 break;
2316 }
2317
2318 $componentDetails = [];
2319 while ($dao->fetch()) {
2320 $row = [];
2321
2322 foreach (array_keys($sqlColumns) as $column) {
2323 $row[$column] = $dao->$column;
2324 }
2325 $componentDetails[] = $row;
2326 }
2327 $this->writeRows($headerRows, $componentDetails);
2328
2329 $offset += $limit;
2330 }
2331 }
2332
2333 /**
2334 * Set up the temp table.
2335 *
2336 * @param array $headerRows
2337 */
2338 protected function instantiateTempTable(array $headerRows) {
2339 CRM_Utils_System::download(CRM_Utils_String::munge($this->getExportFileName()),
2340 'text/x-csv',
2341 CRM_Core_DAO::$_nullObject,
2342 'csv',
2343 FALSE
2344 );
2345 // Output UTF BOM so that MS Excel copes with diacritics. This is recommended as
2346 // the Windows variant but is tested with MS Excel for Mac (Office 365 v 16.31)
2347 // and it continues to work on Libre Office, Numbers, Notes etc.
2348 echo "\xEF\xBB\xBF";
2349 CRM_Core_Report_Excel::makeCSVTable($headerRows, [], TRUE);
2350 }
2351
2352 /**
2353 * Write rows to the csv.
2354 *
2355 * @param array $headerRows
2356 * @param array $rows
2357 */
2358 protected function writeRows(array $headerRows, array $rows) {
2359 if (!empty($rows)) {
2360 CRM_Core_Report_Excel::makeCSVTable($headerRows, $rows, FALSE);
2361 }
2362 }
2363
2364 /**
2365 * Cache the greeting fields for the given contact.
2366 *
2367 * @param int $contactID
2368 */
2369 protected function cacheContactGreetings(int $contactID) {
2370 if (!isset($this->contactGreetingFields[$contactID])) {
2371 $this->contactGreetingFields[$contactID] = $this->replaceMergeTokens($contactID);
2372 }
2373 }
2374
2375 /**
2376 * Get the greeting value for the given contact.
2377 *
2378 * The values have already been cached so we are grabbing the value at this point.
2379 *
2380 * @param int $contactID
2381 * @param string $type
2382 * postal_greeting|addressee|email_greeting
2383 * @param string $default
2384 *
2385 * @return string
2386 */
2387 protected function getContactGreeting(int $contactID, string $type, string $default) {
2388 return CRM_Utils_Array::value($type,
2389 $this->contactGreetingFields[$contactID], $default
2390 );
2391 }
2392
2393 /**
2394 * Get the portion of the greeting string that relates to the contact.
2395 *
2396 * For example if the greeting id 'Dear Sarah' we are going to combine it with 'Dear Mike'
2397 * so we want to strip the 'Dear ' and just get 'Sarah
2398 * @param int $contactID
2399 * @param int $greetingID
2400 * @param string $type
2401 * postal_greeting, addressee (email_greeting not currently implemented for unknown reasons.
2402 * @param string $defaultGreeting
2403 *
2404 * @return mixed|string
2405 */
2406 protected function getContactPortionOfGreeting(int $contactID, int $greetingID, string $type, string $defaultGreeting) {
2407 $copyPostalGreeting = $this->getContactGreeting($contactID, $type, $defaultGreeting);
2408 $template = $type === 'postal_greeting' ? $this->getPostalGreetingTemplate() : $this->getAddresseeGreetingTemplate();
2409 if ($copyPostalGreeting) {
2410 $copyPostalGreeting = $this->trimNonTokensFromAddressString($copyPostalGreeting,
2411 $this->greetingOptions[$type][$greetingID],
2412 $template
2413 );
2414 }
2415 return $copyPostalGreeting;
2416 }
2417
2418 }