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