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