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