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