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