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