Extract field wrangling to determineReturnProperties
[civicrm-core.git] / CRM / Export / BAO / Export.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
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 * Get Export component
46 *
47 * @param int $exportMode
48 * Export mode.
49 *
50 * @return string
51 * CiviCRM Export Component
52 */
53 public static function exportComponent($exportMode) {
54 switch ($exportMode) {
55 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
56 $component = 'civicrm_contribution';
57 break;
58
59 case CRM_Export_Form_Select::EVENT_EXPORT:
60 $component = 'civicrm_participant';
61 break;
62
63 case CRM_Export_Form_Select::MEMBER_EXPORT:
64 $component = 'civicrm_membership';
65 break;
66
67 case CRM_Export_Form_Select::PLEDGE_EXPORT:
68 $component = 'civicrm_pledge';
69 break;
70
71 case CRM_Export_Form_Select::GRANT_EXPORT:
72 $component = 'civicrm_grant';
73 break;
74 }
75 return $component;
76 }
77
78 /**
79 * Get Query Group By Clause
80 * @param \CRM_Export_BAO_ExportProcessor $processor
81 * Export Mode
82 * @param array $returnProperties
83 * Return Properties
84 * @param object $query
85 * CRM_Contact_BAO_Query
86 *
87 * @return string
88 * Group By Clause
89 */
90 public static function getGroupBy($processor, $returnProperties, $query) {
91 $groupBy = NULL;
92 $exportMode = $processor->getExportMode();
93 $queryMode = $processor->getQueryMode();
94 if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) ||
95 CRM_Utils_Array::value('notes', $returnProperties) ||
96 // CRM-9552
97 ($queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy)
98 ) {
99 $groupBy = "contact_a.id";
100 }
101
102 switch ($exportMode) {
103 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
104 $groupBy = 'civicrm_contribution.id';
105 if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
106 // especial group by when soft credit columns are included
107 $groupBy = ['contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id'];
108 }
109 break;
110
111 case CRM_Export_Form_Select::EVENT_EXPORT:
112 $groupBy = 'civicrm_participant.id';
113 break;
114
115 case CRM_Export_Form_Select::MEMBER_EXPORT:
116 $groupBy = "civicrm_membership.id";
117 break;
118 }
119
120 if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
121 $groupBy = "civicrm_activity.id ";
122 }
123
124 return $groupBy ? ' GROUP BY ' . implode(', ', (array) $groupBy) : '';
125 }
126
127 /**
128 * Get the list the export fields.
129 *
130 * @param int $selectAll
131 * User preference while export.
132 * @param array $ids
133 * Contact ids.
134 * @param array $params
135 * Associated array of fields.
136 * @param string $order
137 * Order by clause.
138 * @param array $fields
139 * Associated array of fields.
140 * @param array $moreReturnProperties
141 * Additional return fields.
142 * @param int $exportMode
143 * Export mode.
144 * @param string $componentClause
145 * Component clause.
146 * @param string $componentTable
147 * Component table.
148 * @param bool $mergeSameAddress
149 * Merge records if they have same address.
150 * @param bool $mergeSameHousehold
151 * Merge records if they belong to the same household.
152 *
153 * @param array $exportParams
154 * @param string $queryOperator
155 *
156 * @return array|null
157 * An array can be requested from within a unit test.
158 *
159 * @throws \CRM_Core_Exception
160 */
161 public static function exportComponents(
162 $selectAll,
163 $ids,
164 $params,
165 $order = NULL,
166 $fields = NULL,
167 $moreReturnProperties = NULL,
168 $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT,
169 $componentClause = NULL,
170 $componentTable = NULL,
171 $mergeSameAddress = FALSE,
172 $mergeSameHousehold = FALSE,
173 $exportParams = [],
174 $queryOperator = 'AND'
175 ) {
176
177 $isPostalOnly = (
178 isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
179 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
180 );
181
182 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold, $isPostalOnly);
183 $returnProperties = $processor->getReturnProperties();
184 $paymentTableId = $processor->getPaymentTableID();
185
186 if ($mergeSameAddress) {
187 //make sure the addressee fields are selected
188 //while using merge same address feature
189 $returnProperties['addressee'] = 1;
190 $returnProperties['postal_greeting'] = 1;
191 $returnProperties['email_greeting'] = 1;
192 $returnProperties['street_name'] = 1;
193 $returnProperties['household_name'] = 1;
194 $returnProperties['street_address'] = 1;
195 $returnProperties['city'] = 1;
196 $returnProperties['state_province'] = 1;
197
198 // some columns are required for assistance incase they are not already present
199 $exportParams['merge_same_address']['temp_columns'] = [];
200 $tempColumns = ['id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id'];
201 foreach ($tempColumns as $column) {
202 if (!array_key_exists($column, $returnProperties)) {
203 $returnProperties[$column] = 1;
204 $column = $column == 'id' ? 'civicrm_primary_id' : $column;
205 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
206 }
207 }
208 }
209
210 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
211 // If an Additional Group is selected, then all contacts in that group are
212 // added to the export set (filtering out duplicates).
213 $query = "
214 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";
215 CRM_Core_DAO::executeQuery($query);
216 }
217
218 if ($moreReturnProperties) {
219 // fix for CRM-7066
220 if (!empty($moreReturnProperties['group'])) {
221 unset($moreReturnProperties['group']);
222 $moreReturnProperties['groups'] = 1;
223 }
224 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
225 }
226
227 $exportParams['postal_mailing_export']['temp_columns'] = [];
228 if ($exportParams['exportOption'] == 2 &&
229 isset($exportParams['postal_mailing_export']) &&
230 CRM_Utils_Array::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
231 ) {
232 $postalColumns = ['is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1'];
233 foreach ($postalColumns as $column) {
234 if (!array_key_exists($column, $returnProperties)) {
235 $returnProperties[$column] = 1;
236 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
237 }
238 }
239 }
240
241 // rectify params to what proximity search expects if there is a value for prox_distance
242 // CRM-7021
243 if (!empty($params)) {
244 CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
245 }
246
247 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
248
249 if ($mergeSameHousehold == 1) {
250 if (empty($returnProperties['id'])) {
251 $returnProperties['id'] = 1;
252 }
253
254 $processor->setHouseholdMergeReturnProperties(array_diff_key($returnProperties, array_fill_keys(['location_type', 'im_provider'], 1)));
255 }
256
257 // This perhaps only needs calling when $mergeSameHousehold == 1
258 self::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
259
260 // make sure the groups stuff is included only if specifically specified
261 // by the fields param (CRM-1969), else we limit the contacts outputted to only
262 // ones that are part of a group
263 if (!empty($returnProperties['groups'])) {
264 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
265 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
266 // total hack for export, CRM-3618
267 $from = str_replace($oldClause,
268 $newClause,
269 $from
270 );
271 }
272
273 $whereClauses = ['trash_clause' => "contact_a.is_deleted != 1"];
274 if (!$selectAll && $componentTable) {
275 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
276 }
277 elseif ($componentClause) {
278 $whereClauses[] = $componentClause;
279 }
280
281 // CRM-13982 - check if is deleted
282 foreach ($params as $value) {
283 if ($value[0] == 'contact_is_deleted') {
284 unset($whereClauses['trash_clause']);
285 }
286 }
287
288 if (empty($where)) {
289 $where = "WHERE " . implode(' AND ', $whereClauses);
290 }
291 else {
292 $where .= " AND " . implode(' AND ', $whereClauses);
293 }
294
295 $queryString = "$select $from $where $having";
296
297 $groupBy = self::getGroupBy($processor, $returnProperties, $query);
298
299 $queryString .= $groupBy;
300
301 if ($order) {
302 // always add contact_a.id to the ORDER clause
303 // so the order is deterministic
304 //CRM-15301
305 if (strpos('contact_a.id', $order) === FALSE) {
306 $order .= ", contact_a.id";
307 }
308
309 list($field, $dir) = explode(' ', $order, 2);
310 $field = trim($field);
311 if (!empty($returnProperties[$field])) {
312 //CRM-15301
313 $queryString .= " ORDER BY $order";
314 }
315 }
316
317 $addPaymentHeader = FALSE;
318
319 list($outputColumns, $metadata) = self::getExportStructureArrays($returnProperties, $processor);
320
321 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
322 // @todo - this is a temp fix - ideally later we don't set stuff only to unset it.
323 // test exists covering this...
324 foreach (array_keys($exportParams['merge_same_address']['temp_columns']) as $field) {
325 $processor->setColumnAsCalculationOnly($field);
326 }
327 }
328
329 $paymentDetails = [];
330 if ($processor->isExportPaymentFields()) {
331 // get payment related in for event and members
332 $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
333 //get all payment headers.
334 // If we haven't selected specific payment fields, load in all the
335 // payment headers.
336 if (!$processor->isExportSpecifiedPaymentFields()) {
337 if (!empty($paymentDetails)) {
338 $addPaymentHeader = TRUE;
339 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
340 $processor->addOutputSpecification($paymentField);
341 }
342 }
343 }
344 }
345
346 $componentDetails = [];
347
348 $rowCount = self::EXPORT_ROW_COUNT;
349 $offset = 0;
350 // we write to temp table often to avoid using too much memory
351 $tempRowCount = 100;
352
353 $count = -1;
354
355 $headerRows = $processor->getHeaderRows();
356 $sqlColumns = $processor->getSQLColumns();
357 $processor->setTemporaryTable(self::createTempTable($sqlColumns));
358 $limitReached = FALSE;
359
360 while (!$limitReached) {
361 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
362 CRM_Core_DAO::disableFullGroupByMode();
363 $iterationDAO = CRM_Core_DAO::executeQuery($limitQuery);
364 CRM_Core_DAO::reenableFullGroupByMode();
365 // If this is less than our limit by the end of the iteration we do not need to run the query again to
366 // check if some remain.
367 $rowsThisIteration = 0;
368
369 while ($iterationDAO->fetch()) {
370 $count++;
371 $rowsThisIteration++;
372 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader, $paymentTableId);
373 if ($row === FALSE) {
374 continue;
375 }
376
377 // add component info
378 // write the row to a file
379 $componentDetails[] = $row;
380
381 // output every $tempRowCount rows
382 if ($count % $tempRowCount == 0) {
383 self::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
384 $componentDetails = [];
385 }
386 }
387 if ($rowsThisIteration < self::EXPORT_ROW_COUNT) {
388 $limitReached = TRUE;
389 }
390 $offset += $rowCount;
391 }
392
393 if ($processor->getTemporaryTable()) {
394 self::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
395
396 // do merge same address and merge same household processing
397 if ($mergeSameAddress) {
398 self::mergeSameAddress($processor, $sqlColumns, $exportParams);
399 }
400
401 // call export hook
402 $table = $processor->getTemporaryTable();
403 CRM_Utils_Hook::export($table, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
404 if ($table !== $processor->getTemporaryTable()) {
405 CRM_Core_Error::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
406 $processor->setTemporaryTable($table);
407 }
408
409 // In order to be able to write a unit test against this function we need to suppress
410 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
411 if (empty($exportParams['suppress_csv_for_testing'])) {
412 self::writeCSVFromTable($headerRows, $sqlColumns, $processor);
413 }
414 else {
415 // return tableName sqlColumns headerRows in test context
416 return [$processor->getTemporaryTable(), $sqlColumns, $headerRows, $processor];
417 }
418
419 // delete the export temp table and component table
420 $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable();
421 CRM_Core_DAO::executeQuery($sql);
422 CRM_Core_DAO::reenableFullGroupByMode();
423 CRM_Utils_System::civiExit(0, ['processor' => $processor]);
424 }
425 else {
426 CRM_Core_DAO::reenableFullGroupByMode();
427 throw new CRM_Core_Exception(ts('No records to export'));
428 }
429 }
430
431 /**
432 * Handle import error file creation.
433 */
434 public static function invoke() {
435 $type = CRM_Utils_Request::retrieve('type', 'Positive');
436 $parserName = CRM_Utils_Request::retrieve('parser', 'String');
437 if (empty($parserName) || empty($type)) {
438 return;
439 }
440
441 // clean and ensure parserName is a valid string
442 $parserName = CRM_Utils_String::munge($parserName);
443 $parserClass = explode('_', $parserName);
444
445 // make sure parserClass is in the CRM namespace and
446 // at least 3 levels deep
447 if ($parserClass[0] == 'CRM' &&
448 count($parserClass) >= 3
449 ) {
450 require_once str_replace('_', DIRECTORY_SEPARATOR, $parserName) . ".php";
451 // ensure the functions exists
452 if (method_exists($parserName, 'errorFileName') &&
453 method_exists($parserName, 'saveFileName')
454 ) {
455 $errorFileName = $parserName::errorFileName($type);
456 $saveFileName = $parserName::saveFileName($type);
457 if (!empty($errorFileName) && !empty($saveFileName)) {
458 CRM_Utils_System::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
459 CRM_Utils_System::setHttpHeader('Content-Description', 'File Transfer');
460 CRM_Utils_System::setHttpHeader('Content-Type', 'text/csv');
461 CRM_Utils_System::setHttpHeader('Content-Length', filesize($errorFileName));
462 CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
463
464 readfile($errorFileName);
465 }
466 }
467 }
468 CRM_Utils_System::civiExit();
469 }
470
471 /**
472 * @param $customSearchClass
473 * @param $formValues
474 * @param $order
475 */
476 public static function exportCustom($customSearchClass, $formValues, $order) {
477 $ext = CRM_Extension_System::singleton()->getMapper();
478 if (!$ext->isExtensionClass($customSearchClass)) {
479 require_once str_replace('_', DIRECTORY_SEPARATOR, $customSearchClass) . '.php';
480 }
481 else {
482 require_once $ext->classToPath($customSearchClass);
483 }
484 $search = new $customSearchClass($formValues);
485
486 $includeContactIDs = FALSE;
487 if ($formValues['radio_ts'] == 'ts_sel') {
488 $includeContactIDs = TRUE;
489 }
490
491 $sql = $search->all(0, 0, $order, $includeContactIDs);
492
493 $columns = $search->columns();
494
495 $header = array_keys($columns);
496 $fields = array_values($columns);
497
498 $rows = [];
499 $dao = CRM_Core_DAO::executeQuery($sql);
500 $alterRow = FALSE;
501 if (method_exists($search, 'alterRow')) {
502 $alterRow = TRUE;
503 }
504 while ($dao->fetch()) {
505 $row = [];
506
507 foreach ($fields as $field) {
508 $unqualified_field = CRM_Utils_Array::First(array_slice(explode('.', $field), -1));
509 $row[$field] = $dao->$unqualified_field;
510 }
511 if ($alterRow) {
512 $search->alterRow($row);
513 }
514 $rows[] = $row;
515 }
516
517 CRM_Core_Report_Excel::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
518 CRM_Utils_System::civiExit();
519 }
520
521 /**
522 * @param \CRM_Export_BAO_ExportProcessor $processor
523 * @param $details
524 * @param $sqlColumns
525 */
526 public static function writeDetailsToTable($processor, $details, $sqlColumns) {
527 $tableName = $processor->getTemporaryTable();
528 if (empty($details)) {
529 return;
530 }
531
532 $sql = "
533 SELECT max(id)
534 FROM $tableName
535 ";
536
537 $id = CRM_Core_DAO::singleValueQuery($sql);
538 if (!$id) {
539 $id = 0;
540 }
541
542 $sqlClause = [];
543
544 foreach ($details as $row) {
545 $id++;
546 $valueString = [$id];
547 foreach ($row as $value) {
548 if (empty($value)) {
549 $valueString[] = "''";
550 }
551 else {
552 $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'";
553 }
554 }
555 $sqlClause[] = '(' . implode(',', $valueString) . ')';
556 }
557 $sqlColumns = array_merge(['id' => 1], $sqlColumns);
558 $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
559
560 $sqlValueString = implode(",\n", $sqlClause);
561
562 $sql = "
563 INSERT INTO $tableName $sqlColumnString
564 VALUES $sqlValueString
565 ";
566 CRM_Core_DAO::executeQuery($sql);
567 }
568
569 /**
570 * @param $sqlColumns
571 *
572 * @return string
573 */
574 public static function createTempTable($sqlColumns) {
575 //creating a temporary table for the search result that need be exported
576 $exportTempTable = CRM_Utils_SQL_TempTable::build()->setDurable()->setCategory('export');
577
578 // also create the sql table
579 $exportTempTable->drop();
580
581 $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
582 if (!empty($sqlColumns)) {
583 $sql .= implode(",\n", array_values($sqlColumns)) . ',';
584 }
585
586 $sql .= "\n PRIMARY KEY ( id )";
587
588 // add indexes for street_address and household_name if present
589 $addIndices = [
590 'street_address',
591 'household_name',
592 'civicrm_primary_id',
593 ];
594
595 foreach ($addIndices as $index) {
596 if (isset($sqlColumns[$index])) {
597 $sql .= ",
598 INDEX index_{$index}( $index )
599 ";
600 }
601 }
602
603 $exportTempTable->createWithColumns($sql);
604 return $exportTempTable->getName();
605 }
606
607 /**
608 * @param \CRM_Export_BAO_ExportProcessor $processor
609 * @param $sqlColumns
610 * @param array $exportParams
611 */
612 public static function mergeSameAddress($processor, &$sqlColumns, $exportParams) {
613 $tableName = $processor->getTemporaryTable();
614 // check if any records are present based on if they have used shared address feature,
615 // and not based on if city / state .. matches.
616 $sql = "
617 SELECT r1.id as copy_id,
618 r1.civicrm_primary_id as copy_contact_id,
619 r1.addressee as copy_addressee,
620 r1.addressee_id as copy_addressee_id,
621 r1.postal_greeting as copy_postal_greeting,
622 r1.postal_greeting_id as copy_postal_greeting_id,
623 r2.id as master_id,
624 r2.civicrm_primary_id as master_contact_id,
625 r2.postal_greeting as master_postal_greeting,
626 r2.postal_greeting_id as master_postal_greeting_id,
627 r2.addressee as master_addressee,
628 r2.addressee_id as master_addressee_id
629 FROM $tableName r1
630 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
631 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
632 ORDER BY r1.id";
633 $linkedMerge = self::_buildMasterCopyArray($sql, $exportParams, TRUE);
634
635 // find all the records that have the same street address BUT not in a household
636 // require match on city and state as well
637 $sql = "
638 SELECT r1.id as master_id,
639 r1.civicrm_primary_id as master_contact_id,
640 r1.postal_greeting as master_postal_greeting,
641 r1.postal_greeting_id as master_postal_greeting_id,
642 r1.addressee as master_addressee,
643 r1.addressee_id as master_addressee_id,
644 r2.id as copy_id,
645 r2.civicrm_primary_id as copy_contact_id,
646 r2.postal_greeting as copy_postal_greeting,
647 r2.postal_greeting_id as copy_postal_greeting_id,
648 r2.addressee as copy_addressee,
649 r2.addressee_id as copy_addressee_id
650 FROM $tableName r1
651 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
652 r1.city = r2.city AND
653 r1.state_province_id = r2.state_province_id )
654 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
655 AND ( r2.household_name IS NULL OR r2.household_name = '' )
656 AND ( r1.street_address != '' )
657 AND r2.id > r1.id
658 ORDER BY r1.id
659 ";
660 $merge = self::_buildMasterCopyArray($sql, $exportParams);
661
662 // unset ids from $merge already present in $linkedMerge
663 foreach ($linkedMerge as $masterID => $values) {
664 $keys = [$masterID];
665 $keys = array_merge($keys, array_keys($values['copy']));
666 foreach ($merge as $mid => $vals) {
667 if (in_array($mid, $keys)) {
668 unset($merge[$mid]);
669 }
670 else {
671 foreach ($values['copy'] as $copyId) {
672 if (in_array($copyId, $keys)) {
673 unset($merge[$mid]['copy'][$copyId]);
674 }
675 }
676 }
677 }
678 }
679 $merge = $merge + $linkedMerge;
680
681 foreach ($merge as $masterID => $values) {
682 $sql = "
683 UPDATE $tableName
684 SET addressee = %1, postal_greeting = %2, email_greeting = %3
685 WHERE id = %4
686 ";
687 $params = [
688 1 => [$values['addressee'], 'String'],
689 2 => [$values['postalGreeting'], 'String'],
690 3 => [$values['emailGreeting'], 'String'],
691 4 => [$masterID, 'Integer'],
692 ];
693 CRM_Core_DAO::executeQuery($sql, $params);
694
695 // delete all copies
696 $deleteIDs = array_keys($values['copy']);
697 $deleteIDString = implode(',', $deleteIDs);
698 $sql = "
699 DELETE FROM $tableName
700 WHERE id IN ( $deleteIDString )
701 ";
702 CRM_Core_DAO::executeQuery($sql);
703 }
704
705 // unset temporary columns that were added for postal mailing format
706 // @todo - this part is pretty close to ready to be removed....
707 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
708 $unsetKeys = array_keys($sqlColumns);
709 foreach ($unsetKeys as $headerKey => $sqlColKey) {
710 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
711 unset($sqlColumns[$sqlColKey]);
712 }
713 }
714 }
715 }
716
717 /**
718 * @param int $contactId
719 * @param array $exportParams
720 *
721 * @return array
722 */
723 public static function _replaceMergeTokens($contactId, $exportParams) {
724 $greetings = [];
725 $contact = NULL;
726
727 $greetingFields = [
728 'postal_greeting',
729 'addressee',
730 ];
731 foreach ($greetingFields as $greeting) {
732 if (!empty($exportParams[$greeting])) {
733 $greetingLabel = $exportParams[$greeting];
734 if (empty($contact)) {
735 $values = [
736 'id' => $contactId,
737 'version' => 3,
738 ];
739 $contact = civicrm_api('contact', 'get', $values);
740
741 if (!empty($contact['is_error'])) {
742 return $greetings;
743 }
744 $contact = $contact['values'][$contact['id']];
745 }
746
747 $tokens = ['contact' => $greetingLabel];
748 $greetings[$greeting] = CRM_Utils_Token::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
749 }
750 }
751 return $greetings;
752 }
753
754 /**
755 * The function unsets static part of the string, if token is the dynamic part.
756 *
757 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
758 * i.e 'Hello Alan' => converted to => 'Alan'
759 *
760 * @param string $parsedString
761 * @param string $defaultGreeting
762 * @param bool $addressMergeGreetings
763 * @param string $greetingType
764 *
765 * @return mixed
766 */
767 public static function _trimNonTokens(
768 &$parsedString, $defaultGreeting,
769 $addressMergeGreetings, $greetingType = 'postal_greeting'
770 ) {
771 if (!empty($addressMergeGreetings[$greetingType])) {
772 $greetingLabel = $addressMergeGreetings[$greetingType];
773 }
774 $greetingLabel = empty($greetingLabel) ? $defaultGreeting : $greetingLabel;
775
776 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
777 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
778 foreach ($stringsToBeReplaced as $key => $string) {
779 // to keep one space
780 $stringsToBeReplaced[$key] = ltrim($string);
781 }
782 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
783
784 return $parsedString;
785 }
786
787 /**
788 * @param $sql
789 * @param array $exportParams
790 * @param bool $sharedAddress
791 *
792 * @return array
793 */
794 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
795 static $contactGreetingTokens = [];
796
797 $addresseeOptions = CRM_Core_OptionGroup::values('addressee');
798 $postalOptions = CRM_Core_OptionGroup::values('postal_greeting');
799
800 $merge = $parents = [];
801 $dao = CRM_Core_DAO::executeQuery($sql);
802
803 while ($dao->fetch()) {
804 $masterID = $dao->master_id;
805 $copyID = $dao->copy_id;
806 $masterPostalGreeting = $dao->master_postal_greeting;
807 $masterAddressee = $dao->master_addressee;
808 $copyAddressee = $dao->copy_addressee;
809
810 if (!$sharedAddress) {
811 if (!isset($contactGreetingTokens[$dao->master_contact_id])) {
812 $contactGreetingTokens[$dao->master_contact_id] = self::_replaceMergeTokens($dao->master_contact_id, $exportParams);
813 }
814 $masterPostalGreeting = CRM_Utils_Array::value('postal_greeting',
815 $contactGreetingTokens[$dao->master_contact_id], $dao->master_postal_greeting
816 );
817 $masterAddressee = CRM_Utils_Array::value('addressee',
818 $contactGreetingTokens[$dao->master_contact_id], $dao->master_addressee
819 );
820
821 if (!isset($contactGreetingTokens[$dao->copy_contact_id])) {
822 $contactGreetingTokens[$dao->copy_contact_id] = self::_replaceMergeTokens($dao->copy_contact_id, $exportParams);
823 }
824 $copyPostalGreeting = CRM_Utils_Array::value('postal_greeting',
825 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_postal_greeting
826 );
827 $copyAddressee = CRM_Utils_Array::value('addressee',
828 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_addressee
829 );
830 }
831
832 if (!isset($merge[$masterID])) {
833 // check if this is an intermediate child
834 // this happens if there are 3 or more matches a,b, c
835 // the above query will return a, b / a, c / b, c
836 // we might be doing a bit more work, but for now its ok, unless someone
837 // knows how to fix the query above
838 if (isset($parents[$masterID])) {
839 $masterID = $parents[$masterID];
840 }
841 else {
842 $merge[$masterID] = [
843 'addressee' => $masterAddressee,
844 'copy' => [],
845 'postalGreeting' => $masterPostalGreeting,
846 ];
847 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
848 }
849 }
850 $parents[$copyID] = $masterID;
851
852 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
853
854 if (!empty($exportParams['postal_greeting_other']) &&
855 count($merge[$masterID]['copy']) >= 1
856 ) {
857 // use static greetings specified if no of contacts > 2
858 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
859 }
860 elseif ($copyPostalGreeting) {
861 self::_trimNonTokens($copyPostalGreeting,
862 $postalOptions[$dao->copy_postal_greeting_id],
863 $exportParams
864 );
865 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
866 // if there happens to be a duplicate, remove it
867 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
868 }
869
870 if (!empty($exportParams['addressee_other']) &&
871 count($merge[$masterID]['copy']) >= 1
872 ) {
873 // use static greetings specified if no of contacts > 2
874 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
875 }
876 elseif ($copyAddressee) {
877 self::_trimNonTokens($copyAddressee,
878 $addresseeOptions[$dao->copy_addressee_id],
879 $exportParams, 'addressee'
880 );
881 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
882 }
883 }
884 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
885 }
886
887 return $merge;
888 }
889
890 /**
891 * @param $headerRows
892 * @param $sqlColumns
893 * @param \CRM_Export_BAO_ExportProcessor $processor
894 */
895 public static function writeCSVFromTable($headerRows, $sqlColumns, $processor) {
896 $exportTempTable = $processor->getTemporaryTable();
897 $exportMode = $processor->getExportMode();
898 $writeHeader = TRUE;
899 $offset = 0;
900 $limit = self::EXPORT_ROW_COUNT;
901
902 $query = "SELECT * FROM $exportTempTable";
903
904 while (1) {
905 $limitQuery = $query . "
906 LIMIT $offset, $limit
907 ";
908 $dao = CRM_Core_DAO::executeQuery($limitQuery);
909
910 if ($dao->N <= 0) {
911 break;
912 }
913
914 $componentDetails = [];
915 while ($dao->fetch()) {
916 $row = [];
917
918 foreach ($sqlColumns as $column => $dontCare) {
919 $row[$column] = $dao->$column;
920 }
921 $componentDetails[] = $row;
922 }
923 CRM_Core_Report_Excel::writeCSVFile($processor->getExportFileName(),
924 $headerRows,
925 $componentDetails,
926 NULL,
927 $writeHeader
928 );
929
930 $writeHeader = FALSE;
931 $offset += $limit;
932 }
933 }
934
935 /**
936 * Build componentPayment fields.
937 *
938 * This is no longer used by export but BAO_Mapping still calls it & we
939 * should find a generic way to handle this or move this to that class.
940 *
941 * @deprecated
942 */
943 public static function componentPaymentFields() {
944 static $componentPaymentFields;
945 if (!isset($componentPaymentFields)) {
946 $componentPaymentFields = [
947 'componentPaymentField_total_amount' => ts('Total Amount'),
948 'componentPaymentField_contribution_status' => ts('Contribution Status'),
949 'componentPaymentField_received_date' => ts('Date Received'),
950 'componentPaymentField_payment_instrument' => ts('Payment Method'),
951 'componentPaymentField_transaction_id' => ts('Transaction ID'),
952 ];
953 }
954 return $componentPaymentFields;
955 }
956
957 /**
958 * Get the various arrays that we use to structure our output.
959 *
960 * The extraction of these has been moved to a separate function for clarity and so that
961 * tests can be added - in particular on the $outputHeaders array.
962 *
963 * However it still feels a bit like something that I'm too polite to write down and this should be seen
964 * as a step on the refactoring path rather than how it should be.
965 *
966 * @param array $returnProperties
967 * @param \CRM_Export_BAO_ExportProcessor $processor
968 *
969 * @return array
970 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
971 * alias for the field generated by BAO_Query object.
972 * - headerRows Array of the column header strings to put in the csv header - non-associative.
973 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
974 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
975 * I'm too embarassed to discuss here.
976 * The keys need
977 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
978 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
979 * in the main DAO loop is done once per row & that coule be 100,000 times.)
980 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
981 * - a) the function used is more efficient or
982 * - b) this code is old & outdated. Submit your answers to circular bin or better
983 * yet find a way to comment them for posterity.
984 */
985 public static function getExportStructureArrays($returnProperties, $processor) {
986 $outputColumns = $metadata = [];
987 $queryFields = $processor->getQueryFields();
988 foreach ($returnProperties as $key => $value) {
989 if (($key != 'location' || !is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
990 $outputColumns[$key] = $value;
991 $processor->addOutputSpecification($key);
992 }
993 elseif ($processor->isRelationshipTypeKey($key)) {
994 $outputColumns[$key] = $value;
995 foreach ($value as $relationField => $relationValue) {
996 // below block is same as primary block (duplicate)
997 if (isset($queryFields[$relationField]['title'])) {
998 $processor->addOutputSpecification($relationField, $key);
999 }
1000 elseif (is_array($relationValue) && $relationField == 'location') {
1001 // fix header for location type case
1002 foreach ($relationValue as $ltype => $val) {
1003 foreach (array_keys($val) as $fld) {
1004 $type = explode('-', $fld);
1005 $processor->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array::value(1, $type));
1006 }
1007 }
1008 }
1009 }
1010 }
1011 else {
1012 foreach ($value as $locationType => $locationFields) {
1013 foreach (array_keys($locationFields) as $locationFieldName) {
1014 $type = explode('-', $locationFieldName);
1015
1016 $actualDBFieldName = $type[0];
1017 $daoFieldName = CRM_Utils_String::munge($locationType) . '-' . $actualDBFieldName;
1018
1019 if (!empty($type[1])) {
1020 $daoFieldName .= "-" . $type[1];
1021 }
1022 $processor->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array::value(1, $type));
1023 $metadata[$daoFieldName] = $processor->getMetaDataForField($actualDBFieldName);
1024 $outputColumns[$daoFieldName] = TRUE;
1025 }
1026 }
1027 }
1028 }
1029 return [$outputColumns, $metadata];
1030 }
1031
1032 /**
1033 * Get the values of linked household contact.
1034 *
1035 * @param CRM_Core_DAO $relDAO
1036 * @param array $value
1037 * @param string $field
1038 * @param array $row
1039 */
1040 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1041 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
1042 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
1043 $i18n = CRM_Core_I18n::singleton();
1044 $field = $field . '_';
1045
1046 foreach ($value as $relationField => $relationValue) {
1047 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1048 $fieldValue = $relDAO->$relationField;
1049 if ($relationField == 'phone_type_id') {
1050 $fieldValue = $phoneTypes[$relationValue];
1051 }
1052 elseif ($relationField == 'provider_id') {
1053 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
1054 }
1055 // CRM-13995
1056 elseif (is_object($relDAO) && in_array($relationField, [
1057 'email_greeting',
1058 'postal_greeting',
1059 'addressee',
1060 ])) {
1061 //special case for greeting replacement
1062 $fldValue = "{$relationField}_display";
1063 $fieldValue = $relDAO->$fldValue;
1064 }
1065 }
1066 elseif (is_object($relDAO) && $relationField == 'state_province') {
1067 $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
1068 }
1069 elseif (is_object($relDAO) && $relationField == 'country') {
1070 $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
1071 }
1072 else {
1073 $fieldValue = '';
1074 }
1075 $relPrefix = $field . $relationField;
1076
1077 if (is_object($relDAO) && $relationField == 'id') {
1078 $row[$relPrefix] = $relDAO->contact_id;
1079 }
1080 elseif (is_array($relationValue) && $relationField == 'location') {
1081 foreach ($relationValue as $ltype => $val) {
1082 // If the location name has a space in it the we need to handle that. This
1083 // is kinda hacky but specifically covered in the ExportTest so later efforts to
1084 // improve it should be secure in the knowled it will be caught.
1085 $ltype = str_replace(' ', '_', $ltype);
1086 foreach (array_keys($val) as $fld) {
1087 $type = explode('-', $fld);
1088 $fldValue = "{$ltype}-" . $type[0];
1089 if (!empty($type[1])) {
1090 $fldValue .= "-" . $type[1];
1091 }
1092 // CRM-3157: localise country, region (both have ‘country’ context)
1093 // and state_province (‘province’ context)
1094 switch (TRUE) {
1095 case (!is_object($relDAO)):
1096 $row[$field . '_' . $fldValue] = '';
1097 break;
1098
1099 case in_array('country', $type):
1100 case in_array('world_region', $type):
1101 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1102 ['context' => 'country']
1103 );
1104 break;
1105
1106 case in_array('state_province', $type):
1107 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1108 ['context' => 'province']
1109 );
1110 break;
1111
1112 default:
1113 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1114 break;
1115 }
1116 }
1117 }
1118 }
1119 elseif (isset($fieldValue) && $fieldValue != '') {
1120 //check for custom data
1121 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
1122 $row[$relPrefix] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
1123 }
1124 else {
1125 //normal relationship fields
1126 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1127 switch ($relationField) {
1128 case 'country':
1129 case 'world_region':
1130 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
1131 break;
1132
1133 case 'state_province':
1134 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
1135 break;
1136
1137 default:
1138 $row[$relPrefix] = $fieldValue;
1139 break;
1140 }
1141 }
1142 }
1143 else {
1144 // if relation field is empty or null
1145 $row[$relPrefix] = '';
1146 }
1147 }
1148 }
1149
1150 /**
1151 * Get the ids that we want to get related contact details for.
1152 *
1153 * @param array $ids
1154 * @param int $exportMode
1155 *
1156 * @return array
1157 */
1158 protected static function getIDsForRelatedContact($ids, $exportMode) {
1159 if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
1160 return $ids;
1161 }
1162 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
1163 $relIDs = [];
1164 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1165 $dao = CRM_Core_DAO::executeQuery("
1166 SELECT contact_id FROM civicrm_activity_contact
1167 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1168 record_type_id = {$sourceID}
1169 ");
1170
1171 while ($dao->fetch()) {
1172 $relIDs[] = $dao->contact_id;
1173 }
1174 return $relIDs;
1175 }
1176 $component = self::exportComponent($exportMode);
1177
1178 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
1179 return CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
1180 }
1181 else {
1182 return CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
1183 }
1184 }
1185
1186 /**
1187 * @param $selectAll
1188 * @param $ids
1189 * @param \CRM_Export_BAO_ExportProcessor $processor
1190 * @param $componentTable
1191 */
1192 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
1193 $allRelContactArray = $relationQuery = [];
1194 $queryMode = $processor->getQueryMode();
1195 $exportMode = $processor->getExportMode();
1196
1197 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
1198 $allRelContactArray[$relationshipKey] = [];
1199 // build Query for each relationship
1200 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1201 NULL, FALSE, FALSE, $queryMode
1202 );
1203 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
1204
1205 list($id, $direction) = explode('_', $relationshipKey, 2);
1206 // identify the relationship direction
1207 $contactA = 'contact_id_a';
1208 $contactB = 'contact_id_b';
1209 if ($direction == 'b_a') {
1210 $contactA = 'contact_id_b';
1211 $contactB = 'contact_id_a';
1212 }
1213 $relIDs = self::getIDsForRelatedContact($ids, $exportMode);
1214
1215 $relationshipJoin = $relationshipClause = '';
1216 if (!$selectAll && $componentTable) {
1217 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1218 }
1219 elseif (!empty($relIDs)) {
1220 $relID = implode(',', $relIDs);
1221 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1222 }
1223
1224 $relationFrom = " {$relationFrom}
1225 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1226 {$relationshipJoin} ";
1227
1228 //check for active relationship status only
1229 $today = date('Ymd');
1230 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1231 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1232 CRM_Core_DAO::disableFullGroupByMode();
1233 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1234 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
1235
1236 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
1237 CRM_Core_DAO::reenableFullGroupByMode();
1238
1239 while ($allRelContactDAO->fetch()) {
1240 $relationQuery->convertToPseudoNames($allRelContactDAO);
1241 $row = [];
1242 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1243 self::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1244 foreach (array_keys($relationReturnProperties) as $property) {
1245 if ($property === 'location') {
1246 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1247 // $processor->setRelationshipValue from fetchRelationshipDetails
1248 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1249 foreach (array_keys($locationValues) as $locationValue) {
1250 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1251 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $key, $row[$relationshipKey . '__' . $key]);
1252 }
1253 }
1254 }
1255 else {
1256 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $property, $row[$relationshipKey . '_' . $property]);
1257 }
1258 }
1259 }
1260 }
1261 }
1262
1263 }