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