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