Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
fee14197 | 4 | | CiviCRM version 5 | |
6a488035 | 5 | +--------------------------------------------------------------------+ |
6b83d5bd | 6 | | Copyright CiviCRM LLC (c) 2004-2019 | |
6a488035 TO |
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 | +--------------------------------------------------------------------+ | |
d25dd0ee | 26 | */ |
6a488035 TO |
27 | |
28 | /** | |
29 | * | |
30 | * @package CRM | |
6b83d5bd | 31 | * @copyright CiviCRM LLC (c) 2004-2019 |
6a488035 TO |
32 | */ |
33 | ||
34 | /** | |
748450ad | 35 | * This class contains the functions for Component export |
6a488035 TO |
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 | |
24c7dffa | 42 | const EXPORT_ROW_COUNT = 100000; |
6a488035 | 43 | |
f34f5143 SL |
44 | /** |
45 | * Get Export component | |
46 | * | |
47 | * @param int $exportMode | |
48 | * Export mode. | |
49 | * | |
7b966967 | 50 | * @return string |
748450ad | 51 | * CiviCRM Export Component |
f34f5143 | 52 | */ |
7bf9f91e | 53 | public static function exportComponent($exportMode) { |
f34f5143 SL |
54 | switch ($exportMode) { |
55 | case CRM_Export_Form_Select::CONTRIBUTE_EXPORT: | |
56 | $component = 'civicrm_contribution'; | |
57 | break; | |
58 | ||
59 | case CRM_Export_Form_Select::EVENT_EXPORT: | |
60 | $component = 'civicrm_participant'; | |
61 | break; | |
62 | ||
63 | case CRM_Export_Form_Select::MEMBER_EXPORT: | |
64 | $component = 'civicrm_membership'; | |
65 | break; | |
66 | ||
67 | case CRM_Export_Form_Select::PLEDGE_EXPORT: | |
68 | $component = 'civicrm_pledge'; | |
69 | break; | |
70 | ||
71 | case CRM_Export_Form_Select::GRANT_EXPORT: | |
72 | $component = 'civicrm_grant'; | |
73 | break; | |
74 | } | |
75 | return $component; | |
76 | } | |
77 | ||
6a488035 | 78 | /** |
fe482240 | 79 | * Get the list the export fields. |
6a488035 | 80 | * |
b9add4b3 TO |
81 | * @param int $selectAll |
82 | * User preference while export. | |
83 | * @param array $ids | |
84 | * Contact ids. | |
85 | * @param array $params | |
86 | * Associated array of fields. | |
87 | * @param string $order | |
88 | * Order by clause. | |
89 | * @param array $fields | |
90 | * Associated array of fields. | |
91 | * @param array $moreReturnProperties | |
92 | * Additional return fields. | |
93 | * @param int $exportMode | |
94 | * Export mode. | |
95 | * @param string $componentClause | |
96 | * Component clause. | |
97 | * @param string $componentTable | |
98 | * Component table. | |
99 | * @param bool $mergeSameAddress | |
100 | * Merge records if they have same address. | |
101 | * @param bool $mergeSameHousehold | |
102 | * Merge records if they belong to the same household. | |
6c8f6e67 EM |
103 | * |
104 | * @param array $exportParams | |
105 | * @param string $queryOperator | |
6a488035 | 106 | * |
c7224305 | 107 | * @return array|null |
108 | * An array can be requested from within a unit test. | |
109 | * | |
110 | * @throws \CRM_Core_Exception | |
6a488035 | 111 | */ |
317fceb4 | 112 | public static function exportComponents( |
97f6897c | 113 | $selectAll, |
6a488035 TO |
114 | $ids, |
115 | $params, | |
116 | $order = NULL, | |
117 | $fields = NULL, | |
118 | $moreReturnProperties = NULL, | |
119 | $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, | |
120 | $componentClause = NULL, | |
121 | $componentTable = NULL, | |
122 | $mergeSameAddress = FALSE, | |
123 | $mergeSameHousehold = FALSE, | |
be2fb01f | 124 | $exportParams = [], |
6a488035 TO |
125 | $queryOperator = 'AND' |
126 | ) { | |
ef51caa8 | 127 | |
6d52bfe5 | 128 | $isPostalOnly = ( |
129 | isset($exportParams['postal_mailing_export']['postal_mailing_export']) && | |
130 | $exportParams['postal_mailing_export']['postal_mailing_export'] == 1 | |
131 | ); | |
132 | ||
7d6dd61c | 133 | if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) { |
134 | // If an Additional Group is selected, then all contacts in that group are | |
135 | // added to the export set (filtering out duplicates). | |
136 | // Really - the calling function could do this ... just saying | |
137 | // @todo take a whip to the calling function. | |
138 | CRM_Core_DAO::executeQuery(" | |
139 | 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" | |
140 | ); | |
141 | } | |
9e49a7b8 PJ |
142 | // rectify params to what proximity search expects if there is a value for prox_distance |
143 | // CRM-7021 | |
3c6340a6 | 144 | // @todo - move this back to the calling functions |
9e49a7b8 PJ |
145 | if (!empty($params)) { |
146 | CRM_Contact_BAO_ProximityQuery::fixInputParams($params); | |
147 | } | |
3c6340a6 | 148 | // @todo everything from this line up should go back to the calling functions. |
1e9e062d | 149 | $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold, $isPostalOnly, $mergeSameAddress, $exportParams); |
3c6340a6 | 150 | if ($moreReturnProperties) { |
151 | $processor->setAdditionalRequestedReturnProperties($moreReturnProperties); | |
152 | } | |
e034ee91 | 153 | $processor->setComponentTable($componentTable); |
154 | $processor->setComponentClause($componentClause); | |
9e49a7b8 | 155 | |
9858dc0b | 156 | list($query, $queryString) = $processor->runQuery($params, $order); |
6a488035 | 157 | |
ebebd629 | 158 | // This perhaps only needs calling when $mergeSameHousehold == 1 |
ce12a9e0 | 159 | self::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable); |
6a488035 | 160 | |
6a488035 TO |
161 | $addPaymentHeader = FALSE; |
162 | ||
44fc53ab | 163 | list($outputColumns, $metadata) = $processor->getExportStructureArrays(); |
943e6943 | 164 | |
7e2ee2fb | 165 | if ($processor->isMergeSameAddress()) { |
f8fb0608 | 166 | foreach (array_keys($processor->getAdditionalFieldsForSameAddressMerge()) as $field) { |
c8925481 | 167 | $processor->setColumnAsCalculationOnly($field); |
168 | } | |
169 | } | |
170 | ||
943e6943 | 171 | $paymentDetails = []; |
c66a5741 | 172 | if ($processor->isExportPaymentFields()) { |
6a488035 TO |
173 | // get payment related in for event and members |
174 | $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids); | |
d77aba4b | 175 | //get all payment headers. |
7460c131 AS |
176 | // If we haven't selected specific payment fields, load in all the |
177 | // payment headers. | |
c66a5741 | 178 | if (!$processor->isExportSpecifiedPaymentFields()) { |
d77aba4b AS |
179 | if (!empty($paymentDetails)) { |
180 | $addPaymentHeader = TRUE; | |
943e6943 | 181 | foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) { |
182 | $processor->addOutputSpecification($paymentField); | |
183 | } | |
d77aba4b | 184 | } |
6a488035 | 185 | } |
6a488035 TO |
186 | } |
187 | ||
be2fb01f | 188 | $componentDetails = []; |
6a488035 TO |
189 | |
190 | $rowCount = self::EXPORT_ROW_COUNT; | |
191 | $offset = 0; | |
192 | // we write to temp table often to avoid using too much memory | |
193 | $tempRowCount = 100; | |
194 | ||
195 | $count = -1; | |
196 | ||
28254dcb | 197 | $headerRows = $processor->getHeaderRows(); |
2cd3d767 | 198 | $sqlColumns = $processor->getSQLColumns(); |
3e644436 | 199 | $processor->createTempTable(); |
24c7dffa | 200 | $limitReached = FALSE; |
0b94b406 | 201 | |
24c7dffa | 202 | while (!$limitReached) { |
6a488035 | 203 | $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}"; |
6f5824c1 | 204 | CRM_Core_DAO::disableFullGroupByMode(); |
bab4f15e | 205 | $iterationDAO = CRM_Core_DAO::executeQuery($limitQuery); |
6f5824c1 | 206 | CRM_Core_DAO::reenableFullGroupByMode(); |
24c7dffa | 207 | // If this is less than our limit by the end of the iteration we do not need to run the query again to |
208 | // check if some remain. | |
209 | $rowsThisIteration = 0; | |
6a488035 | 210 | |
bab4f15e | 211 | while ($iterationDAO->fetch()) { |
6a488035 | 212 | $count++; |
24c7dffa | 213 | $rowsThisIteration++; |
c58085f8 | 214 | $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader); |
136f69a8 | 215 | if ($row === FALSE) { |
216 | continue; | |
217 | } | |
6a488035 TO |
218 | |
219 | // add component info | |
220 | // write the row to a file | |
221 | $componentDetails[] = $row; | |
222 | ||
223 | // output every $tempRowCount rows | |
224 | if ($count % $tempRowCount == 0) { | |
68989e71 | 225 | self::writeDetailsToTable($processor, $componentDetails, $sqlColumns); |
be2fb01f | 226 | $componentDetails = []; |
6a488035 TO |
227 | } |
228 | } | |
24c7dffa | 229 | if ($rowsThisIteration < self::EXPORT_ROW_COUNT) { |
230 | $limitReached = TRUE; | |
231 | } | |
6a488035 TO |
232 | $offset += $rowCount; |
233 | } | |
234 | ||
68989e71 | 235 | if ($processor->getTemporaryTable()) { |
c33484c7 | 236 | self::writeDetailsToTable($processor, $componentDetails); |
6a488035 TO |
237 | |
238 | // do merge same address and merge same household processing | |
239 | if ($mergeSameAddress) { | |
f8fb0608 | 240 | $processor->mergeSameAddress(); |
6a488035 TO |
241 | } |
242 | ||
6a488035 | 243 | // call export hook |
68989e71 | 244 | $table = $processor->getTemporaryTable(); |
245 | CRM_Utils_Hook::export($table, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids); | |
246 | if ($table !== $processor->getTemporaryTable()) { | |
247 | CRM_Core_Error::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)'); | |
248 | $processor->setTemporaryTable($table); | |
249 | } | |
6a488035 | 250 | |
ef51caa8 | 251 | // In order to be able to write a unit test against this function we need to suppress |
252 | // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions. | |
253 | if (empty($exportParams['suppress_csv_for_testing'])) { | |
68989e71 | 254 | self::writeCSVFromTable($headerRows, $sqlColumns, $processor); |
ef51caa8 | 255 | } |
994a070c | 256 | else { |
b7db6051 | 257 | // return tableName sqlColumns headerRows in test context |
68989e71 | 258 | return [$processor->getTemporaryTable(), $sqlColumns, $headerRows, $processor]; |
994a070c | 259 | } |
6a488035 TO |
260 | |
261 | // delete the export temp table and component table | |
68989e71 | 262 | $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable(); |
6a488035 | 263 | CRM_Core_DAO::executeQuery($sql); |
2f68ef20 | 264 | CRM_Core_DAO::reenableFullGroupByMode(); |
68989e71 | 265 | CRM_Utils_System::civiExit(0, ['processor' => $processor]); |
6a488035 TO |
266 | } |
267 | else { | |
2f68ef20 | 268 | CRM_Core_DAO::reenableFullGroupByMode(); |
c7224305 | 269 | throw new CRM_Core_Exception(ts('No records to export')); |
6a488035 TO |
270 | } |
271 | } | |
272 | ||
6a488035 | 273 | /** |
100fef9d | 274 | * Handle import error file creation. |
6a488035 | 275 | */ |
00be9182 | 276 | public static function invoke() { |
a3d827a7 CW |
277 | $type = CRM_Utils_Request::retrieve('type', 'Positive'); |
278 | $parserName = CRM_Utils_Request::retrieve('parser', 'String'); | |
6a488035 TO |
279 | if (empty($parserName) || empty($type)) { |
280 | return; | |
281 | } | |
282 | ||
283 | // clean and ensure parserName is a valid string | |
284 | $parserName = CRM_Utils_String::munge($parserName); | |
285 | $parserClass = explode('_', $parserName); | |
286 | ||
287 | // make sure parserClass is in the CRM namespace and | |
288 | // at least 3 levels deep | |
289 | if ($parserClass[0] == 'CRM' && | |
290 | count($parserClass) >= 3 | |
291 | ) { | |
d3e86119 | 292 | require_once str_replace('_', DIRECTORY_SEPARATOR, $parserName) . ".php"; |
6a488035 TO |
293 | // ensure the functions exists |
294 | if (method_exists($parserName, 'errorFileName') && | |
295 | method_exists($parserName, 'saveFileName') | |
296 | ) { | |
297 | $errorFileName = $parserName::errorFileName($type); | |
298 | $saveFileName = $parserName::saveFileName($type); | |
299 | if (!empty($errorFileName) && !empty($saveFileName)) { | |
d42a224c CW |
300 | CRM_Utils_System::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0'); |
301 | CRM_Utils_System::setHttpHeader('Content-Description', 'File Transfer'); | |
302 | CRM_Utils_System::setHttpHeader('Content-Type', 'text/csv'); | |
303 | CRM_Utils_System::setHttpHeader('Content-Length', filesize($errorFileName)); | |
304 | CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName); | |
6a488035 TO |
305 | |
306 | readfile($errorFileName); | |
307 | } | |
308 | } | |
309 | } | |
310 | CRM_Utils_System::civiExit(); | |
311 | } | |
312 | ||
e0ef6999 EM |
313 | /** |
314 | * @param $customSearchClass | |
315 | * @param $formValues | |
316 | * @param $order | |
317 | */ | |
00be9182 | 318 | public static function exportCustom($customSearchClass, $formValues, $order) { |
6a488035 TO |
319 | $ext = CRM_Extension_System::singleton()->getMapper(); |
320 | if (!$ext->isExtensionClass($customSearchClass)) { | |
d3e86119 | 321 | require_once str_replace('_', DIRECTORY_SEPARATOR, $customSearchClass) . '.php'; |
6a488035 TO |
322 | } |
323 | else { | |
d3e86119 | 324 | require_once $ext->classToPath($customSearchClass); |
6a488035 TO |
325 | } |
326 | $search = new $customSearchClass($formValues); | |
327 | ||
328 | $includeContactIDs = FALSE; | |
329 | if ($formValues['radio_ts'] == 'ts_sel') { | |
330 | $includeContactIDs = TRUE; | |
331 | } | |
332 | ||
333 | $sql = $search->all(0, 0, $order, $includeContactIDs); | |
334 | ||
335 | $columns = $search->columns(); | |
336 | ||
337 | $header = array_keys($columns); | |
338 | $fields = array_values($columns); | |
339 | ||
be2fb01f | 340 | $rows = []; |
97f6897c | 341 | $dao = CRM_Core_DAO::executeQuery($sql); |
6a488035 TO |
342 | $alterRow = FALSE; |
343 | if (method_exists($search, 'alterRow')) { | |
344 | $alterRow = TRUE; | |
345 | } | |
346 | while ($dao->fetch()) { | |
be2fb01f | 347 | $row = []; |
6a488035 TO |
348 | |
349 | foreach ($fields as $field) { | |
37990ecd JV |
350 | $unqualified_field = CRM_Utils_Array::First(array_slice(explode('.', $field), -1)); |
351 | $row[$field] = $dao->$unqualified_field; | |
6a488035 TO |
352 | } |
353 | if ($alterRow) { | |
354 | $search->alterRow($row); | |
355 | } | |
356 | $rows[] = $row; | |
357 | } | |
358 | ||
620eae15 | 359 | CRM_Core_Report_Excel::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows); |
6a488035 TO |
360 | CRM_Utils_System::civiExit(); |
361 | } | |
362 | ||
e0ef6999 | 363 | /** |
68989e71 | 364 | * @param \CRM_Export_BAO_ExportProcessor $processor |
e0ef6999 | 365 | * @param $details |
e0ef6999 | 366 | */ |
c33484c7 | 367 | public static function writeDetailsToTable($processor, $details) { |
68989e71 | 368 | $tableName = $processor->getTemporaryTable(); |
6a488035 TO |
369 | if (empty($details)) { |
370 | return; | |
371 | } | |
372 | ||
373 | $sql = " | |
374 | SELECT max(id) | |
375 | FROM $tableName | |
376 | "; | |
377 | ||
378 | $id = CRM_Core_DAO::singleValueQuery($sql); | |
379 | if (!$id) { | |
380 | $id = 0; | |
381 | } | |
382 | ||
be2fb01f | 383 | $sqlClause = []; |
6a488035 | 384 | |
610f72e1 | 385 | foreach ($details as $row) { |
6a488035 | 386 | $id++; |
be2fb01f | 387 | $valueString = [$id]; |
610f72e1 | 388 | foreach ($row as $value) { |
6a488035 TO |
389 | if (empty($value)) { |
390 | $valueString[] = "''"; | |
391 | } | |
392 | else { | |
393 | $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'"; | |
394 | } | |
395 | } | |
396 | $sqlClause[] = '(' . implode(',', $valueString) . ')'; | |
397 | } | |
c33484c7 | 398 | $sqlColumns = array_merge(['id' => 1], $processor->getSQLColumns()); |
dfab581c | 399 | $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')'; |
6a488035 TO |
400 | |
401 | $sqlValueString = implode(",\n", $sqlClause); | |
402 | ||
403 | $sql = " | |
404 | INSERT INTO $tableName $sqlColumnString | |
405 | VALUES $sqlValueString | |
406 | "; | |
6a488035 TO |
407 | CRM_Core_DAO::executeQuery($sql); |
408 | } | |
409 | ||
e0ef6999 | 410 | /** |
e0ef6999 EM |
411 | * @param $headerRows |
412 | * @param $sqlColumns | |
70107611 | 413 | * @param \CRM_Export_BAO_ExportProcessor $processor |
e0ef6999 | 414 | */ |
68989e71 | 415 | public static function writeCSVFromTable($headerRows, $sqlColumns, $processor) { |
416 | $exportTempTable = $processor->getTemporaryTable(); | |
6a488035 | 417 | $writeHeader = TRUE; |
97f6897c TO |
418 | $offset = 0; |
419 | $limit = self::EXPORT_ROW_COUNT; | |
6a488035 TO |
420 | |
421 | $query = "SELECT * FROM $exportTempTable"; | |
422 | ||
423 | while (1) { | |
424 | $limitQuery = $query . " | |
425 | LIMIT $offset, $limit | |
426 | "; | |
427 | $dao = CRM_Core_DAO::executeQuery($limitQuery); | |
428 | ||
429 | if ($dao->N <= 0) { | |
430 | break; | |
431 | } | |
432 | ||
be2fb01f | 433 | $componentDetails = []; |
6a488035 | 434 | while ($dao->fetch()) { |
be2fb01f | 435 | $row = []; |
6a488035 | 436 | |
f8fb0608 | 437 | foreach (array_keys($processor->getSQLColumns()) as $column) { |
6a488035 TO |
438 | $row[$column] = $dao->$column; |
439 | } | |
440 | $componentDetails[] = $row; | |
441 | } | |
29034a98 | 442 | CRM_Core_Report_Excel::writeCSVFile($processor->getExportFileName(), |
6a488035 TO |
443 | $headerRows, |
444 | $componentDetails, | |
97f6897c | 445 | NULL, |
70107611 | 446 | $writeHeader |
447 | ); | |
6a488035 | 448 | |
97f6897c | 449 | $writeHeader = FALSE; |
6a488035 TO |
450 | $offset += $limit; |
451 | } | |
452 | } | |
453 | ||
d77aba4b AS |
454 | /** |
455 | * Build componentPayment fields. | |
0e32ed68 | 456 | * |
457 | * This is no longer used by export but BAO_Mapping still calls it & we | |
458 | * should find a generic way to handle this or move this to that class. | |
459 | * | |
460 | * @deprecated | |
d77aba4b | 461 | */ |
00be9182 | 462 | public static function componentPaymentFields() { |
d77aba4b | 463 | static $componentPaymentFields; |
97f6897c | 464 | if (!isset($componentPaymentFields)) { |
be2fb01f | 465 | $componentPaymentFields = [ |
97f6897c | 466 | 'componentPaymentField_total_amount' => ts('Total Amount'), |
d77aba4b | 467 | 'componentPaymentField_contribution_status' => ts('Contribution Status'), |
7bc6b5bb | 468 | 'componentPaymentField_received_date' => ts('Date Received'), |
536f0e02 | 469 | 'componentPaymentField_payment_instrument' => ts('Payment Method'), |
97f6897c | 470 | 'componentPaymentField_transaction_id' => ts('Transaction ID'), |
be2fb01f | 471 | ]; |
d77aba4b AS |
472 | } |
473 | return $componentPaymentFields; | |
474 | } | |
96025800 | 475 | |
1860fab0 | 476 | /** |
477 | * Get the values of linked household contact. | |
478 | * | |
479 | * @param CRM_Core_DAO $relDAO | |
480 | * @param array $value | |
481 | * @param string $field | |
482 | * @param array $row | |
483 | */ | |
484 | private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) { | |
485 | $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); | |
486 | $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); | |
487 | $i18n = CRM_Core_I18n::singleton(); | |
ce12a9e0 | 488 | $field = $field . '_'; |
489 | ||
1860fab0 | 490 | foreach ($value as $relationField => $relationValue) { |
491 | if (is_object($relDAO) && property_exists($relDAO, $relationField)) { | |
492 | $fieldValue = $relDAO->$relationField; | |
493 | if ($relationField == 'phone_type_id') { | |
494 | $fieldValue = $phoneTypes[$relationValue]; | |
495 | } | |
496 | elseif ($relationField == 'provider_id') { | |
497 | $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders); | |
498 | } | |
499 | // CRM-13995 | |
be2fb01f | 500 | elseif (is_object($relDAO) && in_array($relationField, [ |
7b966967 SL |
501 | 'email_greeting', |
502 | 'postal_greeting', | |
503 | 'addressee', | |
504 | ])) { | |
1860fab0 | 505 | //special case for greeting replacement |
506 | $fldValue = "{$relationField}_display"; | |
507 | $fieldValue = $relDAO->$fldValue; | |
508 | } | |
509 | } | |
510 | elseif (is_object($relDAO) && $relationField == 'state_province') { | |
511 | $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id); | |
512 | } | |
513 | elseif (is_object($relDAO) && $relationField == 'country') { | |
514 | $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id); | |
515 | } | |
516 | else { | |
517 | $fieldValue = ''; | |
518 | } | |
f0d58350 | 519 | $relPrefix = $field . $relationField; |
1860fab0 | 520 | |
521 | if (is_object($relDAO) && $relationField == 'id') { | |
f0d58350 | 522 | $row[$relPrefix] = $relDAO->contact_id; |
1860fab0 | 523 | } |
524 | elseif (is_array($relationValue) && $relationField == 'location') { | |
525 | foreach ($relationValue as $ltype => $val) { | |
a16a432a | 526 | // If the location name has a space in it the we need to handle that. This |
527 | // is kinda hacky but specifically covered in the ExportTest so later efforts to | |
528 | // improve it should be secure in the knowled it will be caught. | |
529 | $ltype = str_replace(' ', '_', $ltype); | |
1860fab0 | 530 | foreach (array_keys($val) as $fld) { |
531 | $type = explode('-', $fld); | |
532 | $fldValue = "{$ltype}-" . $type[0]; | |
533 | if (!empty($type[1])) { | |
534 | $fldValue .= "-" . $type[1]; | |
535 | } | |
536 | // CRM-3157: localise country, region (both have ‘country’ context) | |
537 | // and state_province (‘province’ context) | |
538 | switch (TRUE) { | |
539 | case (!is_object($relDAO)): | |
540 | $row[$field . '_' . $fldValue] = ''; | |
541 | break; | |
542 | ||
543 | case in_array('country', $type): | |
544 | case in_array('world_region', $type): | |
545 | $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue, | |
be2fb01f | 546 | ['context' => 'country'] |
1860fab0 | 547 | ); |
548 | break; | |
549 | ||
550 | case in_array('state_province', $type): | |
551 | $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue, | |
be2fb01f | 552 | ['context' => 'province'] |
1860fab0 | 553 | ); |
554 | break; | |
555 | ||
556 | default: | |
557 | $row[$field . '_' . $fldValue] = $relDAO->$fldValue; | |
558 | break; | |
559 | } | |
560 | } | |
561 | } | |
562 | } | |
563 | elseif (isset($fieldValue) && $fieldValue != '') { | |
564 | //check for custom data | |
565 | if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) { | |
f0d58350 | 566 | $row[$relPrefix] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID); |
1860fab0 | 567 | } |
568 | else { | |
569 | //normal relationship fields | |
570 | // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context) | |
571 | switch ($relationField) { | |
572 | case 'country': | |
573 | case 'world_region': | |
be2fb01f | 574 | $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']); |
1860fab0 | 575 | break; |
576 | ||
577 | case 'state_province': | |
be2fb01f | 578 | $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']); |
1860fab0 | 579 | break; |
580 | ||
581 | default: | |
f0d58350 | 582 | $row[$relPrefix] = $fieldValue; |
1860fab0 | 583 | break; |
584 | } | |
585 | } | |
586 | } | |
587 | else { | |
588 | // if relation field is empty or null | |
f0d58350 | 589 | $row[$relPrefix] = ''; |
1860fab0 | 590 | } |
591 | } | |
592 | } | |
593 | ||
814065a3 | 594 | /** |
595 | * Get the ids that we want to get related contact details for. | |
596 | * | |
597 | * @param array $ids | |
598 | * @param int $exportMode | |
599 | * | |
600 | * @return array | |
601 | */ | |
602 | protected static function getIDsForRelatedContact($ids, $exportMode) { | |
603 | if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) { | |
604 | return $ids; | |
605 | } | |
606 | if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) { | |
607 | $relIDs = []; | |
608 | $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source'); | |
609 | $dao = CRM_Core_DAO::executeQuery(" | |
610 | SELECT contact_id FROM civicrm_activity_contact | |
611 | WHERE activity_id IN ( " . implode(',', $ids) . ") AND | |
612 | record_type_id = {$sourceID} | |
613 | "); | |
614 | ||
615 | while ($dao->fetch()) { | |
616 | $relIDs[] = $dao->contact_id; | |
617 | } | |
618 | return $relIDs; | |
619 | } | |
620 | $component = self::exportComponent($exportMode); | |
621 | ||
622 | if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) { | |
623 | return CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids); | |
624 | } | |
625 | else { | |
626 | return CRM_Core_DAO::getContactIDsFromComponent($ids, $component); | |
627 | } | |
628 | } | |
629 | ||
44f8f95c | 630 | /** |
631 | * @param $selectAll | |
632 | * @param $ids | |
439355f5 | 633 | * @param \CRM_Export_BAO_ExportProcessor $processor |
44f8f95c | 634 | * @param $componentTable |
44f8f95c | 635 | */ |
ce12a9e0 | 636 | protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) { |
be2fb01f | 637 | $allRelContactArray = $relationQuery = []; |
439355f5 | 638 | $queryMode = $processor->getQueryMode(); |
639 | $exportMode = $processor->getExportMode(); | |
44f8f95c | 640 | |
ce12a9e0 | 641 | foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) { |
be2fb01f | 642 | $allRelContactArray[$relationshipKey] = []; |
ce12a9e0 | 643 | // build Query for each relationship |
644 | $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties, | |
645 | NULL, FALSE, FALSE, $queryMode | |
646 | ); | |
647 | list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query(); | |
648 | ||
649 | list($id, $direction) = explode('_', $relationshipKey, 2); | |
650 | // identify the relationship direction | |
651 | $contactA = 'contact_id_a'; | |
652 | $contactB = 'contact_id_b'; | |
653 | if ($direction == 'b_a') { | |
654 | $contactA = 'contact_id_b'; | |
655 | $contactB = 'contact_id_a'; | |
656 | } | |
657 | $relIDs = self::getIDsForRelatedContact($ids, $exportMode); | |
658 | ||
659 | $relationshipJoin = $relationshipClause = ''; | |
660 | if (!$selectAll && $componentTable) { | |
661 | $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}"; | |
662 | } | |
663 | elseif (!empty($relIDs)) { | |
664 | $relID = implode(',', $relIDs); | |
665 | $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )"; | |
666 | } | |
44f8f95c | 667 | |
ce12a9e0 | 668 | $relationFrom = " {$relationFrom} |
669 | INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id} | |
670 | {$relationshipJoin} "; | |
671 | ||
672 | //check for active relationship status only | |
673 | $today = date('Ymd'); | |
674 | $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )"; | |
675 | $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}"; | |
6f5824c1 | 676 | CRM_Core_DAO::disableFullGroupByMode(); |
ce12a9e0 | 677 | $relationSelect = "{$relationSelect}, {$contactA} as refContact "; |
6f5824c1 | 678 | $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}"; |
ce12a9e0 | 679 | |
680 | $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString); | |
6f5824c1 | 681 | CRM_Core_DAO::reenableFullGroupByMode(); |
682 | ||
ce12a9e0 | 683 | while ($allRelContactDAO->fetch()) { |
684 | $relationQuery->convertToPseudoNames($allRelContactDAO); | |
685 | $row = []; | |
686 | // @todo pass processor to fetchRelationshipDetails and set fields directly within it. | |
687 | self::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row); | |
688 | foreach (array_keys($relationReturnProperties) as $property) { | |
689 | if ($property === 'location') { | |
690 | // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call | |
691 | // $processor->setRelationshipValue from fetchRelationshipDetails | |
692 | foreach ($relationReturnProperties['location'] as $locationName => $locationValues) { | |
693 | foreach (array_keys($locationValues) as $locationValue) { | |
694 | $key = str_replace(' ', '_', $locationName) . '-' . $locationValue; | |
695 | $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $key, $row[$relationshipKey . '__' . $key]); | |
696 | } | |
697 | } | |
698 | } | |
699 | else { | |
700 | $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $property, $row[$relationshipKey . '_' . $property]); | |
701 | } | |
44f8f95c | 702 | } |
44f8f95c | 703 | } |
704 | } | |
44f8f95c | 705 | } |
706 | ||
6a488035 | 707 | } |