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