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