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