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