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