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