Merge pull request #15428 from greenpeace-cee/fix-status-check
[civicrm-core.git] / CRM / Export / BAO / Export.php
... / ...
CommitLineData
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28/**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34/**
35 * This class contains the functions for Component export
36 *
37 */
38class CRM_Export_BAO_Export {
39 // increase this number a lot to avoid making too many queries
40 // LIMIT is not much faster than a no LIMIT query
41 // CRM-7675
42 const EXPORT_ROW_COUNT = 100000;
43
44 /**
45 * Get the list the export fields.
46 *
47 * @param int $selectAll
48 * User preference while export.
49 * @param array $ids
50 * Contact ids.
51 * @param array $params
52 * Associated array of fields.
53 * @param string $order
54 * Order by clause.
55 * @param array $fields
56 * Associated array of fields.
57 * @param array $moreReturnProperties
58 * Additional return fields.
59 * @param int $exportMode
60 * Export mode.
61 * @param string $componentClause
62 * Component clause.
63 * @param string $componentTable
64 * Component table.
65 * @param bool $mergeSameAddress
66 * Merge records if they have same address.
67 * @param bool $mergeSameHousehold
68 * Merge records if they belong to the same household.
69 *
70 * @param array $exportParams
71 * @param string $queryOperator
72 *
73 * @throws \CRM_Core_Exception
74 */
75 public static function exportComponents(
76 $selectAll,
77 $ids,
78 $params,
79 $order = NULL,
80 $fields = NULL,
81 $moreReturnProperties = NULL,
82 $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT,
83 $componentClause = NULL,
84 $componentTable = NULL,
85 $mergeSameAddress = FALSE,
86 $mergeSameHousehold = FALSE,
87 $exportParams = [],
88 $queryOperator = 'AND'
89 ) {
90
91 $isPostalOnly = (
92 isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
93 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
94 );
95
96 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
97 // If an Additional Group is selected, then all contacts in that group are
98 // added to the export set (filtering out duplicates).
99 // Really - the calling function could do this ... just saying
100 // @todo take a whip to the calling function.
101 CRM_Core_DAO::executeQuery("
102INSERT 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"
103 );
104 }
105 // rectify params to what proximity search expects if there is a value for prox_distance
106 // CRM-7021
107 // @todo - move this back to the calling functions
108 if (!empty($params)) {
109 CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
110 }
111 // @todo everything from this line up should go back to the calling functions.
112 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold, $isPostalOnly, $mergeSameAddress, $exportParams);
113 if ($moreReturnProperties) {
114 $processor->setAdditionalRequestedReturnProperties($moreReturnProperties);
115 }
116 $processor->setComponentTable($componentTable);
117 $processor->setComponentClause($componentClause);
118 $processor->setIds($ids);
119
120 list($query, $queryString) = $processor->runQuery($params, $order);
121
122 // This perhaps only needs calling when $mergeSameHousehold == 1
123 self::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
124
125 $addPaymentHeader = FALSE;
126
127 list($outputColumns, $metadata) = $processor->getExportStructureArrays();
128
129 if ($processor->isMergeSameAddress()) {
130 foreach (array_keys($processor->getAdditionalFieldsForSameAddressMerge()) as $field) {
131 $processor->setColumnAsCalculationOnly($field);
132 }
133 }
134
135 $paymentDetails = [];
136 if ($processor->isExportPaymentFields()) {
137 // get payment related in for event and members
138 $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
139 //get all payment headers.
140 // If we haven't selected specific payment fields, load in all the
141 // payment headers.
142 if (!$processor->isExportSpecifiedPaymentFields()) {
143 if (!empty($paymentDetails)) {
144 $addPaymentHeader = TRUE;
145 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
146 $processor->addOutputSpecification($paymentField);
147 }
148 }
149 }
150 }
151
152 $componentDetails = [];
153
154 $rowCount = self::EXPORT_ROW_COUNT;
155 $offset = 0;
156 // we write to temp table often to avoid using too much memory
157 $tempRowCount = 100;
158
159 $count = -1;
160
161 $sqlColumns = $processor->getSQLColumns();
162 $processor->createTempTable();
163 $limitReached = FALSE;
164
165 while (!$limitReached) {
166 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
167 CRM_Core_DAO::disableFullGroupByMode();
168 $iterationDAO = CRM_Core_DAO::executeQuery($limitQuery);
169 CRM_Core_DAO::reenableFullGroupByMode();
170 // If this is less than our limit by the end of the iteration we do not need to run the query again to
171 // check if some remain.
172 $rowsThisIteration = 0;
173
174 while ($iterationDAO->fetch()) {
175 $count++;
176 $rowsThisIteration++;
177 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader);
178 if ($row === FALSE) {
179 continue;
180 }
181
182 // add component info
183 // write the row to a file
184 $componentDetails[] = $row;
185
186 // output every $tempRowCount rows
187 if ($count % $tempRowCount == 0) {
188 self::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
189 $componentDetails = [];
190 }
191 }
192 if ($rowsThisIteration < self::EXPORT_ROW_COUNT) {
193 $limitReached = TRUE;
194 }
195 $offset += $rowCount;
196 }
197
198 if ($processor->getTemporaryTable()) {
199 self::writeDetailsToTable($processor, $componentDetails);
200
201 // do merge same address and merge same household processing
202 if ($mergeSameAddress) {
203 $processor->mergeSameAddress();
204 }
205
206 $processor->writeCSVFromTable();
207
208 // delete the export temp table and component table
209 $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable();
210 CRM_Core_DAO::executeQuery($sql);
211 CRM_Core_DAO::reenableFullGroupByMode();
212 CRM_Utils_System::civiExit(0, ['processor' => $processor]);
213 }
214 else {
215 CRM_Core_DAO::reenableFullGroupByMode();
216 throw new CRM_Core_Exception(ts('No records to export'));
217 }
218 }
219
220 /**
221 * Handle import error file creation.
222 */
223 public static function invoke() {
224 $type = CRM_Utils_Request::retrieve('type', 'Positive');
225 $parserName = CRM_Utils_Request::retrieve('parser', 'String');
226 if (empty($parserName) || empty($type)) {
227 return;
228 }
229
230 // clean and ensure parserName is a valid string
231 $parserName = CRM_Utils_String::munge($parserName);
232 $parserClass = explode('_', $parserName);
233
234 // make sure parserClass is in the CRM namespace and
235 // at least 3 levels deep
236 if ($parserClass[0] == 'CRM' &&
237 count($parserClass) >= 3
238 ) {
239 require_once str_replace('_', DIRECTORY_SEPARATOR, $parserName) . ".php";
240 // ensure the functions exists
241 if (method_exists($parserName, 'errorFileName') &&
242 method_exists($parserName, 'saveFileName')
243 ) {
244 $errorFileName = $parserName::errorFileName($type);
245 $saveFileName = $parserName::saveFileName($type);
246 if (!empty($errorFileName) && !empty($saveFileName)) {
247 CRM_Utils_System::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
248 CRM_Utils_System::setHttpHeader('Content-Description', 'File Transfer');
249 CRM_Utils_System::setHttpHeader('Content-Type', 'text/csv');
250 CRM_Utils_System::setHttpHeader('Content-Length', filesize($errorFileName));
251 CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
252
253 readfile($errorFileName);
254 }
255 }
256 }
257 CRM_Utils_System::civiExit();
258 }
259
260 /**
261 * @param $customSearchClass
262 * @param $formValues
263 * @param $order
264 */
265 public static function exportCustom($customSearchClass, $formValues, $order) {
266 $ext = CRM_Extension_System::singleton()->getMapper();
267 if (!$ext->isExtensionClass($customSearchClass)) {
268 require_once str_replace('_', DIRECTORY_SEPARATOR, $customSearchClass) . '.php';
269 }
270 else {
271 require_once $ext->classToPath($customSearchClass);
272 }
273 $search = new $customSearchClass($formValues);
274
275 $includeContactIDs = FALSE;
276 if ($formValues['radio_ts'] == 'ts_sel') {
277 $includeContactIDs = TRUE;
278 }
279
280 $sql = $search->all(0, 0, $order, $includeContactIDs);
281
282 $columns = $search->columns();
283
284 $header = array_keys($columns);
285 $fields = array_values($columns);
286
287 $rows = [];
288 $dao = CRM_Core_DAO::executeQuery($sql);
289 $alterRow = FALSE;
290 if (method_exists($search, 'alterRow')) {
291 $alterRow = TRUE;
292 }
293 while ($dao->fetch()) {
294 $row = [];
295
296 foreach ($fields as $field) {
297 $unqualified_field = CRM_Utils_Array::First(array_slice(explode('.', $field), -1));
298 $row[$field] = $dao->$unqualified_field;
299 }
300 if ($alterRow) {
301 $search->alterRow($row);
302 }
303 $rows[] = $row;
304 }
305
306 CRM_Core_Report_Excel::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
307 CRM_Utils_System::civiExit();
308 }
309
310 /**
311 * @param \CRM_Export_BAO_ExportProcessor $processor
312 * @param $details
313 */
314 public static function writeDetailsToTable($processor, $details) {
315 $tableName = $processor->getTemporaryTable();
316 if (empty($details)) {
317 return;
318 }
319
320 $sql = "
321SELECT max(id)
322FROM $tableName
323";
324
325 $id = CRM_Core_DAO::singleValueQuery($sql);
326 if (!$id) {
327 $id = 0;
328 }
329
330 $sqlClause = [];
331
332 foreach ($details as $row) {
333 $id++;
334 $valueString = [$id];
335 foreach ($row as $value) {
336 if (empty($value)) {
337 $valueString[] = "''";
338 }
339 else {
340 $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'";
341 }
342 }
343 $sqlClause[] = '(' . implode(',', $valueString) . ')';
344 }
345 $sqlColumns = array_merge(['id' => 1], $processor->getSQLColumns());
346 $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
347
348 $sqlValueString = implode(",\n", $sqlClause);
349
350 $sql = "
351INSERT INTO $tableName $sqlColumnString
352VALUES $sqlValueString
353";
354 CRM_Core_DAO::executeQuery($sql);
355 }
356
357 /**
358 * Get the ids that we want to get related contact details for.
359 *
360 * @param array $ids
361 * @param int $exportMode
362 *
363 * @return array
364 */
365 protected static function getIDsForRelatedContact($ids, $exportMode) {
366 if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
367 return $ids;
368 }
369 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
370 $relIDs = [];
371 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
372 $dao = CRM_Core_DAO::executeQuery("
373 SELECT contact_id FROM civicrm_activity_contact
374 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
375 record_type_id = {$sourceID}
376 ");
377
378 while ($dao->fetch()) {
379 $relIDs[] = $dao->contact_id;
380 }
381 return $relIDs;
382 }
383 $componentMapping = [
384 CRM_Export_Form_Select::CONTRIBUTE_EXPORT => 'civicrm_contribution',
385 CRM_Export_Form_Select::EVENT_EXPORT => 'civicrm_participant',
386 CRM_Export_Form_Select::MEMBER_EXPORT => 'civicrm_membership',
387 CRM_Export_Form_Select::PLEDGE_EXPORT => 'civicrm_pledge',
388 CRM_Export_Form_Select::GRANT_EXPORT => 'civicrm_grant',
389 ];
390
391 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
392 return CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
393 }
394 else {
395 return CRM_Core_DAO::getContactIDsFromComponent($ids, $componentMapping[$exportMode]);
396 }
397 }
398
399 /**
400 * @param $selectAll
401 * @param $ids
402 * @param \CRM_Export_BAO_ExportProcessor $processor
403 * @param $componentTable
404 */
405 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
406 $allRelContactArray = $relationQuery = [];
407 $queryMode = $processor->getQueryMode();
408 $exportMode = $processor->getExportMode();
409
410 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
411 $allRelContactArray[$relationshipKey] = [];
412 // build Query for each relationship
413 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
414 NULL, FALSE, FALSE, $queryMode
415 );
416 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
417
418 list($id, $direction) = explode('_', $relationshipKey, 2);
419 // identify the relationship direction
420 $contactA = 'contact_id_a';
421 $contactB = 'contact_id_b';
422 if ($direction == 'b_a') {
423 $contactA = 'contact_id_b';
424 $contactB = 'contact_id_a';
425 }
426 $relIDs = self::getIDsForRelatedContact($ids, $exportMode);
427
428 $relationshipJoin = $relationshipClause = '';
429 if (!$selectAll && $componentTable) {
430 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
431 }
432 elseif (!empty($relIDs)) {
433 $relID = implode(',', $relIDs);
434 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
435 }
436
437 $relationFrom = " {$relationFrom}
438 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
439 {$relationshipJoin} ";
440
441 //check for active relationship status only
442 $today = date('Ymd');
443 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
444 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
445 CRM_Core_DAO::disableFullGroupByMode();
446 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
447 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
448
449 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
450 CRM_Core_DAO::reenableFullGroupByMode();
451
452 while ($allRelContactDAO->fetch()) {
453 $relationQuery->convertToPseudoNames($allRelContactDAO);
454 $row = [];
455 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
456 $processor->fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
457 foreach (array_keys($relationReturnProperties) as $property) {
458 if ($property === 'location') {
459 // @todo - simplify location in fetchRelationshipDetails - remove handling here. Or just call
460 // $processor->setRelationshipValue from fetchRelationshipDetails
461 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
462 foreach (array_keys($locationValues) as $locationValue) {
463 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
464 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $key, $row[$relationshipKey . '__' . $key]);
465 }
466 }
467 }
468 else {
469 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $property, $row[$relationshipKey . '_' . $property]);
470 }
471 }
472 }
473 }
474 }
475
476}