Extract code for getting additional return properties, test
[civicrm-core.git] / CRM / Export / BAO / Export.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2018
32 */
33
34 /**
35 * This class contains the functions for Component export
36 *
37 */
38 class CRM_Export_BAO_Export {
39 // increase this number a lot to avoid making too many queries
40 // LIMIT is not much faster than a no LIMIT query
41 // CRM-7675
42 const EXPORT_ROW_COUNT = 100000;
43
44 protected static $relationshipReturnProperties = [];
45
46 /**
47 * Key representing the head of household in the relationship array.
48 *
49 * e.g. 8_a_b.
50 *
51 * @var string
52 */
53 protected static $headOfHouseholdRelationshipKey;
54
55 /**
56 * Key representing the head of household in the relationship array.
57 *
58 * e.g. 8_a_b.
59 *
60 * @var string
61 */
62 protected static $memberOfHouseholdRelationshipKey;
63
64 /**
65 * Key representing the head of household in the relationship array.
66 *
67 * e.g. ['8_b_a' => 'Household Member Is', '8_a_b = 'Household Member Of'.....]
68 *
69 * @var
70 */
71 protected static $relationshipTypes = [];
72
73 /**
74 * @param $value
75 * @param $locationTypeFields
76 * @param $relationshipTypes
77 *
78 * @return array
79 */
80 protected static function setRelationshipReturnProperties($value, $locationTypeFields, $relationshipTypes) {
81 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
82 $relPhoneTypeId = $relIMProviderId = NULL;
83 if (!empty($value[2])) {
84 $relationField = CRM_Utils_Array::value(2, $value);
85 if (trim(CRM_Utils_Array::value(3, $value))) {
86 $relLocTypeId = CRM_Utils_Array::value(3, $value);
87 }
88 else {
89 $relLocTypeId = 'Primary';
90 }
91
92 if ($relationField == 'phone') {
93 $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
94 }
95 elseif ($relationField == 'im') {
96 $relIMProviderId = CRM_Utils_Array::value(4, $value);
97 }
98 }
99 elseif (!empty($value[4])) {
100 $relationField = CRM_Utils_Array::value(4, $value);
101 $relLocTypeId = CRM_Utils_Array::value(5, $value);
102 if ($relationField == 'phone') {
103 $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
104 }
105 elseif ($relationField == 'im') {
106 $relIMProviderId = CRM_Utils_Array::value(6, $value);
107 }
108 }
109 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
110 if ($relPhoneTypeId) {
111 self::$relationshipReturnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
112 }
113 elseif ($relIMProviderId) {
114 self::$relationshipReturnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
115 }
116 else {
117 self::$relationshipReturnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
118 }
119 }
120 else {
121 self::$relationshipReturnProperties[$relationshipTypes][$relationField] = 1;
122 }
123 return array($relationField);
124 }
125
126 /**
127 * @return array
128 */
129 public static function getRelationshipReturnProperties() {
130 return self::relationshipReturnProperties;
131 }
132
133 /**
134 * Get default return property for export based on mode
135 *
136 * @param int $exportMode
137 * Export mode.
138 *
139 * @return string $property
140 * Default Return property
141 */
142 public static function defaultReturnProperty($exportMode) {
143 // hack to add default return property based on export mode
144 $property = NULL;
145 if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
146 $property = 'contribution_id';
147 }
148 elseif ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
149 $property = 'participant_id';
150 }
151 elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
152 $property = 'membership_id';
153 }
154 elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
155 $property = 'pledge_id';
156 }
157 elseif ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
158 $property = 'case_id';
159 }
160 elseif ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT) {
161 $property = 'grant_id';
162 }
163 elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
164 $property = 'activity_id';
165 }
166 return $property;
167 }
168
169 /**
170 * Get Export component
171 *
172 * @param int $exportMode
173 * Export mode.
174 *
175 * @return string $component
176 * CiviCRM Export Component
177 */
178 public static function exportComponent($exportMode) {
179 switch ($exportMode) {
180 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
181 $component = 'civicrm_contribution';
182 break;
183
184 case CRM_Export_Form_Select::EVENT_EXPORT:
185 $component = 'civicrm_participant';
186 break;
187
188 case CRM_Export_Form_Select::MEMBER_EXPORT:
189 $component = 'civicrm_membership';
190 break;
191
192 case CRM_Export_Form_Select::PLEDGE_EXPORT:
193 $component = 'civicrm_pledge';
194 break;
195
196 case CRM_Export_Form_Select::GRANT_EXPORT:
197 $component = 'civicrm_grant';
198 break;
199 }
200 return $component;
201 }
202
203 /**
204 * Get Query Group By Clause
205 * @param int $exportMode
206 * Export Mode
207 * @param string $queryMode
208 * Query Mode
209 * @param array $returnProperties
210 * Return Properties
211 * @param object $query
212 * CRM_Contact_BAO_Query
213 *
214 * @return string $groupBy
215 * Group By Clause
216 */
217 public static function getGroupBy($exportMode, $queryMode, $returnProperties, $query) {
218 $groupBy = '';
219 if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) ||
220 CRM_Utils_Array::value('notes', $returnProperties) ||
221 // CRM-9552
222 ($queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy)
223 ) {
224 $groupBy = "contact_a.id";
225 }
226
227 switch ($exportMode) {
228 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
229 $groupBy = 'civicrm_contribution.id';
230 if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
231 // especial group by when soft credit columns are included
232 $groupBy = array('contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id');
233 }
234 break;
235
236 case CRM_Export_Form_Select::EVENT_EXPORT:
237 $groupBy = 'civicrm_participant.id';
238 break;
239
240 case CRM_Export_Form_Select::MEMBER_EXPORT:
241 $groupBy = "civicrm_membership.id";
242 break;
243 }
244
245 if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
246 $groupBy = "civicrm_activity.id ";
247 }
248
249 if (!empty($groupBy)) {
250 if (!Civi::settings()->get('searchPrimaryDetailsOnly')) {
251 CRM_Core_DAO::disableFullGroupByMode();
252 }
253 $groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($query->_select, $groupBy);
254 }
255
256 return $groupBy;
257 }
258
259 /**
260 * Define extra properties for the export based on query mode
261 *
262 * @param string $queryMode
263 * Query Mode
264 * @return array $extraProperties
265 * Extra Properties
266 */
267 public static function defineExtraProperties($queryMode) {
268 switch ($queryMode) {
269 case CRM_Contact_BAO_Query::MODE_EVENT:
270 $paymentFields = TRUE;
271 $paymentTableId = 'participant_id';
272 break;
273
274 case CRM_Contact_BAO_Query::MODE_MEMBER:
275 $paymentFields = TRUE;
276 $paymentTableId = 'membership_id';
277 break;
278
279 case CRM_Contact_BAO_Query::MODE_PLEDGE:
280 $paymentFields = TRUE;
281 $paymentTableId = 'pledge_payment_id';
282 break;
283
284 case CRM_Contact_BAO_Query::MODE_CASE:
285 $paymentFields = FALSE;
286 $paymentTableId = '';
287 break;
288
289 default:
290 $paymentFields = FALSE;
291 $paymentTableId = '';
292 }
293 $extraProperties = array(
294 'paymentFields' => $paymentFields,
295 'paymentTableId' => $paymentTableId,
296 );
297 return $extraProperties;
298 }
299
300 /**
301 * Get the list the export fields.
302 *
303 * @param int $selectAll
304 * User preference while export.
305 * @param array $ids
306 * Contact ids.
307 * @param array $params
308 * Associated array of fields.
309 * @param string $order
310 * Order by clause.
311 * @param array $fields
312 * Associated array of fields.
313 * @param array $moreReturnProperties
314 * Additional return fields.
315 * @param int $exportMode
316 * Export mode.
317 * @param string $componentClause
318 * Component clause.
319 * @param string $componentTable
320 * Component table.
321 * @param bool $mergeSameAddress
322 * Merge records if they have same address.
323 * @param bool $mergeSameHousehold
324 * Merge records if they belong to the same household.
325 *
326 * @param array $exportParams
327 * @param string $queryOperator
328 *
329 * @return array|null
330 * An array can be requested from within a unit test.
331 *
332 * @throws \CRM_Core_Exception
333 */
334 public static function exportComponents(
335 $selectAll,
336 $ids,
337 $params,
338 $order = NULL,
339 $fields = NULL,
340 $moreReturnProperties = NULL,
341 $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT,
342 $componentClause = NULL,
343 $componentTable = NULL,
344 $mergeSameAddress = FALSE,
345 $mergeSameHousehold = FALSE,
346 $exportParams = array(),
347 $queryOperator = 'AND'
348 ) {
349
350 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $queryOperator);
351 $returnProperties = array();
352 $paymentFields = $selectedPaymentFields = $paymentTableId = FALSE;
353
354 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
355 // Warning - this imProviders var is used in a somewhat fragile way - don't rename it
356 // without manually testing the export of IM provider still works.
357 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
358 self::$relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(
359 NULL,
360 NULL,
361 NULL,
362 NULL,
363 TRUE,
364 'name',
365 FALSE
366 );
367 //also merge Head of Household
368 self::$memberOfHouseholdRelationshipKey = CRM_Utils_Array::key('Household Member of', self::$relationshipTypes);
369 self::$headOfHouseholdRelationshipKey = CRM_Utils_Array::key('Head of Household for', self::$relationshipTypes);
370
371 $queryMode = $processor->getQueryMode();
372
373 if ($fields) {
374 //construct return properties
375 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
376 $locationTypeFields = array(
377 'street_address',
378 'supplemental_address_1',
379 'supplemental_address_2',
380 'supplemental_address_3',
381 'city',
382 'postal_code',
383 'postal_code_suffix',
384 'geo_code_1',
385 'geo_code_2',
386 'state_province',
387 'country',
388 'phone',
389 'email',
390 'im',
391 );
392
393 foreach ($fields as $key => $value) {
394 $fieldName = CRM_Utils_Array::value(1, $value);
395 if (!$fieldName) {
396 continue;
397 }
398
399 if (array_key_exists($fieldName, self::$relationshipTypes) && (!empty($value[2]) || !empty($value[4]))) {
400 self::setRelationshipReturnProperties($value, $locationTypeFields, $fieldName);
401 // @todo we can later not add this to this array but maintain a separate array.
402 $returnProperties = array_merge($returnProperties, self::$relationshipReturnProperties);
403 }
404 elseif (is_numeric(CRM_Utils_Array::value(2, $value))) {
405 $locTypeId = $value[2];
406 if ($fieldName == 'phone') {
407 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . CRM_Utils_Array::value(3, $value)] = 1;
408 }
409 elseif ($fieldName == 'im') {
410 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . CRM_Utils_Array::value(3, $value)] = 1;
411 }
412 else {
413 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
414 }
415 }
416 else {
417 //hack to fix component fields
418 //revert mix of event_id and title
419 if ($fieldName == 'event_id') {
420 $returnProperties['event_id'] = 1;
421 }
422 elseif (
423 $exportMode == CRM_Export_Form_Select::EVENT_EXPORT &&
424 array_key_exists($fieldName, self::componentPaymentFields())
425 ) {
426 $selectedPaymentFields = TRUE;
427 $paymentTableId = 'participant_id';
428 $returnProperties[$fieldName] = 1;
429 }
430 else {
431 $returnProperties[$fieldName] = 1;
432 }
433 }
434 }
435 $defaultExportMode = self::defaultReturnProperty($exportMode);
436 if ($defaultExportMode) {
437 $returnProperties[$defaultExportMode] = 1;
438 }
439 }
440 else {
441 $returnProperties = [];
442 $fields = CRM_Contact_BAO_Contact::exportableFields('All', TRUE, TRUE);
443 foreach ($fields as $key => $var) {
444 if ($key && (substr($key, 0, 6) != 'custom')) {
445 //for CRM=952
446 $returnProperties[$key] = 1;
447 }
448 }
449
450 $extraProperties = self::defineExtraProperties($queryMode);
451 $paymentFields = $extraProperties['paymentFields'];
452 $paymentTableId = $extraProperties['paymentTableId'];
453
454 $returnProperties = array_merge($returnProperties, $processor->getAdditionalReturnProperties());
455
456 if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
457 // unset non exportable fields for components
458 $nonExpoFields = array(
459 'groups',
460 'tags',
461 'notes',
462 'contribution_status_id',
463 'pledge_status_id',
464 'pledge_payment_status_id',
465 );
466 foreach ($nonExpoFields as $value) {
467 unset($returnProperties[$value]);
468 }
469 }
470 }
471
472 if ($mergeSameAddress) {
473 //make sure the addressee fields are selected
474 //while using merge same address feature
475 $returnProperties['addressee'] = 1;
476 $returnProperties['postal_greeting'] = 1;
477 $returnProperties['email_greeting'] = 1;
478 $returnProperties['street_name'] = 1;
479 $returnProperties['household_name'] = 1;
480 $returnProperties['street_address'] = 1;
481 $returnProperties['city'] = 1;
482 $returnProperties['state_province'] = 1;
483
484 // some columns are required for assistance incase they are not already present
485 $exportParams['merge_same_address']['temp_columns'] = array();
486 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
487 foreach ($tempColumns as $column) {
488 if (!array_key_exists($column, $returnProperties)) {
489 $returnProperties[$column] = 1;
490 $column = $column == 'id' ? 'civicrm_primary_id' : $column;
491 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
492 }
493 }
494 }
495
496 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
497 // If an Additional Group is selected, then all contacts in that group are
498 // added to the export set (filtering out duplicates).
499 $query = "
500 INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_contact gc WHERE gc.group_id = {$exportParams['additional_group']} ON DUPLICATE KEY UPDATE {$componentTable}.contact_id = gc.contact_id";
501 CRM_Core_DAO::executeQuery($query);
502 }
503
504 if ($moreReturnProperties) {
505 // fix for CRM-7066
506 if (!empty($moreReturnProperties['group'])) {
507 unset($moreReturnProperties['group']);
508 $moreReturnProperties['groups'] = 1;
509 }
510 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
511 }
512
513 $exportParams['postal_mailing_export']['temp_columns'] = array();
514 if ($exportParams['exportOption'] == 2 &&
515 isset($exportParams['postal_mailing_export']) &&
516 CRM_Utils_Array::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
517 ) {
518 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
519 foreach ($postalColumns as $column) {
520 if (!array_key_exists($column, $returnProperties)) {
521 $returnProperties[$column] = 1;
522 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
523 }
524 }
525 }
526
527 // rectify params to what proximity search expects if there is a value for prox_distance
528 // CRM-7021
529 if (!empty($params)) {
530 CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
531 }
532
533 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
534
535 if ($mergeSameHousehold == 1) {
536 if (empty($returnProperties['id'])) {
537 $returnProperties['id'] = 1;
538 }
539
540 foreach ($returnProperties as $key => $value) {
541 if (!array_key_exists($key, self::$relationshipTypes)) {
542 $returnProperties[self::$memberOfHouseholdRelationshipKey][$key] = $value;
543 $returnProperties[self::$headOfHouseholdRelationshipKey][$key] = $value;
544 }
545 }
546
547 unset($returnProperties[self::$memberOfHouseholdRelationshipKey]['location_type']);
548 unset($returnProperties[self::$memberOfHouseholdRelationshipKey]['im_provider']);
549 unset($returnProperties[self::$headOfHouseholdRelationshipKey]['location_type']);
550 unset($returnProperties[self::$headOfHouseholdRelationshipKey]['im_provider']);
551 }
552
553 list($relationQuery, $allRelContactArray) = self::buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $returnProperties, $queryMode);
554
555 // make sure the groups stuff is included only if specifically specified
556 // by the fields param (CRM-1969), else we limit the contacts outputted to only
557 // ones that are part of a group
558 if (!empty($returnProperties['groups'])) {
559 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
560 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
561 // total hack for export, CRM-3618
562 $from = str_replace($oldClause,
563 $newClause,
564 $from
565 );
566 }
567
568 if (!$selectAll && $componentTable) {
569 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
570 }
571 elseif ($componentClause) {
572 if (empty($where)) {
573 $where = "WHERE $componentClause";
574 }
575 else {
576 $where .= " AND $componentClause";
577 }
578 }
579
580 // CRM-13982 - check if is deleted
581 $excludeTrashed = TRUE;
582 foreach ($params as $value) {
583 if ($value[0] == 'contact_is_deleted') {
584 $excludeTrashed = FALSE;
585 }
586 }
587 $trashClause = $excludeTrashed ? "contact_a.is_deleted != 1" : "( 1 )";
588
589 if (empty($where)) {
590 $where = "WHERE $trashClause";
591 }
592 else {
593 $where .= " AND $trashClause";
594 }
595
596 $queryString = "$select $from $where $having";
597
598 $groupBy = self::getGroupBy($exportMode, $queryMode, $returnProperties, $query);
599
600 $queryString .= $groupBy;
601
602 if ($order) {
603 // always add contact_a.id to the ORDER clause
604 // so the order is deterministic
605 //CRM-15301
606 if (strpos('contact_a.id', $order) === FALSE) {
607 $order .= ", contact_a.id";
608 }
609
610 list($field, $dir) = explode(' ', $order, 2);
611 $field = trim($field);
612 if (!empty($returnProperties[$field])) {
613 //CRM-15301
614 $queryString .= " ORDER BY $order";
615 }
616 }
617
618 $addPaymentHeader = FALSE;
619
620 $paymentDetails = array();
621 if ($paymentFields || $selectedPaymentFields) {
622
623 // get payment related in for event and members
624 $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
625 //get all payment headers.
626 // If we haven't selected specific payment fields, load in all the
627 // payment headers.
628 if (!$selectedPaymentFields) {
629 $paymentHeaders = self::componentPaymentFields();
630 if (!empty($paymentDetails)) {
631 $addPaymentHeader = TRUE;
632 }
633 }
634 // If we have selected specific payment fields, leave the payment headers
635 // as an empty array; the headers for each selected field will be added
636 // elsewhere.
637 else {
638 $paymentHeaders = array();
639 }
640 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
641 }
642
643 $componentDetails = array();
644 $setHeader = TRUE;
645
646 $rowCount = self::EXPORT_ROW_COUNT;
647 $offset = 0;
648 // we write to temp table often to avoid using too much memory
649 $tempRowCount = 100;
650
651 $count = -1;
652
653 // for CRM-3157 purposes
654 $i18n = CRM_Core_I18n::singleton();
655
656 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self::getExportStructureArrays($returnProperties, $processor, $relationQuery, $selectedPaymentFields);
657
658 $limitReached = FALSE;
659 while (!$limitReached) {
660 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
661 $iterationDAO = CRM_Core_DAO::executeQuery($limitQuery);
662 // If this is less than our limit by the end of the iteration we do not need to run the query again to
663 // check if some remain.
664 $rowsThisIteration = 0;
665
666 while ($iterationDAO->fetch()) {
667 $count++;
668 $rowsThisIteration++;
669 $row = array();
670 $query->convertToPseudoNames($iterationDAO);
671
672 //first loop through output columns so that we return what is required, and in same order.
673 foreach ($outputColumns as $field => $value) {
674
675 // add im_provider to $dao object
676 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
677 $iterationDAO->im_provider = $iterationDAO->provider_id;
678 }
679
680 //build row values (data)
681 $fieldValue = NULL;
682 if (property_exists($iterationDAO, $field)) {
683 $fieldValue = $iterationDAO->$field;
684 // to get phone type from phone type id
685 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
686 $fieldValue = $phoneTypes[$fieldValue];
687 }
688 elseif ($field == 'provider_id' || $field == 'im_provider') {
689 $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
690 }
691 elseif (strstr($field, 'master_id')) {
692 $masterAddressId = NULL;
693 if (isset($iterationDAO->$field)) {
694 $masterAddressId = $iterationDAO->$field;
695 }
696 // get display name of contact that address is shared.
697 $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId);
698 }
699 }
700
701 if (array_key_exists($field, self::$relationshipTypes)) {
702 $relDAO = CRM_Utils_Array::value($iterationDAO->contact_id, $allRelContactArray[$field]);
703 $relationQuery[$field]->convertToPseudoNames($relDAO);
704 self::fetchRelationshipDetails($relDAO, $value, $field, $row);
705 }
706 else {
707 $row[$field] = self::getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $selectedPaymentFields, $paymentDetails, $paymentTableId);
708 }
709 }
710
711 // add payment headers if required
712 if ($addPaymentHeader && $paymentFields) {
713 // @todo rather than do this for every single row do it before the loop starts.
714 // where other header definitions take place.
715 $headerRows = array_merge($headerRows, $paymentHeaders);
716 foreach (array_keys($paymentHeaders) as $paymentHdr) {
717 self::sqlColumnDefn($processor, $sqlColumns, $paymentHdr);
718 }
719 }
720
721 if ($setHeader) {
722 $exportTempTable = self::createTempTable($sqlColumns);
723 }
724
725 //build header only once
726 $setHeader = FALSE;
727
728 // If specific payment fields have been selected for export, payment
729 // data will already be in $row. Otherwise, add payment related
730 // information, if appropriate.
731 if ($addPaymentHeader) {
732 if (!$selectedPaymentFields) {
733 if ($paymentFields) {
734 $paymentData = CRM_Utils_Array::value($row[$paymentTableId], $paymentDetails);
735 if (!is_array($paymentData) || empty($paymentData)) {
736 $paymentData = $nullContributionDetails;
737 }
738 $row = array_merge($row, $paymentData);
739 }
740 elseif (!empty($paymentDetails)) {
741 $row = array_merge($row, $nullContributionDetails);
742 }
743 }
744 }
745 //remove organization name for individuals if it is set for current employer
746 if (!empty($row['contact_type']) &&
747 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
748 ) {
749 $row['organization_name'] = '';
750 }
751
752 // add component info
753 // write the row to a file
754 $componentDetails[] = $row;
755
756 // output every $tempRowCount rows
757 if ($count % $tempRowCount == 0) {
758 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
759 $componentDetails = array();
760 }
761 }
762 if ($rowsThisIteration < self::EXPORT_ROW_COUNT) {
763 $limitReached = TRUE;
764 }
765 $offset += $rowCount;
766 }
767
768 if ($exportTempTable) {
769 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
770
771 // if postalMailing option is checked, exclude contacts who are deceased, have
772 // "Do not mail" privacy setting, or have no street address
773 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
774 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
775 ) {
776 self::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
777 }
778
779 // do merge same address and merge same household processing
780 if ($mergeSameAddress) {
781 self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
782 }
783
784 // merge the records if they have corresponding households
785 if ($mergeSameHousehold) {
786 self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, self::$memberOfHouseholdRelationshipKey);
787 self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, self::$headOfHouseholdRelationshipKey);
788 }
789
790 // call export hook
791 CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
792
793 // In order to be able to write a unit test against this function we need to suppress
794 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
795 if (empty($exportParams['suppress_csv_for_testing'])) {
796 self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
797 }
798 else {
799 // return tableName and sqlColumns in test context
800 return array($exportTempTable, $sqlColumns);
801 }
802
803 // delete the export temp table and component table
804 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
805 CRM_Core_DAO::executeQuery($sql);
806 CRM_Core_DAO::reenableFullGroupByMode();
807 CRM_Utils_System::civiExit();
808 }
809 else {
810 CRM_Core_DAO::reenableFullGroupByMode();
811 throw new CRM_Core_Exception(ts('No records to export'));
812 }
813 }
814
815 /**
816 * Name of the export file based on mode.
817 *
818 * @param string $output
819 * Type of output.
820 * @param int $mode
821 * Export mode.
822 *
823 * @return string
824 * name of the file
825 */
826 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select::CONTACT_EXPORT) {
827 switch ($mode) {
828 case CRM_Export_Form_Select::CONTACT_EXPORT:
829 return ts('CiviCRM Contact Search');
830
831 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
832 return ts('CiviCRM Contribution Search');
833
834 case CRM_Export_Form_Select::MEMBER_EXPORT:
835 return ts('CiviCRM Member Search');
836
837 case CRM_Export_Form_Select::EVENT_EXPORT:
838 return ts('CiviCRM Participant Search');
839
840 case CRM_Export_Form_Select::PLEDGE_EXPORT:
841 return ts('CiviCRM Pledge Search');
842
843 case CRM_Export_Form_Select::CASE_EXPORT:
844 return ts('CiviCRM Case Search');
845
846 case CRM_Export_Form_Select::GRANT_EXPORT:
847 return ts('CiviCRM Grant Search');
848
849 case CRM_Export_Form_Select::ACTIVITY_EXPORT:
850 return ts('CiviCRM Activity Search');
851 }
852 }
853
854 /**
855 * Handle import error file creation.
856 */
857 public static function invoke() {
858 $type = CRM_Utils_Request::retrieve('type', 'Positive');
859 $parserName = CRM_Utils_Request::retrieve('parser', 'String');
860 if (empty($parserName) || empty($type)) {
861 return;
862 }
863
864 // clean and ensure parserName is a valid string
865 $parserName = CRM_Utils_String::munge($parserName);
866 $parserClass = explode('_', $parserName);
867
868 // make sure parserClass is in the CRM namespace and
869 // at least 3 levels deep
870 if ($parserClass[0] == 'CRM' &&
871 count($parserClass) >= 3
872 ) {
873 require_once str_replace('_', DIRECTORY_SEPARATOR, $parserName) . ".php";
874 // ensure the functions exists
875 if (method_exists($parserName, 'errorFileName') &&
876 method_exists($parserName, 'saveFileName')
877 ) {
878 $errorFileName = $parserName::errorFileName($type);
879 $saveFileName = $parserName::saveFileName($type);
880 if (!empty($errorFileName) && !empty($saveFileName)) {
881 CRM_Utils_System::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
882 CRM_Utils_System::setHttpHeader('Content-Description', 'File Transfer');
883 CRM_Utils_System::setHttpHeader('Content-Type', 'text/csv');
884 CRM_Utils_System::setHttpHeader('Content-Length', filesize($errorFileName));
885 CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
886
887 readfile($errorFileName);
888 }
889 }
890 }
891 CRM_Utils_System::civiExit();
892 }
893
894 /**
895 * @param $customSearchClass
896 * @param $formValues
897 * @param $order
898 */
899 public static function exportCustom($customSearchClass, $formValues, $order) {
900 $ext = CRM_Extension_System::singleton()->getMapper();
901 if (!$ext->isExtensionClass($customSearchClass)) {
902 require_once str_replace('_', DIRECTORY_SEPARATOR, $customSearchClass) . '.php';
903 }
904 else {
905 require_once $ext->classToPath($customSearchClass);
906 }
907 $search = new $customSearchClass($formValues);
908
909 $includeContactIDs = FALSE;
910 if ($formValues['radio_ts'] == 'ts_sel') {
911 $includeContactIDs = TRUE;
912 }
913
914 $sql = $search->all(0, 0, $order, $includeContactIDs);
915
916 $columns = $search->columns();
917
918 $header = array_keys($columns);
919 $fields = array_values($columns);
920
921 $rows = array();
922 $dao = CRM_Core_DAO::executeQuery($sql);
923 $alterRow = FALSE;
924 if (method_exists($search, 'alterRow')) {
925 $alterRow = TRUE;
926 }
927 while ($dao->fetch()) {
928 $row = array();
929
930 foreach ($fields as $field) {
931 $unqualified_field = CRM_Utils_Array::First(array_slice(explode('.', $field), -1));
932 $row[$field] = $dao->$unqualified_field;
933 }
934 if ($alterRow) {
935 $search->alterRow($row);
936 }
937 $rows[] = $row;
938 }
939
940 CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName(), $header, $rows);
941 CRM_Utils_System::civiExit();
942 }
943
944 /**
945 * @param \CRM_Export_BAO_ExportProcessor $processor
946 * @param $sqlColumns
947 * @param $field
948 */
949 public static function sqlColumnDefn($processor, &$sqlColumns, $field) {
950 if (substr($field, -4) == '_a_b' || substr($field, -4) == '_b_a') {
951 return;
952 }
953 $queryFields = $processor->getQueryFields();
954
955 $fieldName = CRM_Utils_String::munge(strtolower($field), '_', 64);
956 if ($fieldName == 'id') {
957 $fieldName = 'civicrm_primary_id';
958 }
959
960 // early exit for master_id, CRM-12100
961 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
962 // also for current_employer, CRM-16939
963 if ($fieldName == 'master_id' || $fieldName == 'current_employer') {
964 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
965 return;
966 }
967
968 if (substr($fieldName, -11) == 'campaign_id') {
969 // CRM-14398
970 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
971 return;
972 }
973
974 $lookUp = array('prefix_id', 'suffix_id');
975 // set the sql columns
976 if (isset($queryFields[$field]['type'])) {
977 switch ($queryFields[$field]['type']) {
978 case CRM_Utils_Type::T_INT:
979 case CRM_Utils_Type::T_BOOLEAN:
980 if (in_array($field, $lookUp)) {
981 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
982 }
983 else {
984 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
985 }
986 break;
987
988 case CRM_Utils_Type::T_STRING:
989 if (isset($queryFields[$field]['maxlength'])) {
990 $sqlColumns[$fieldName] = "$fieldName varchar({$queryFields[$field]['maxlength']})";
991 }
992 else {
993 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
994 }
995 break;
996
997 case CRM_Utils_Type::T_TEXT:
998 case CRM_Utils_Type::T_LONGTEXT:
999 case CRM_Utils_Type::T_BLOB:
1000 case CRM_Utils_Type::T_MEDIUMBLOB:
1001 $sqlColumns[$fieldName] = "$fieldName longtext";
1002 break;
1003
1004 case CRM_Utils_Type::T_FLOAT:
1005 case CRM_Utils_Type::T_ENUM:
1006 case CRM_Utils_Type::T_DATE:
1007 case CRM_Utils_Type::T_TIME:
1008 case CRM_Utils_Type::T_TIMESTAMP:
1009 case CRM_Utils_Type::T_MONEY:
1010 case CRM_Utils_Type::T_EMAIL:
1011 case CRM_Utils_Type::T_URL:
1012 case CRM_Utils_Type::T_CCNUM:
1013 default:
1014 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1015 break;
1016 }
1017 }
1018 else {
1019 if (substr($fieldName, -3, 3) == '_id') {
1020 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1021 }
1022 elseif (substr($fieldName, -5, 5) == '_note') {
1023 $sqlColumns[$fieldName] = "$fieldName text";
1024 }
1025 else {
1026 $changeFields = array(
1027 'groups',
1028 'tags',
1029 'notes',
1030 );
1031
1032 if (in_array($fieldName, $changeFields)) {
1033 $sqlColumns[$fieldName] = "$fieldName text";
1034 }
1035 else {
1036 // set the sql columns for custom data
1037 if (isset($queryFields[$field]['data_type'])) {
1038
1039 switch ($queryFields[$field]['data_type']) {
1040 case 'String':
1041 // May be option labels, which could be up to 512 characters
1042 $length = max(512, CRM_Utils_Array::value('text_length', $queryFields[$field]));
1043 $sqlColumns[$fieldName] = "$fieldName varchar($length)";
1044 break;
1045
1046 case 'Country':
1047 case 'StateProvince':
1048 case 'Link':
1049 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1050 break;
1051
1052 case 'Memo':
1053 $sqlColumns[$fieldName] = "$fieldName text";
1054 break;
1055
1056 default:
1057 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1058 break;
1059 }
1060 }
1061 else {
1062 $sqlColumns[$fieldName] = "$fieldName text";
1063 }
1064 }
1065 }
1066 }
1067 }
1068
1069 /**
1070 * @param string $tableName
1071 * @param $details
1072 * @param $sqlColumns
1073 */
1074 public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1075 if (empty($details)) {
1076 return;
1077 }
1078
1079 $sql = "
1080 SELECT max(id)
1081 FROM $tableName
1082 ";
1083
1084 $id = CRM_Core_DAO::singleValueQuery($sql);
1085 if (!$id) {
1086 $id = 0;
1087 }
1088
1089 $sqlClause = array();
1090
1091 foreach ($details as $dontCare => $row) {
1092 $id++;
1093 $valueString = array($id);
1094 foreach ($row as $dontCare => $value) {
1095 if (empty($value)) {
1096 $valueString[] = "''";
1097 }
1098 else {
1099 $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'";
1100 }
1101 }
1102 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1103 }
1104
1105 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1106
1107 $sqlValueString = implode(",\n", $sqlClause);
1108
1109 $sql = "
1110 INSERT INTO $tableName $sqlColumnString
1111 VALUES $sqlValueString
1112 ";
1113 CRM_Core_DAO::executeQuery($sql);
1114 }
1115
1116 /**
1117 * @param $sqlColumns
1118 *
1119 * @return string
1120 */
1121 public static function createTempTable(&$sqlColumns) {
1122 //creating a temporary table for the search result that need be exported
1123 $exportTempTable = CRM_Utils_SQL_TempTable::build()->setDurable()->setCategory('export')->getName();
1124
1125 // also create the sql table
1126 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1127 CRM_Core_DAO::executeQuery($sql);
1128
1129 $sql = "
1130 CREATE TABLE {$exportTempTable} (
1131 id int unsigned NOT NULL AUTO_INCREMENT,
1132 ";
1133 $sql .= implode(",\n", array_values($sqlColumns));
1134
1135 $sql .= ",
1136 PRIMARY KEY ( id )
1137 ";
1138 // add indexes for street_address and household_name if present
1139 $addIndices = array(
1140 'street_address',
1141 'household_name',
1142 'civicrm_primary_id',
1143 );
1144
1145 foreach ($addIndices as $index) {
1146 if (isset($sqlColumns[$index])) {
1147 $sql .= ",
1148 INDEX index_{$index}( $index )
1149 ";
1150 }
1151 }
1152
1153 $sql .= "
1154 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1155 ";
1156
1157 CRM_Core_DAO::executeQuery($sql);
1158 return $exportTempTable;
1159 }
1160
1161 /**
1162 * @param string $tableName
1163 * @param $headerRows
1164 * @param $sqlColumns
1165 * @param array $exportParams
1166 */
1167 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1168 // check if any records are present based on if they have used shared address feature,
1169 // and not based on if city / state .. matches.
1170 $sql = "
1171 SELECT r1.id as copy_id,
1172 r1.civicrm_primary_id as copy_contact_id,
1173 r1.addressee as copy_addressee,
1174 r1.addressee_id as copy_addressee_id,
1175 r1.postal_greeting as copy_postal_greeting,
1176 r1.postal_greeting_id as copy_postal_greeting_id,
1177 r2.id as master_id,
1178 r2.civicrm_primary_id as master_contact_id,
1179 r2.postal_greeting as master_postal_greeting,
1180 r2.postal_greeting_id as master_postal_greeting_id,
1181 r2.addressee as master_addressee,
1182 r2.addressee_id as master_addressee_id
1183 FROM $tableName r1
1184 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1185 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1186 ORDER BY r1.id";
1187 $linkedMerge = self::_buildMasterCopyArray($sql, $exportParams, TRUE);
1188
1189 // find all the records that have the same street address BUT not in a household
1190 // require match on city and state as well
1191 $sql = "
1192 SELECT r1.id as master_id,
1193 r1.civicrm_primary_id as master_contact_id,
1194 r1.postal_greeting as master_postal_greeting,
1195 r1.postal_greeting_id as master_postal_greeting_id,
1196 r1.addressee as master_addressee,
1197 r1.addressee_id as master_addressee_id,
1198 r2.id as copy_id,
1199 r2.civicrm_primary_id as copy_contact_id,
1200 r2.postal_greeting as copy_postal_greeting,
1201 r2.postal_greeting_id as copy_postal_greeting_id,
1202 r2.addressee as copy_addressee,
1203 r2.addressee_id as copy_addressee_id
1204 FROM $tableName r1
1205 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1206 r1.city = r2.city AND
1207 r1.state_province_id = r2.state_province_id )
1208 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1209 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1210 AND ( r1.street_address != '' )
1211 AND r2.id > r1.id
1212 ORDER BY r1.id
1213 ";
1214 $merge = self::_buildMasterCopyArray($sql, $exportParams);
1215
1216 // unset ids from $merge already present in $linkedMerge
1217 foreach ($linkedMerge as $masterID => $values) {
1218 $keys = array($masterID);
1219 $keys = array_merge($keys, array_keys($values['copy']));
1220 foreach ($merge as $mid => $vals) {
1221 if (in_array($mid, $keys)) {
1222 unset($merge[$mid]);
1223 }
1224 else {
1225 foreach ($values['copy'] as $copyId) {
1226 if (in_array($copyId, $keys)) {
1227 unset($merge[$mid]['copy'][$copyId]);
1228 }
1229 }
1230 }
1231 }
1232 }
1233 $merge = $merge + $linkedMerge;
1234
1235 foreach ($merge as $masterID => $values) {
1236 $sql = "
1237 UPDATE $tableName
1238 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1239 WHERE id = %4
1240 ";
1241 $params = array(
1242 1 => array($values['addressee'], 'String'),
1243 2 => array($values['postalGreeting'], 'String'),
1244 3 => array($values['emailGreeting'], 'String'),
1245 4 => array($masterID, 'Integer'),
1246 );
1247 CRM_Core_DAO::executeQuery($sql, $params);
1248
1249 // delete all copies
1250 $deleteIDs = array_keys($values['copy']);
1251 $deleteIDString = implode(',', $deleteIDs);
1252 $sql = "
1253 DELETE FROM $tableName
1254 WHERE id IN ( $deleteIDString )
1255 ";
1256 CRM_Core_DAO::executeQuery($sql);
1257 }
1258
1259 // unset temporary columns that were added for postal mailing format
1260 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1261 $unsetKeys = array_keys($sqlColumns);
1262 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1263 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1264 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1265 }
1266 }
1267 }
1268 }
1269
1270 /**
1271 * @param int $contactId
1272 * @param array $exportParams
1273 *
1274 * @return array
1275 */
1276 public static function _replaceMergeTokens($contactId, $exportParams) {
1277 $greetings = array();
1278 $contact = NULL;
1279
1280 $greetingFields = array(
1281 'postal_greeting',
1282 'addressee',
1283 );
1284 foreach ($greetingFields as $greeting) {
1285 if (!empty($exportParams[$greeting])) {
1286 $greetingLabel = $exportParams[$greeting];
1287 if (empty($contact)) {
1288 $values = array(
1289 'id' => $contactId,
1290 'version' => 3,
1291 );
1292 $contact = civicrm_api('contact', 'get', $values);
1293
1294 if (!empty($contact['is_error'])) {
1295 return $greetings;
1296 }
1297 $contact = $contact['values'][$contact['id']];
1298 }
1299
1300 $tokens = array('contact' => $greetingLabel);
1301 $greetings[$greeting] = CRM_Utils_Token::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1302 }
1303 }
1304 return $greetings;
1305 }
1306
1307 /**
1308 * The function unsets static part of the string, if token is the dynamic part.
1309 *
1310 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1311 * i.e 'Hello Alan' => converted to => 'Alan'
1312 *
1313 * @param string $parsedString
1314 * @param string $defaultGreeting
1315 * @param bool $addressMergeGreetings
1316 * @param string $greetingType
1317 *
1318 * @return mixed
1319 */
1320 public static function _trimNonTokens(
1321 &$parsedString, $defaultGreeting,
1322 $addressMergeGreetings, $greetingType = 'postal_greeting'
1323 ) {
1324 if (!empty($addressMergeGreetings[$greetingType])) {
1325 $greetingLabel = $addressMergeGreetings[$greetingType];
1326 }
1327 $greetingLabel = empty($greetingLabel) ? $defaultGreeting : $greetingLabel;
1328
1329 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1330 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1331 foreach ($stringsToBeReplaced as $key => $string) {
1332 // to keep one space
1333 $stringsToBeReplaced[$key] = ltrim($string);
1334 }
1335 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1336
1337 return $parsedString;
1338 }
1339
1340 /**
1341 * @param $sql
1342 * @param array $exportParams
1343 * @param bool $sharedAddress
1344 *
1345 * @return array
1346 */
1347 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1348 static $contactGreetingTokens = array();
1349
1350 $addresseeOptions = CRM_Core_OptionGroup::values('addressee');
1351 $postalOptions = CRM_Core_OptionGroup::values('postal_greeting');
1352
1353 $merge = $parents = array();
1354 $dao = CRM_Core_DAO::executeQuery($sql);
1355
1356 while ($dao->fetch()) {
1357 $masterID = $dao->master_id;
1358 $copyID = $dao->copy_id;
1359 $masterPostalGreeting = $dao->master_postal_greeting;
1360 $masterAddressee = $dao->master_addressee;
1361 $copyAddressee = $dao->copy_addressee;
1362
1363 if (!$sharedAddress) {
1364 if (!isset($contactGreetingTokens[$dao->master_contact_id])) {
1365 $contactGreetingTokens[$dao->master_contact_id] = self::_replaceMergeTokens($dao->master_contact_id, $exportParams);
1366 }
1367 $masterPostalGreeting = CRM_Utils_Array::value('postal_greeting',
1368 $contactGreetingTokens[$dao->master_contact_id], $dao->master_postal_greeting
1369 );
1370 $masterAddressee = CRM_Utils_Array::value('addressee',
1371 $contactGreetingTokens[$dao->master_contact_id], $dao->master_addressee
1372 );
1373
1374 if (!isset($contactGreetingTokens[$dao->copy_contact_id])) {
1375 $contactGreetingTokens[$dao->copy_contact_id] = self::_replaceMergeTokens($dao->copy_contact_id, $exportParams);
1376 }
1377 $copyPostalGreeting = CRM_Utils_Array::value('postal_greeting',
1378 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_postal_greeting
1379 );
1380 $copyAddressee = CRM_Utils_Array::value('addressee',
1381 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_addressee
1382 );
1383 }
1384
1385 if (!isset($merge[$masterID])) {
1386 // check if this is an intermediate child
1387 // this happens if there are 3 or more matches a,b, c
1388 // the above query will return a, b / a, c / b, c
1389 // we might be doing a bit more work, but for now its ok, unless someone
1390 // knows how to fix the query above
1391 if (isset($parents[$masterID])) {
1392 $masterID = $parents[$masterID];
1393 }
1394 else {
1395 $merge[$masterID] = array(
1396 'addressee' => $masterAddressee,
1397 'copy' => array(),
1398 'postalGreeting' => $masterPostalGreeting,
1399 );
1400 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1401 }
1402 }
1403 $parents[$copyID] = $masterID;
1404
1405 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1406
1407 if (!empty($exportParams['postal_greeting_other']) &&
1408 count($merge[$masterID]['copy']) >= 1
1409 ) {
1410 // use static greetings specified if no of contacts > 2
1411 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1412 }
1413 elseif ($copyPostalGreeting) {
1414 self::_trimNonTokens($copyPostalGreeting,
1415 $postalOptions[$dao->copy_postal_greeting_id],
1416 $exportParams
1417 );
1418 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1419 // if there happens to be a duplicate, remove it
1420 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1421 }
1422
1423 if (!empty($exportParams['addressee_other']) &&
1424 count($merge[$masterID]['copy']) >= 1
1425 ) {
1426 // use static greetings specified if no of contacts > 2
1427 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1428 }
1429 elseif ($copyAddressee) {
1430 self::_trimNonTokens($copyAddressee,
1431 $addresseeOptions[$dao->copy_addressee_id],
1432 $exportParams, 'addressee'
1433 );
1434 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1435 }
1436 }
1437 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1438 }
1439
1440 return $merge;
1441 }
1442
1443 /**
1444 * Merge household record into the individual record
1445 * if exists
1446 *
1447 * @param string $exportTempTable
1448 * Temporary temp table that stores the records.
1449 * @param array $headerRows
1450 * Array of headers for the export file.
1451 * @param array $sqlColumns
1452 * Array of names of the table columns of the temp table.
1453 * @param string $prefix
1454 * Name of the relationship type that is prefixed to the table columns.
1455 */
1456 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1457 $prefixColumn = $prefix . '_';
1458 $allKeys = array_keys($sqlColumns);
1459 $replaced = array();
1460 $headerRows = array_values($headerRows);
1461
1462 // name map of the non standard fields in header rows & sql columns
1463 $mappingFields = array(
1464 'civicrm_primary_id' => 'id',
1465 'contact_source' => 'source',
1466 'current_employer_id' => 'employer_id',
1467 'contact_is_deleted' => 'is_deleted',
1468 'name' => 'address_name',
1469 'provider_id' => 'im_service_provider',
1470 'phone_type_id' => 'phone_type',
1471 );
1472
1473 //figure out which columns are to be replaced by which ones
1474 foreach ($sqlColumns as $columnNames => $dontCare) {
1475 if ($rep = CRM_Utils_Array::value($columnNames, $mappingFields)) {
1476 $replaced[$columnNames] = CRM_Utils_String::munge($prefixColumn . $rep, '_', 64);
1477 }
1478 else {
1479 $householdColName = CRM_Utils_String::munge($prefixColumn . $columnNames, '_', 64);
1480
1481 if (!empty($sqlColumns[$householdColName])) {
1482 $replaced[$columnNames] = $householdColName;
1483 }
1484 }
1485 }
1486 $query = "UPDATE $exportTempTable SET ";
1487
1488 $clause = array();
1489 foreach ($replaced as $from => $to) {
1490 $clause[] = "$from = $to ";
1491 unset($sqlColumns[$to]);
1492 if ($key = CRM_Utils_Array::key($to, $allKeys)) {
1493 unset($headerRows[$key]);
1494 }
1495 }
1496 $query .= implode(",\n", $clause);
1497 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1498
1499 CRM_Core_DAO::executeQuery($query);
1500
1501 //drop the table columns that store redundant household info
1502 $dropQuery = "ALTER TABLE $exportTempTable ";
1503 foreach ($replaced as $householdColumns) {
1504 $dropClause[] = " DROP $householdColumns ";
1505 }
1506 $dropQuery .= implode(",\n", $dropClause);
1507
1508 CRM_Core_DAO::executeQuery($dropQuery);
1509
1510 // also drop the temp table if exists
1511 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1512 CRM_Core_DAO::executeQuery($sql);
1513
1514 // clean up duplicate records
1515 $query = "
1516 CREATE TABLE {$exportTempTable}_temp SELECT *
1517 FROM {$exportTempTable}
1518 GROUP BY civicrm_primary_id ";
1519
1520 CRM_Core_DAO::executeQuery($query);
1521
1522 $query = "DROP TABLE $exportTempTable";
1523 CRM_Core_DAO::executeQuery($query);
1524
1525 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1526 CRM_Core_DAO::executeQuery($query);
1527 }
1528
1529 /**
1530 * @param $exportTempTable
1531 * @param $headerRows
1532 * @param $sqlColumns
1533 * @param $exportMode
1534 * @param null $saveFile
1535 * @param string $batchItems
1536 */
1537 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1538 $writeHeader = TRUE;
1539 $offset = 0;
1540 $limit = self::EXPORT_ROW_COUNT;
1541
1542 $query = "SELECT * FROM $exportTempTable";
1543
1544 while (1) {
1545 $limitQuery = $query . "
1546 LIMIT $offset, $limit
1547 ";
1548 $dao = CRM_Core_DAO::executeQuery($limitQuery);
1549
1550 if ($dao->N <= 0) {
1551 break;
1552 }
1553
1554 $componentDetails = array();
1555 while ($dao->fetch()) {
1556 $row = array();
1557
1558 foreach ($sqlColumns as $column => $dontCare) {
1559 $row[$column] = $dao->$column;
1560 }
1561 $componentDetails[] = $row;
1562 }
1563 if ($exportMode == 'financial') {
1564 $getExportFileName = 'CiviCRM Contribution Search';
1565 }
1566 else {
1567 $getExportFileName = self::getExportFileName('csv', $exportMode);
1568 }
1569 $csvRows = CRM_Core_Report_Excel::writeCSVFile($getExportFileName,
1570 $headerRows,
1571 $componentDetails,
1572 NULL,
1573 $writeHeader,
1574 $saveFile);
1575
1576 if ($saveFile && !empty($csvRows)) {
1577 $batchItems .= $csvRows;
1578 }
1579
1580 $writeHeader = FALSE;
1581 $offset += $limit;
1582 }
1583 }
1584
1585 /**
1586 * Manipulate header rows for relationship fields.
1587 *
1588 * @param $headerRows
1589 */
1590 public static function manipulateHeaderRows(&$headerRows) {
1591 foreach ($headerRows as & $header) {
1592 $split = explode('-', $header);
1593 if ($relationTypeName = CRM_Utils_Array::value($split[0], self::$relationshipTypes)) {
1594 $split[0] = $relationTypeName;
1595 $header = implode('-', $split);
1596 }
1597 }
1598 }
1599
1600 /**
1601 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1602 * or have no street address
1603 * @param $exportTempTable
1604 * @param $headerRows
1605 * @param $sqlColumns
1606 * @param $exportParams
1607 */
1608 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1609 $whereClause = array();
1610
1611 if (array_key_exists('is_deceased', $sqlColumns)) {
1612 $whereClause[] = 'is_deceased = 1';
1613 }
1614
1615 if (array_key_exists('do_not_mail', $sqlColumns)) {
1616 $whereClause[] = 'do_not_mail = 1';
1617 }
1618
1619 if (array_key_exists('street_address', $sqlColumns)) {
1620 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1621
1622 // check for supplemental_address_1
1623 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1624 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1625 'address_options', TRUE, NULL, TRUE
1626 );
1627 if (!empty($addressOptions['supplemental_address_1'])) {
1628 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1629 // enclose it again, since we are doing an AND in between a set of ORs
1630 $addressWhereClause = "( $addressWhereClause )";
1631 }
1632 }
1633
1634 $whereClause[] = $addressWhereClause;
1635 }
1636
1637 if (!empty($whereClause)) {
1638 $whereClause = implode(' OR ', $whereClause);
1639 $query = "
1640 DELETE
1641 FROM $exportTempTable
1642 WHERE {$whereClause}";
1643 CRM_Core_DAO::singleValueQuery($query);
1644 }
1645
1646 // unset temporary columns that were added for postal mailing format
1647 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1648 $unsetKeys = array_keys($sqlColumns);
1649 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1650 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1651 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1652 }
1653 }
1654 }
1655 }
1656
1657 /**
1658 * Build componentPayment fields.
1659 */
1660 public static function componentPaymentFields() {
1661 static $componentPaymentFields;
1662 if (!isset($componentPaymentFields)) {
1663 $componentPaymentFields = array(
1664 'componentPaymentField_total_amount' => ts('Total Amount'),
1665 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1666 'componentPaymentField_received_date' => ts('Date Received'),
1667 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1668 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1669 );
1670 }
1671 return $componentPaymentFields;
1672 }
1673
1674 /**
1675 * Set the definition for the header rows and sql columns based on the field to output.
1676 *
1677 * @param string $field
1678 * @param array $headerRows
1679 * @param array $sqlColumns
1680 * Columns to go in the temp table.
1681 * @param \CRM_Export_BAO_ExportProcessor $processor
1682 * @param array|string $value
1683 * @param array $phoneTypes
1684 * @param array $imProviders
1685 * @param string $relationQuery
1686 * @param array $selectedPaymentFields
1687 * @return array
1688 */
1689 public static function setHeaderRows($field, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields) {
1690
1691 $queryFields = $processor->getQueryFields();
1692 // Split campaign into 2 fields for id and title
1693 if (substr($field, -14) == 'campaign_title') {
1694 $headerRows[] = ts('Campaign Title');
1695 }
1696 elseif (substr($field, -11) == 'campaign_id') {
1697 $headerRows[] = ts('Campaign ID');
1698 }
1699 elseif (isset($queryFields[$field]['title'])) {
1700 $headerRows[] = $queryFields[$field]['title'];
1701 }
1702 elseif ($field == 'phone_type_id') {
1703 $headerRows[] = ts('Phone Type');
1704 }
1705 elseif ($field == 'provider_id') {
1706 $headerRows[] = ts('IM Service Provider');
1707 }
1708 elseif (array_key_exists($field, self::$relationshipTypes)) {
1709 foreach ($value as $relationField => $relationValue) {
1710 // below block is same as primary block (duplicate)
1711 if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
1712 if ($relationQuery[$field]->_fields[$relationField]['name'] == 'name') {
1713 $headerName = $field . '-' . $relationField;
1714 }
1715 else {
1716 if ($relationField == 'current_employer') {
1717 $headerName = $field . '-' . 'current_employer';
1718 }
1719 else {
1720 $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['name'];
1721 }
1722 }
1723
1724 $headerRows[] = $headerName;
1725
1726 self::sqlColumnDefn($processor, $sqlColumns, $headerName);
1727 }
1728 elseif ($relationField == 'phone_type_id') {
1729 $headerName = $field . '-' . 'Phone Type';
1730 $headerRows[] = $headerName;
1731 self::sqlColumnDefn($processor, $sqlColumns, $headerName);
1732 }
1733 elseif ($relationField == 'provider_id') {
1734 $headerName = $field . '-' . 'Im Service Provider';
1735 $headerRows[] = $headerName;
1736 self::sqlColumnDefn($processor, $sqlColumns, $headerName);
1737 }
1738 elseif ($relationField == 'state_province_id') {
1739 $headerName = $field . '-' . 'state_province_id';
1740 $headerRows[] = $headerName;
1741 self::sqlColumnDefn($processor, $sqlColumns, $headerName);
1742 }
1743 elseif (is_array($relationValue) && $relationField == 'location') {
1744 // fix header for location type case
1745 foreach ($relationValue as $ltype => $val) {
1746 foreach (array_keys($val) as $fld) {
1747 $type = explode('-', $fld);
1748
1749 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title'];
1750
1751 if (!empty($type[1])) {
1752 if (CRM_Utils_Array::value(0, $type) == 'phone') {
1753 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
1754 }
1755 elseif (CRM_Utils_Array::value(0, $type) == 'im') {
1756 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
1757 }
1758 }
1759 $headerName = $field . '-' . $hdr;
1760 $headerRows[] = $headerName;
1761 self::sqlColumnDefn($processor, $sqlColumns, $headerName);
1762 }
1763 }
1764 }
1765 }
1766 self::manipulateHeaderRows($headerRows);
1767 }
1768 elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
1769 $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields());
1770 }
1771 else {
1772 $headerRows[] = $field;
1773 }
1774
1775 self::sqlColumnDefn($processor, $sqlColumns, $field);
1776
1777 return array($headerRows, $sqlColumns);
1778 }
1779
1780 /**
1781 * Get the various arrays that we use to structure our output.
1782 *
1783 * The extraction of these has been moved to a separate function for clarity and so that
1784 * tests can be added - in particular on the $outputHeaders array.
1785 *
1786 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1787 * as a step on the refactoring path rather than how it should be.
1788 *
1789 * @param array $returnProperties
1790 * @param \CRM_Export_BAO_ExportProcessor $processor
1791 * @param string $relationQuery
1792 * @param array $selectedPaymentFields
1793 * @return array
1794 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1795 * alias for the field generated by BAO_Query object.
1796 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1797 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1798 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1799 * I'm too embarassed to discuss here.
1800 * The keys need
1801 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1802 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1803 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1804 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1805 * - a) the function used is more efficient or
1806 * - b) this code is old & outdated. Submit your answers to circular bin or better
1807 * yet find a way to comment them for posterity.
1808 */
1809 public static function getExportStructureArrays($returnProperties, $processor, $relationQuery, $selectedPaymentFields) {
1810 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
1811 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
1812 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
1813
1814 $queryFields = $processor->getQueryFields();
1815 foreach ($returnProperties as $key => $value) {
1816 if ($key != 'location' || !is_array($value)) {
1817 $outputColumns[$key] = $value;
1818 list($headerRows, $sqlColumns) = self::setHeaderRows($key, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields);
1819 }
1820 else {
1821 foreach ($value as $locationType => $locationFields) {
1822 foreach (array_keys($locationFields) as $locationFieldName) {
1823 $type = explode('-', $locationFieldName);
1824
1825 $actualDBFieldName = $type[0];
1826 $outputFieldName = $locationType . '-' . $queryFields[$actualDBFieldName]['title'];
1827 $daoFieldName = CRM_Utils_String::munge($locationType) . '-' . $actualDBFieldName;
1828
1829 if (!empty($type[1])) {
1830 $daoFieldName .= "-" . $type[1];
1831 if ($actualDBFieldName == 'phone') {
1832 $outputFieldName .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
1833 }
1834 elseif ($actualDBFieldName == 'im') {
1835 $outputFieldName .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
1836 }
1837 }
1838 if ($type[0] == 'im_provider') {
1839 // Warning: shame inducing hack.
1840 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
1841 }
1842 self::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
1843 list($headerRows, $sqlColumns) = self::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields);
1844 if ($actualDBFieldName == 'country' || $actualDBFieldName == 'world_region') {
1845 $metadata[$daoFieldName] = array('context' => 'country');
1846 }
1847 if ($actualDBFieldName == 'state_province') {
1848 $metadata[$daoFieldName] = array('context' => 'province');
1849 }
1850 $outputColumns[$daoFieldName] = TRUE;
1851 }
1852 }
1853 }
1854 }
1855 return array($outputColumns, $headerRows, $sqlColumns, $metadata);
1856 }
1857
1858 /**
1859 * Get the values of linked household contact.
1860 *
1861 * @param CRM_Core_DAO $relDAO
1862 * @param array $value
1863 * @param string $field
1864 * @param array $row
1865 */
1866 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1867 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
1868 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
1869 $i18n = CRM_Core_I18n::singleton();
1870 foreach ($value as $relationField => $relationValue) {
1871 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1872 $fieldValue = $relDAO->$relationField;
1873 if ($relationField == 'phone_type_id') {
1874 $fieldValue = $phoneTypes[$relationValue];
1875 }
1876 elseif ($relationField == 'provider_id') {
1877 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
1878 }
1879 // CRM-13995
1880 elseif (is_object($relDAO) && in_array($relationField, array(
1881 'email_greeting',
1882 'postal_greeting',
1883 'addressee',
1884 ))
1885 ) {
1886 //special case for greeting replacement
1887 $fldValue = "{$relationField}_display";
1888 $fieldValue = $relDAO->$fldValue;
1889 }
1890 }
1891 elseif (is_object($relDAO) && $relationField == 'state_province') {
1892 $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
1893 }
1894 elseif (is_object($relDAO) && $relationField == 'country') {
1895 $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
1896 }
1897 else {
1898 $fieldValue = '';
1899 }
1900 $field = $field . '_';
1901 $relPrefix = $field . $relationField;
1902
1903 if (is_object($relDAO) && $relationField == 'id') {
1904 $row[$relPrefix] = $relDAO->contact_id;
1905 }
1906 elseif (is_array($relationValue) && $relationField == 'location') {
1907 foreach ($relationValue as $ltype => $val) {
1908 foreach (array_keys($val) as $fld) {
1909 $type = explode('-', $fld);
1910 $fldValue = "{$ltype}-" . $type[0];
1911 if (!empty($type[1])) {
1912 $fldValue .= "-" . $type[1];
1913 }
1914 // CRM-3157: localise country, region (both have ‘country’ context)
1915 // and state_province (‘province’ context)
1916 switch (TRUE) {
1917 case (!is_object($relDAO)):
1918 $row[$field . '_' . $fldValue] = '';
1919 break;
1920
1921 case in_array('country', $type):
1922 case in_array('world_region', $type):
1923 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1924 array('context' => 'country')
1925 );
1926 break;
1927
1928 case in_array('state_province', $type):
1929 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1930 array('context' => 'province')
1931 );
1932 break;
1933
1934 default:
1935 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1936 break;
1937 }
1938 }
1939 }
1940 }
1941 elseif (isset($fieldValue) && $fieldValue != '') {
1942 //check for custom data
1943 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
1944 $row[$relPrefix] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
1945 }
1946 else {
1947 //normal relationship fields
1948 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1949 switch ($relationField) {
1950 case 'country':
1951 case 'world_region':
1952 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1953 break;
1954
1955 case 'state_province':
1956 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1957 break;
1958
1959 default:
1960 $row[$relPrefix] = $fieldValue;
1961 break;
1962 }
1963 }
1964 }
1965 else {
1966 // if relation field is empty or null
1967 $row[$relPrefix] = '';
1968 }
1969 }
1970 }
1971
1972 /**
1973 * Get the ids that we want to get related contact details for.
1974 *
1975 * @param array $ids
1976 * @param int $exportMode
1977 *
1978 * @return array
1979 */
1980 protected static function getIDsForRelatedContact($ids, $exportMode) {
1981 if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
1982 return $ids;
1983 }
1984 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
1985 $relIDs = [];
1986 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1987 $dao = CRM_Core_DAO::executeQuery("
1988 SELECT contact_id FROM civicrm_activity_contact
1989 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1990 record_type_id = {$sourceID}
1991 ");
1992
1993 while ($dao->fetch()) {
1994 $relIDs[] = $dao->contact_id;
1995 }
1996 return $relIDs;
1997 }
1998 $component = self::exportComponent($exportMode);
1999
2000 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
2001 return CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
2002 }
2003 else {
2004 return CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
2005 }
2006 }
2007
2008 /**
2009 * @param $selectAll
2010 * @param $ids
2011 * @param $exportMode
2012 * @param $componentTable
2013 * @param $returnProperties
2014 * @param $queryMode
2015 * @return array
2016 */
2017 protected static function buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $returnProperties, $queryMode) {
2018 $allRelContactArray = $relationQuery = array();
2019
2020 foreach (self::$relationshipTypes as $rel => $dnt) {
2021 if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) {
2022 $allRelContactArray[$rel] = array();
2023 // build Query for each relationship
2024 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
2025 NULL, FALSE, FALSE, $queryMode
2026 );
2027 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
2028
2029 list($id, $direction) = explode('_', $rel, 2);
2030 // identify the relationship direction
2031 $contactA = 'contact_id_a';
2032 $contactB = 'contact_id_b';
2033 if ($direction == 'b_a') {
2034 $contactA = 'contact_id_b';
2035 $contactB = 'contact_id_a';
2036 }
2037 $relIDs = self::getIDsForRelatedContact($ids, $exportMode);
2038
2039 $relationshipJoin = $relationshipClause = '';
2040 if (!$selectAll && $componentTable) {
2041 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
2042 }
2043 elseif (!empty($relIDs)) {
2044 $relID = implode(',', $relIDs);
2045 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
2046 }
2047
2048 $relationFrom = " {$relationFrom}
2049 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
2050 {$relationshipJoin} ";
2051
2052 //check for active relationship status only
2053 $today = date('Ymd');
2054 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
2055 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
2056 $relationGroupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($relationQuery[$rel]->_select, "crel.{$contactA}");
2057 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
2058 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
2059
2060 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
2061 while ($allRelContactDAO->fetch()) {
2062 //FIX Me: Migrate this to table rather than array
2063 // build the array of all related contacts
2064 $allRelContactArray[$rel][$allRelContactDAO->refContact] = clone($allRelContactDAO);
2065 }
2066 $allRelContactDAO->free();
2067 }
2068 }
2069 return array($relationQuery, $allRelContactArray);
2070 }
2071
2072 /**
2073 * @param $field
2074 * @param $iterationDAO
2075 * @param $fieldValue
2076 * @param $i18n
2077 * @param $metadata
2078 * @param $selectedPaymentFields
2079 * @param $paymentDetails
2080 * @param string $paymentTableId
2081 * @return string
2082 */
2083 protected static function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $selectedPaymentFields, $paymentDetails, $paymentTableId) {
2084
2085 if ($field == 'id') {
2086 return $iterationDAO->contact_id;
2087 // special case for calculated field
2088 }
2089 elseif ($field == 'source_contact_id') {
2090 return $iterationDAO->contact_id;
2091 }
2092 elseif ($field == 'pledge_balance_amount') {
2093 return $iterationDAO->pledge_amount - $iterationDAO->pledge_total_paid;
2094 // special case for calculated field
2095 }
2096 elseif ($field == 'pledge_next_pay_amount') {
2097 return $iterationDAO->pledge_next_pay_amount + $iterationDAO->pledge_outstanding_amount;
2098 }
2099 elseif (isset($fieldValue) &&
2100 $fieldValue != ''
2101 ) {
2102 //check for custom data
2103 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
2104 return CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
2105 }
2106
2107 elseif (in_array($field, array(
2108 'email_greeting',
2109 'postal_greeting',
2110 'addressee',
2111 ))) {
2112 //special case for greeting replacement
2113 $fldValue = "{$field}_display";
2114 return $iterationDAO->$fldValue;
2115 }
2116 else {
2117 //normal fields with a touch of CRM-3157
2118 switch ($field) {
2119 case 'country':
2120 case 'world_region':
2121 return $i18n->crm_translate($fieldValue, array('context' => 'country'));
2122
2123 case 'state_province':
2124 return $i18n->crm_translate($fieldValue, array('context' => 'province'));
2125
2126 case 'gender':
2127 case 'preferred_communication_method':
2128 case 'preferred_mail_format':
2129 case 'communication_style':
2130 return $i18n->crm_translate($fieldValue);
2131
2132 default:
2133 if (isset($metadata[$field])) {
2134 // No I don't know why we do it this way & whether we could
2135 // make better use of pseudoConstants.
2136 if (!empty($metadata[$field]['context'])) {
2137 return $i18n->crm_translate($fieldValue, $metadata[$field]);
2138 }
2139 if (!empty($metadata[$field]['pseudoconstant'])) {
2140 // This is not our normal syntax for pseudoconstants but I am a bit loath to
2141 // call an external function until sure it is not increasing php processing given this
2142 // may be iterated 100,000 times & we already have the $imProvider var loaded.
2143 // That can be next refactor...
2144 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
2145 // but I have to reach a stable point....
2146 $varName = $metadata[$field]['pseudoconstant']['var'];
2147 if ($varName === 'imProviders') {
2148 return CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
2149 }
2150 if ($varName === 'phoneTypes') {
2151 return CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_Phone', 'phone_type_id', $fieldValue);
2152 }
2153 }
2154
2155 }
2156 return $fieldValue;
2157 }
2158 }
2159 }
2160 elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
2161 $paymentData = CRM_Utils_Array::value($iterationDAO->$paymentTableId, $paymentDetails);
2162 $payFieldMapper = array(
2163 'componentPaymentField_total_amount' => 'total_amount',
2164 'componentPaymentField_contribution_status' => 'contribution_status',
2165 'componentPaymentField_payment_instrument' => 'pay_instru',
2166 'componentPaymentField_transaction_id' => 'trxn_id',
2167 'componentPaymentField_received_date' => 'receive_date',
2168 );
2169 return CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, '');
2170 }
2171 else {
2172 // if field is empty or null
2173 return '';
2174 }
2175 }
2176
2177 }