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