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