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