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