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