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