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