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