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'])) { | |
608 | self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode); | |
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 | ||
627 | /** | |
fe482240 | 628 | * Name of the export file based on mode. |
6a488035 | 629 | * |
b9add4b3 TO |
630 | * @param string $output |
631 | * Type of output. | |
632 | * @param int $mode | |
633 | * Export mode. | |
6a488035 | 634 | * |
a6c01b45 CW |
635 | * @return string |
636 | * name of the file | |
6a488035 | 637 | */ |
00be9182 | 638 | public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select::CONTACT_EXPORT) { |
6a488035 TO |
639 | switch ($mode) { |
640 | case CRM_Export_Form_Select::CONTACT_EXPORT: | |
641 | return ts('CiviCRM Contact Search'); | |
642 | ||
643 | case CRM_Export_Form_Select::CONTRIBUTE_EXPORT: | |
644 | return ts('CiviCRM Contribution Search'); | |
645 | ||
646 | case CRM_Export_Form_Select::MEMBER_EXPORT: | |
647 | return ts('CiviCRM Member Search'); | |
648 | ||
649 | case CRM_Export_Form_Select::EVENT_EXPORT: | |
650 | return ts('CiviCRM Participant Search'); | |
651 | ||
652 | case CRM_Export_Form_Select::PLEDGE_EXPORT: | |
653 | return ts('CiviCRM Pledge Search'); | |
654 | ||
655 | case CRM_Export_Form_Select::CASE_EXPORT: | |
656 | return ts('CiviCRM Case Search'); | |
657 | ||
658 | case CRM_Export_Form_Select::GRANT_EXPORT: | |
659 | return ts('CiviCRM Grant Search'); | |
660 | ||
661 | case CRM_Export_Form_Select::ACTIVITY_EXPORT: | |
662 | return ts('CiviCRM Activity Search'); | |
663 | } | |
664 | } | |
665 | ||
666 | /** | |
100fef9d | 667 | * Handle import error file creation. |
6a488035 | 668 | */ |
00be9182 | 669 | public static function invoke() { |
a3d827a7 CW |
670 | $type = CRM_Utils_Request::retrieve('type', 'Positive'); |
671 | $parserName = CRM_Utils_Request::retrieve('parser', 'String'); | |
6a488035 TO |
672 | if (empty($parserName) || empty($type)) { |
673 | return; | |
674 | } | |
675 | ||
676 | // clean and ensure parserName is a valid string | |
677 | $parserName = CRM_Utils_String::munge($parserName); | |
678 | $parserClass = explode('_', $parserName); | |
679 | ||
680 | // make sure parserClass is in the CRM namespace and | |
681 | // at least 3 levels deep | |
682 | if ($parserClass[0] == 'CRM' && | |
683 | count($parserClass) >= 3 | |
684 | ) { | |
d3e86119 | 685 | require_once str_replace('_', DIRECTORY_SEPARATOR, $parserName) . ".php"; |
6a488035 TO |
686 | // ensure the functions exists |
687 | if (method_exists($parserName, 'errorFileName') && | |
688 | method_exists($parserName, 'saveFileName') | |
689 | ) { | |
690 | $errorFileName = $parserName::errorFileName($type); | |
691 | $saveFileName = $parserName::saveFileName($type); | |
692 | if (!empty($errorFileName) && !empty($saveFileName)) { | |
d42a224c CW |
693 | CRM_Utils_System::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0'); |
694 | CRM_Utils_System::setHttpHeader('Content-Description', 'File Transfer'); | |
695 | CRM_Utils_System::setHttpHeader('Content-Type', 'text/csv'); | |
696 | CRM_Utils_System::setHttpHeader('Content-Length', filesize($errorFileName)); | |
697 | CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName); | |
6a488035 TO |
698 | |
699 | readfile($errorFileName); | |
700 | } | |
701 | } | |
702 | } | |
703 | CRM_Utils_System::civiExit(); | |
704 | } | |
705 | ||
e0ef6999 EM |
706 | /** |
707 | * @param $customSearchClass | |
708 | * @param $formValues | |
709 | * @param $order | |
710 | */ | |
00be9182 | 711 | public static function exportCustom($customSearchClass, $formValues, $order) { |
6a488035 TO |
712 | $ext = CRM_Extension_System::singleton()->getMapper(); |
713 | if (!$ext->isExtensionClass($customSearchClass)) { | |
d3e86119 | 714 | require_once str_replace('_', DIRECTORY_SEPARATOR, $customSearchClass) . '.php'; |
6a488035 TO |
715 | } |
716 | else { | |
d3e86119 | 717 | require_once $ext->classToPath($customSearchClass); |
6a488035 TO |
718 | } |
719 | $search = new $customSearchClass($formValues); | |
720 | ||
721 | $includeContactIDs = FALSE; | |
722 | if ($formValues['radio_ts'] == 'ts_sel') { | |
723 | $includeContactIDs = TRUE; | |
724 | } | |
725 | ||
726 | $sql = $search->all(0, 0, $order, $includeContactIDs); | |
727 | ||
728 | $columns = $search->columns(); | |
729 | ||
730 | $header = array_keys($columns); | |
731 | $fields = array_values($columns); | |
732 | ||
97f6897c TO |
733 | $rows = array(); |
734 | $dao = CRM_Core_DAO::executeQuery($sql); | |
6a488035 TO |
735 | $alterRow = FALSE; |
736 | if (method_exists($search, 'alterRow')) { | |
737 | $alterRow = TRUE; | |
738 | } | |
739 | while ($dao->fetch()) { | |
740 | $row = array(); | |
741 | ||
742 | foreach ($fields as $field) { | |
37990ecd JV |
743 | $unqualified_field = CRM_Utils_Array::First(array_slice(explode('.', $field), -1)); |
744 | $row[$field] = $dao->$unqualified_field; | |
6a488035 TO |
745 | } |
746 | if ($alterRow) { | |
747 | $search->alterRow($row); | |
748 | } | |
749 | $rows[] = $row; | |
750 | } | |
751 | ||
752 | CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName(), $header, $rows); | |
753 | CRM_Utils_System::civiExit(); | |
754 | } | |
755 | ||
e0ef6999 | 756 | /** |
adabfa40 | 757 | * @param \CRM_Export_BAO_ExportProcessor $processor |
e0ef6999 EM |
758 | * @param $sqlColumns |
759 | * @param $field | |
760 | */ | |
adabfa40 | 761 | public static function sqlColumnDefn($processor, &$sqlColumns, $field) { |
c8adad81 | 762 | $sqlColumns[$processor->getMungedFieldName($field)] = $processor->getSqlColumnDefinition($field); |
6a488035 TO |
763 | } |
764 | ||
e0ef6999 | 765 | /** |
100fef9d | 766 | * @param string $tableName |
e0ef6999 EM |
767 | * @param $details |
768 | * @param $sqlColumns | |
769 | */ | |
610f72e1 | 770 | public static function writeDetailsToTable($tableName, $details, $sqlColumns) { |
6a488035 TO |
771 | if (empty($details)) { |
772 | return; | |
773 | } | |
774 | ||
775 | $sql = " | |
776 | SELECT max(id) | |
777 | FROM $tableName | |
778 | "; | |
779 | ||
780 | $id = CRM_Core_DAO::singleValueQuery($sql); | |
781 | if (!$id) { | |
782 | $id = 0; | |
783 | } | |
784 | ||
785 | $sqlClause = array(); | |
786 | ||
610f72e1 | 787 | foreach ($details as $row) { |
6a488035 TO |
788 | $id++; |
789 | $valueString = array($id); | |
610f72e1 | 790 | foreach ($row as $value) { |
6a488035 TO |
791 | if (empty($value)) { |
792 | $valueString[] = "''"; | |
793 | } | |
794 | else { | |
795 | $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'"; | |
796 | } | |
797 | } | |
798 | $sqlClause[] = '(' . implode(',', $valueString) . ')'; | |
799 | } | |
800 | ||
801 | $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')'; | |
802 | ||
803 | $sqlValueString = implode(",\n", $sqlClause); | |
804 | ||
805 | $sql = " | |
806 | INSERT INTO $tableName $sqlColumnString | |
807 | VALUES $sqlValueString | |
808 | "; | |
6a488035 TO |
809 | CRM_Core_DAO::executeQuery($sql); |
810 | } | |
811 | ||
e0ef6999 EM |
812 | /** |
813 | * @param $sqlColumns | |
814 | * | |
815 | * @return string | |
816 | */ | |
610f72e1 | 817 | public static function createTempTable($sqlColumns) { |
6a488035 | 818 | //creating a temporary table for the search result that need be exported |
8e8b9e7c | 819 | $exportTempTable = CRM_Utils_SQL_TempTable::build()->setDurable()->setCategory('export')->getName(); |
6a488035 TO |
820 | |
821 | // also create the sql table | |
822 | $sql = "DROP TABLE IF EXISTS {$exportTempTable}"; | |
823 | CRM_Core_DAO::executeQuery($sql); | |
824 | ||
825 | $sql = " | |
826 | CREATE TABLE {$exportTempTable} ( | |
827 | id int unsigned NOT NULL AUTO_INCREMENT, | |
828 | "; | |
829 | $sql .= implode(",\n", array_values($sqlColumns)); | |
830 | ||
831 | $sql .= ", | |
832 | PRIMARY KEY ( id ) | |
833 | "; | |
834 | // add indexes for street_address and household_name if present | |
835 | $addIndices = array( | |
836 | 'street_address', | |
837 | 'household_name', | |
838 | 'civicrm_primary_id', | |
839 | ); | |
840 | ||
841 | foreach ($addIndices as $index) { | |
842 | if (isset($sqlColumns[$index])) { | |
843 | $sql .= ", | |
844 | INDEX index_{$index}( $index ) | |
845 | "; | |
846 | } | |
847 | } | |
848 | ||
849 | $sql .= " | |
75f1cd78 | 850 | ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci |
6a488035 TO |
851 | "; |
852 | ||
853 | CRM_Core_DAO::executeQuery($sql); | |
854 | return $exportTempTable; | |
855 | } | |
856 | ||
e0ef6999 | 857 | /** |
100fef9d | 858 | * @param string $tableName |
e0ef6999 EM |
859 | * @param $headerRows |
860 | * @param $sqlColumns | |
100fef9d | 861 | * @param array $exportParams |
e0ef6999 | 862 | */ |
00be9182 | 863 | public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) { |
6a488035 TO |
864 | // check if any records are present based on if they have used shared address feature, |
865 | // and not based on if city / state .. matches. | |
866 | $sql = " | |
867 | SELECT r1.id as copy_id, | |
868 | r1.civicrm_primary_id as copy_contact_id, | |
869 | r1.addressee as copy_addressee, | |
870 | r1.addressee_id as copy_addressee_id, | |
871 | r1.postal_greeting as copy_postal_greeting, | |
872 | r1.postal_greeting_id as copy_postal_greeting_id, | |
873 | r2.id as master_id, | |
874 | r2.civicrm_primary_id as master_contact_id, | |
875 | r2.postal_greeting as master_postal_greeting, | |
876 | r2.postal_greeting_id as master_postal_greeting_id, | |
877 | r2.addressee as master_addressee, | |
878 | r2.addressee_id as master_addressee_id | |
879 | FROM $tableName r1 | |
880 | INNER JOIN civicrm_address adr ON r1.master_id = adr.id | |
881 | INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id | |
882 | ORDER BY r1.id"; | |
883 | $linkedMerge = self::_buildMasterCopyArray($sql, $exportParams, TRUE); | |
884 | ||
885 | // find all the records that have the same street address BUT not in a household | |
886 | // require match on city and state as well | |
887 | $sql = " | |
888 | SELECT r1.id as master_id, | |
889 | r1.civicrm_primary_id as master_contact_id, | |
890 | r1.postal_greeting as master_postal_greeting, | |
891 | r1.postal_greeting_id as master_postal_greeting_id, | |
892 | r1.addressee as master_addressee, | |
893 | r1.addressee_id as master_addressee_id, | |
894 | r2.id as copy_id, | |
895 | r2.civicrm_primary_id as copy_contact_id, | |
896 | r2.postal_greeting as copy_postal_greeting, | |
897 | r2.postal_greeting_id as copy_postal_greeting_id, | |
898 | r2.addressee as copy_addressee, | |
899 | r2.addressee_id as copy_addressee_id | |
900 | FROM $tableName r1 | |
901 | LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND | |
902 | r1.city = r2.city AND | |
903 | r1.state_province_id = r2.state_province_id ) | |
904 | WHERE ( r1.household_name IS NULL OR r1.household_name = '' ) | |
905 | AND ( r2.household_name IS NULL OR r2.household_name = '' ) | |
906 | AND ( r1.street_address != '' ) | |
907 | AND r2.id > r1.id | |
908 | ORDER BY r1.id | |
909 | "; | |
910 | $merge = self::_buildMasterCopyArray($sql, $exportParams); | |
911 | ||
912 | // unset ids from $merge already present in $linkedMerge | |
913 | foreach ($linkedMerge as $masterID => $values) { | |
914 | $keys = array($masterID); | |
915 | $keys = array_merge($keys, array_keys($values['copy'])); | |
916 | foreach ($merge as $mid => $vals) { | |
917 | if (in_array($mid, $keys)) { | |
918 | unset($merge[$mid]); | |
919 | } | |
920 | else { | |
921 | foreach ($values['copy'] as $copyId) { | |
922 | if (in_array($copyId, $keys)) { | |
923 | unset($merge[$mid]['copy'][$copyId]); | |
924 | } | |
925 | } | |
926 | } | |
927 | } | |
928 | } | |
929 | $merge = $merge + $linkedMerge; | |
930 | ||
931 | foreach ($merge as $masterID => $values) { | |
932 | $sql = " | |
933 | UPDATE $tableName | |
934 | SET addressee = %1, postal_greeting = %2, email_greeting = %3 | |
935 | WHERE id = %4 | |
936 | "; | |
97f6897c TO |
937 | $params = array( |
938 | 1 => array($values['addressee'], 'String'), | |
6a488035 TO |
939 | 2 => array($values['postalGreeting'], 'String'), |
940 | 3 => array($values['emailGreeting'], 'String'), | |
941 | 4 => array($masterID, 'Integer'), | |
942 | ); | |
943 | CRM_Core_DAO::executeQuery($sql, $params); | |
944 | ||
945 | // delete all copies | |
97f6897c | 946 | $deleteIDs = array_keys($values['copy']); |
6a488035 | 947 | $deleteIDString = implode(',', $deleteIDs); |
97f6897c | 948 | $sql = " |
6a488035 TO |
949 | DELETE FROM $tableName |
950 | WHERE id IN ( $deleteIDString ) | |
951 | "; | |
952 | CRM_Core_DAO::executeQuery($sql); | |
953 | } | |
954 | ||
955 | // unset temporary columns that were added for postal mailing format | |
956 | if (!empty($exportParams['merge_same_address']['temp_columns'])) { | |
957 | $unsetKeys = array_keys($sqlColumns); | |
958 | foreach ($unsetKeys as $headerKey => $sqlColKey) { | |
959 | if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) { | |
960 | unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]); | |
961 | } | |
962 | } | |
963 | } | |
964 | } | |
965 | ||
e0ef6999 | 966 | /** |
100fef9d CW |
967 | * @param int $contactId |
968 | * @param array $exportParams | |
e0ef6999 EM |
969 | * |
970 | * @return array | |
971 | */ | |
00be9182 | 972 | public static function _replaceMergeTokens($contactId, $exportParams) { |
6a488035 TO |
973 | $greetings = array(); |
974 | $contact = NULL; | |
975 | ||
976 | $greetingFields = array( | |
977 | 'postal_greeting', | |
978 | 'addressee', | |
979 | ); | |
980 | foreach ($greetingFields as $greeting) { | |
a7488080 | 981 | if (!empty($exportParams[$greeting])) { |
6a488035 TO |
982 | $greetingLabel = $exportParams[$greeting]; |
983 | if (empty($contact)) { | |
984 | $values = array( | |
985 | 'id' => $contactId, | |
986 | 'version' => 3, | |
987 | ); | |
988 | $contact = civicrm_api('contact', 'get', $values); | |
989 | ||
a7488080 | 990 | if (!empty($contact['is_error'])) { |
6a488035 TO |
991 | return $greetings; |
992 | } | |
993 | $contact = $contact['values'][$contact['id']]; | |
994 | } | |
995 | ||
996 | $tokens = array('contact' => $greetingLabel); | |
997 | $greetings[$greeting] = CRM_Utils_Token::replaceContactTokens($greetingLabel, $contact, NULL, $tokens); | |
998 | } | |
999 | } | |
1000 | return $greetings; | |
1001 | } | |
1002 | ||
1003 | /** | |
1004 | * The function unsets static part of the string, if token is the dynamic part. | |
54957108 | 1005 | * |
6a488035 TO |
1006 | * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}' |
1007 | * i.e 'Hello Alan' => converted to => 'Alan' | |
54957108 | 1008 | * |
1009 | * @param string $parsedString | |
1010 | * @param string $defaultGreeting | |
1011 | * @param bool $addressMergeGreetings | |
1012 | * @param string $greetingType | |
1013 | * | |
1014 | * @return mixed | |
6a488035 | 1015 | */ |
317fceb4 | 1016 | public static function _trimNonTokens( |
97f6897c | 1017 | &$parsedString, $defaultGreeting, |
353ffa53 | 1018 | $addressMergeGreetings, $greetingType = 'postal_greeting' |
6a488035 | 1019 | ) { |
a7488080 | 1020 | if (!empty($addressMergeGreetings[$greetingType])) { |
6a488035 TO |
1021 | $greetingLabel = $addressMergeGreetings[$greetingType]; |
1022 | } | |
1023 | $greetingLabel = empty($greetingLabel) ? $defaultGreeting : $greetingLabel; | |
1024 | ||
1025 | $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel); | |
1026 | $stringsToBeReplaced = explode(';;', $stringsToBeReplaced); | |
1027 | foreach ($stringsToBeReplaced as $key => $string) { | |
1028 | // to keep one space | |
1029 | $stringsToBeReplaced[$key] = ltrim($string); | |
1030 | } | |
1031 | $parsedString = str_replace($stringsToBeReplaced, "", $parsedString); | |
1032 | ||
1033 | return $parsedString; | |
1034 | } | |
1035 | ||
e0ef6999 EM |
1036 | /** |
1037 | * @param $sql | |
100fef9d | 1038 | * @param array $exportParams |
e0ef6999 EM |
1039 | * @param bool $sharedAddress |
1040 | * | |
1041 | * @return array | |
1042 | */ | |
00be9182 | 1043 | public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) { |
6a488035 TO |
1044 | static $contactGreetingTokens = array(); |
1045 | ||
1046 | $addresseeOptions = CRM_Core_OptionGroup::values('addressee'); | |
1047 | $postalOptions = CRM_Core_OptionGroup::values('postal_greeting'); | |
1048 | ||
1049 | $merge = $parents = array(); | |
1050 | $dao = CRM_Core_DAO::executeQuery($sql); | |
1051 | ||
1052 | while ($dao->fetch()) { | |
1053 | $masterID = $dao->master_id; | |
1054 | $copyID = $dao->copy_id; | |
1055 | $masterPostalGreeting = $dao->master_postal_greeting; | |
1056 | $masterAddressee = $dao->master_addressee; | |
1057 | $copyAddressee = $dao->copy_addressee; | |
1058 | ||
1059 | if (!$sharedAddress) { | |
1060 | if (!isset($contactGreetingTokens[$dao->master_contact_id])) { | |
1061 | $contactGreetingTokens[$dao->master_contact_id] = self::_replaceMergeTokens($dao->master_contact_id, $exportParams); | |
1062 | } | |
1063 | $masterPostalGreeting = CRM_Utils_Array::value('postal_greeting', | |
1064 | $contactGreetingTokens[$dao->master_contact_id], $dao->master_postal_greeting | |
1065 | ); | |
1066 | $masterAddressee = CRM_Utils_Array::value('addressee', | |
1067 | $contactGreetingTokens[$dao->master_contact_id], $dao->master_addressee | |
1068 | ); | |
1069 | ||
1070 | if (!isset($contactGreetingTokens[$dao->copy_contact_id])) { | |
1071 | $contactGreetingTokens[$dao->copy_contact_id] = self::_replaceMergeTokens($dao->copy_contact_id, $exportParams); | |
1072 | } | |
1073 | $copyPostalGreeting = CRM_Utils_Array::value('postal_greeting', | |
1074 | $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_postal_greeting | |
1075 | ); | |
1076 | $copyAddressee = CRM_Utils_Array::value('addressee', | |
1077 | $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_addressee | |
1078 | ); | |
1079 | } | |
1080 | ||
1081 | if (!isset($merge[$masterID])) { | |
1082 | // check if this is an intermediate child | |
1083 | // this happens if there are 3 or more matches a,b, c | |
1084 | // the above query will return a, b / a, c / b, c | |
1085 | // we might be doing a bit more work, but for now its ok, unless someone | |
1086 | // knows how to fix the query above | |
1087 | if (isset($parents[$masterID])) { | |
1088 | $masterID = $parents[$masterID]; | |
1089 | } | |
1090 | else { | |
1091 | $merge[$masterID] = array( | |
1092 | 'addressee' => $masterAddressee, | |
1093 | 'copy' => array(), | |
1094 | 'postalGreeting' => $masterPostalGreeting, | |
1095 | ); | |
1096 | $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting']; | |
1097 | } | |
1098 | } | |
1099 | $parents[$copyID] = $masterID; | |
1100 | ||
1101 | if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) { | |
1102 | ||
a7488080 | 1103 | if (!empty($exportParams['postal_greeting_other']) && |
6a488035 TO |
1104 | count($merge[$masterID]['copy']) >= 1 |
1105 | ) { | |
1106 | // use static greetings specified if no of contacts > 2 | |
1107 | $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other']; | |
1108 | } | |
1109 | elseif ($copyPostalGreeting) { | |
1110 | self::_trimNonTokens($copyPostalGreeting, | |
1111 | $postalOptions[$dao->copy_postal_greeting_id], | |
1112 | $exportParams | |
1113 | ); | |
1114 | $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}"; | |
1115 | // if there happens to be a duplicate, remove it | |
1116 | $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']); | |
1117 | } | |
1118 | ||
a7488080 | 1119 | if (!empty($exportParams['addressee_other']) && |
6a488035 TO |
1120 | count($merge[$masterID]['copy']) >= 1 |
1121 | ) { | |
1122 | // use static greetings specified if no of contacts > 2 | |
1123 | $merge[$masterID]['addressee'] = $exportParams['addressee_other']; | |
1124 | } | |
1125 | elseif ($copyAddressee) { | |
1126 | self::_trimNonTokens($copyAddressee, | |
1127 | $addresseeOptions[$dao->copy_addressee_id], | |
1128 | $exportParams, 'addressee' | |
1129 | ); | |
1130 | $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee); | |
1131 | } | |
1132 | } | |
1133 | $merge[$masterID]['copy'][$copyID] = $copyAddressee; | |
1134 | } | |
1135 | ||
1136 | return $merge; | |
1137 | } | |
1138 | ||
1139 | /** | |
100fef9d | 1140 | * Merge household record into the individual record |
6a488035 TO |
1141 | * if exists |
1142 | * | |
b9add4b3 TO |
1143 | * @param string $exportTempTable |
1144 | * Temporary temp table that stores the records. | |
b9add4b3 TO |
1145 | * @param array $sqlColumns |
1146 | * Array of names of the table columns of the temp table. | |
1147 | * @param string $prefix | |
1148 | * Name of the relationship type that is prefixed to the table columns. | |
6a488035 | 1149 | */ |
b7db6051 | 1150 | public static function mergeSameHousehold($exportTempTable, &$sqlColumns, $prefix) { |
6a488035 | 1151 | $prefixColumn = $prefix . '_'; |
97f6897c TO |
1152 | $allKeys = array_keys($sqlColumns); |
1153 | $replaced = array(); | |
6a488035 TO |
1154 | |
1155 | // name map of the non standard fields in header rows & sql columns | |
1156 | $mappingFields = array( | |
1157 | 'civicrm_primary_id' => 'id', | |
1158 | 'contact_source' => 'source', | |
1159 | 'current_employer_id' => 'employer_id', | |
1160 | 'contact_is_deleted' => 'is_deleted', | |
1161 | 'name' => 'address_name', | |
1162 | 'provider_id' => 'im_service_provider', | |
21dfd5f5 | 1163 | 'phone_type_id' => 'phone_type', |
6a488035 TO |
1164 | ); |
1165 | ||
1166 | //figure out which columns are to be replaced by which ones | |
1167 | foreach ($sqlColumns as $columnNames => $dontCare) { | |
1168 | if ($rep = CRM_Utils_Array::value($columnNames, $mappingFields)) { | |
1169 | $replaced[$columnNames] = CRM_Utils_String::munge($prefixColumn . $rep, '_', 64); | |
1170 | } | |
1171 | else { | |
1172 | $householdColName = CRM_Utils_String::munge($prefixColumn . $columnNames, '_', 64); | |
1173 | ||
a7488080 | 1174 | if (!empty($sqlColumns[$householdColName])) { |
6a488035 TO |
1175 | $replaced[$columnNames] = $householdColName; |
1176 | } | |
1177 | } | |
1178 | } | |
1179 | $query = "UPDATE $exportTempTable SET "; | |
1180 | ||
1181 | $clause = array(); | |
1182 | foreach ($replaced as $from => $to) { | |
1183 | $clause[] = "$from = $to "; | |
1184 | unset($sqlColumns[$to]); | |
6a488035 TO |
1185 | } |
1186 | $query .= implode(",\n", $clause); | |
1187 | $query .= " WHERE {$replaced['civicrm_primary_id']} != ''"; | |
1188 | ||
1189 | CRM_Core_DAO::executeQuery($query); | |
1190 | ||
1191 | //drop the table columns that store redundant household info | |
1192 | $dropQuery = "ALTER TABLE $exportTempTable "; | |
1193 | foreach ($replaced as $householdColumns) { | |
1194 | $dropClause[] = " DROP $householdColumns "; | |
1195 | } | |
1196 | $dropQuery .= implode(",\n", $dropClause); | |
1197 | ||
1198 | CRM_Core_DAO::executeQuery($dropQuery); | |
1199 | ||
1200 | // also drop the temp table if exists | |
1201 | $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp"; | |
1202 | CRM_Core_DAO::executeQuery($sql); | |
1203 | ||
1204 | // clean up duplicate records | |
1205 | $query = " | |
1206 | CREATE TABLE {$exportTempTable}_temp SELECT * | |
1207 | FROM {$exportTempTable} | |
1208 | GROUP BY civicrm_primary_id "; | |
1209 | ||
1210 | CRM_Core_DAO::executeQuery($query); | |
1211 | ||
1212 | $query = "DROP TABLE $exportTempTable"; | |
1213 | CRM_Core_DAO::executeQuery($query); | |
1214 | ||
1215 | $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}"; | |
1216 | CRM_Core_DAO::executeQuery($query); | |
1217 | } | |
1218 | ||
e0ef6999 EM |
1219 | /** |
1220 | * @param $exportTempTable | |
1221 | * @param $headerRows | |
1222 | * @param $sqlColumns | |
1223 | * @param $exportMode | |
1224 | * @param null $saveFile | |
1225 | * @param string $batchItems | |
1226 | */ | |
97f6897c | 1227 | public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') { |
6a488035 | 1228 | $writeHeader = TRUE; |
97f6897c TO |
1229 | $offset = 0; |
1230 | $limit = self::EXPORT_ROW_COUNT; | |
6a488035 TO |
1231 | |
1232 | $query = "SELECT * FROM $exportTempTable"; | |
1233 | ||
1234 | while (1) { | |
1235 | $limitQuery = $query . " | |
1236 | LIMIT $offset, $limit | |
1237 | "; | |
1238 | $dao = CRM_Core_DAO::executeQuery($limitQuery); | |
1239 | ||
1240 | if ($dao->N <= 0) { | |
1241 | break; | |
1242 | } | |
1243 | ||
1244 | $componentDetails = array(); | |
1245 | while ($dao->fetch()) { | |
1246 | $row = array(); | |
1247 | ||
1248 | foreach ($sqlColumns as $column => $dontCare) { | |
1249 | $row[$column] = $dao->$column; | |
1250 | } | |
1251 | $componentDetails[] = $row; | |
1252 | } | |
97f6897c | 1253 | if ($exportMode == 'financial') { |
6a488035 TO |
1254 | $getExportFileName = 'CiviCRM Contribution Search'; |
1255 | } | |
1256 | else { | |
97f6897c | 1257 | $getExportFileName = self::getExportFileName('csv', $exportMode); |
6a488035 | 1258 | } |
97f6897c | 1259 | $csvRows = CRM_Core_Report_Excel::writeCSVFile($getExportFileName, |
6a488035 TO |
1260 | $headerRows, |
1261 | $componentDetails, | |
97f6897c | 1262 | NULL, |
6a488035 | 1263 | $writeHeader, |
97f6897c | 1264 | $saveFile); |
6a488035 TO |
1265 | |
1266 | if ($saveFile && !empty($csvRows)) { | |
1267 | $batchItems .= $csvRows; | |
1268 | } | |
1269 | ||
97f6897c | 1270 | $writeHeader = FALSE; |
6a488035 TO |
1271 | $offset += $limit; |
1272 | } | |
1273 | } | |
1274 | ||
1275 | /** | |
fe482240 | 1276 | * Manipulate header rows for relationship fields. |
ca87146b EM |
1277 | * |
1278 | * @param $headerRows | |
6a488035 | 1279 | */ |
2593f7dc | 1280 | public static function manipulateHeaderRows(&$headerRows) { |
6a488035 TO |
1281 | foreach ($headerRows as & $header) { |
1282 | $split = explode('-', $header); | |
2593f7dc | 1283 | if ($relationTypeName = CRM_Utils_Array::value($split[0], self::$relationshipTypes)) { |
6a488035 TO |
1284 | $split[0] = $relationTypeName; |
1285 | $header = implode('-', $split); | |
1286 | } | |
1287 | } | |
1288 | } | |
1289 | ||
1290 | /** | |
100fef9d | 1291 | * Exclude contacts who are deceased, have "Do not mail" privacy setting, |
6a488035 | 1292 | * or have no street address |
ca87146b EM |
1293 | * @param $exportTempTable |
1294 | * @param $headerRows | |
1295 | * @param $sqlColumns | |
1296 | * @param $exportParams | |
6a488035 | 1297 | */ |
00be9182 | 1298 | public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) { |
6a488035 TO |
1299 | $whereClause = array(); |
1300 | ||
1301 | if (array_key_exists('is_deceased', $sqlColumns)) { | |
1302 | $whereClause[] = 'is_deceased = 1'; | |
1303 | } | |
1304 | ||
1305 | if (array_key_exists('do_not_mail', $sqlColumns)) { | |
1306 | $whereClause[] = 'do_not_mail = 1'; | |
1307 | } | |
1308 | ||
1309 | if (array_key_exists('street_address', $sqlColumns)) { | |
1310 | $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) "; | |
1311 | ||
1312 | // check for supplemental_address_1 | |
1313 | if (array_key_exists('supplemental_address_1', $sqlColumns)) { | |
1314 | $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, | |
1315 | 'address_options', TRUE, NULL, TRUE | |
1316 | ); | |
a7488080 | 1317 | if (!empty($addressOptions['supplemental_address_1'])) { |
6a488035 TO |
1318 | $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) "; |
1319 | // enclose it again, since we are doing an AND in between a set of ORs | |
1320 | $addressWhereClause = "( $addressWhereClause )"; | |
1321 | } | |
1322 | } | |
1323 | ||
1324 | $whereClause[] = $addressWhereClause; | |
1325 | } | |
1326 | ||
1327 | if (!empty($whereClause)) { | |
1328 | $whereClause = implode(' OR ', $whereClause); | |
1329 | $query = " | |
1330 | DELETE | |
1331 | FROM $exportTempTable | |
1332 | WHERE {$whereClause}"; | |
1333 | CRM_Core_DAO::singleValueQuery($query); | |
1334 | } | |
1335 | ||
1336 | // unset temporary columns that were added for postal mailing format | |
1337 | if (!empty($exportParams['postal_mailing_export']['temp_columns'])) { | |
1338 | $unsetKeys = array_keys($sqlColumns); | |
1339 | foreach ($unsetKeys as $headerKey => $sqlColKey) { | |
1340 | if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) { | |
1341 | unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]); | |
1342 | } | |
1343 | } | |
1344 | } | |
1345 | } | |
d77aba4b AS |
1346 | |
1347 | /** | |
1348 | * Build componentPayment fields. | |
1349 | */ | |
00be9182 | 1350 | public static function componentPaymentFields() { |
d77aba4b | 1351 | static $componentPaymentFields; |
97f6897c | 1352 | if (!isset($componentPaymentFields)) { |
d77aba4b | 1353 | $componentPaymentFields = array( |
97f6897c | 1354 | 'componentPaymentField_total_amount' => ts('Total Amount'), |
d77aba4b | 1355 | 'componentPaymentField_contribution_status' => ts('Contribution Status'), |
7bc6b5bb | 1356 | 'componentPaymentField_received_date' => ts('Date Received'), |
536f0e02 | 1357 | 'componentPaymentField_payment_instrument' => ts('Payment Method'), |
97f6897c | 1358 | 'componentPaymentField_transaction_id' => ts('Transaction ID'), |
d77aba4b AS |
1359 | ); |
1360 | } | |
1361 | return $componentPaymentFields; | |
1362 | } | |
96025800 | 1363 | |
12a36993 | 1364 | /** |
1365 | * Set the definition for the header rows and sql columns based on the field to output. | |
1366 | * | |
1367 | * @param string $field | |
1368 | * @param array $headerRows | |
adabfa40 | 1369 | * @param \CRM_Export_BAO_ExportProcessor $processor |
c66a5741 | 1370 | * |
12a36993 | 1371 | * @return array |
1372 | */ | |
cf1b70b7 | 1373 | public static function setHeaderRows($field, $headerRows, $processor) { |
12a36993 | 1374 | |
adabfa40 | 1375 | $queryFields = $processor->getQueryFields(); |
219c47d6 | 1376 | if (substr($field, -11) == 'campaign_id') { |
1377 | // @todo - set this correctly in the xml rather than here. | |
12a36993 | 1378 | $headerRows[] = ts('Campaign ID'); |
1379 | } | |
b7db6051 | 1380 | elseif ($processor->isMergeSameHousehold() && $field === 'id') { |
1381 | $headerRows[] = ts('Household ID'); | |
1382 | } | |
3110c417 | 1383 | elseif (isset($queryFields[$field]['title'])) { |
1384 | $headerRows[] = $queryFields[$field]['title']; | |
12a36993 | 1385 | } |
12a36993 | 1386 | elseif ($field == 'provider_id') { |
219c47d6 | 1387 | // @todo - set this correctly in the xml rather than here. |
12a36993 | 1388 | $headerRows[] = ts('IM Service Provider'); |
1389 | } | |
c66a5741 | 1390 | elseif ($processor->isExportPaymentFields() && array_key_exists($field, self::componentPaymentFields())) { |
12a36993 | 1391 | $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields()); |
1392 | } | |
1393 | else { | |
1394 | $headerRows[] = $field; | |
1395 | } | |
1396 | ||
cf1b70b7 | 1397 | return $headerRows; |
12a36993 | 1398 | } |
1399 | ||
1400 | /** | |
1401 | * Get the various arrays that we use to structure our output. | |
1402 | * | |
1403 | * The extraction of these has been moved to a separate function for clarity and so that | |
1404 | * tests can be added - in particular on the $outputHeaders array. | |
1405 | * | |
1406 | * However it still feels a bit like something that I'm too polite to write down and this should be seen | |
1407 | * as a step on the refactoring path rather than how it should be. | |
1408 | * | |
1409 | * @param array $returnProperties | |
adabfa40 | 1410 | * @param \CRM_Export_BAO_ExportProcessor $processor |
c66a5741 | 1411 | * |
12a36993 | 1412 | * @return array |
1413 | * - outputColumns Array of columns to be exported. The values don't matter but the key must match the | |
1414 | * alias for the field generated by BAO_Query object. | |
1415 | * - headerRows Array of the column header strings to put in the csv header - non-associative. | |
1416 | * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here. | |
1417 | * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution | |
1418 | * I'm too embarassed to discuss here. | |
1419 | * The keys need | |
1420 | * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values | |
1421 | * we could use does suggest further refactors. However, you future improver, do remember that every check you do | |
1422 | * in the main DAO loop is done once per row & that coule be 100,000 times.) | |
1423 | * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because | |
1424 | * - a) the function used is more efficient or | |
1425 | * - b) this code is old & outdated. Submit your answers to circular bin or better | |
1426 | * yet find a way to comment them for posterity. | |
1427 | */ | |
2a48e887 | 1428 | public static function getExportStructureArrays($returnProperties, $processor) { |
12a36993 | 1429 | $metadata = $headerRows = $outputColumns = $sqlColumns = array(); |
efc76c0a | 1430 | $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); |
1431 | $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); | |
adabfa40 | 1432 | $queryFields = $processor->getQueryFields(); |
12a36993 | 1433 | foreach ($returnProperties as $key => $value) { |
3883f8fb | 1434 | if (($key != 'location' || !is_array($value)) && !$processor->isRelationshipTypeKey($key)) { |
1435 | $outputColumns[$key] = $value; | |
cf1b70b7 | 1436 | $headerRows = self::setHeaderRows($key, $headerRows, $processor); |
1437 | self::sqlColumnDefn($processor, $sqlColumns, $key); | |
3883f8fb | 1438 | } |
1439 | elseif ($processor->isRelationshipTypeKey($key)) { | |
12a36993 | 1440 | $outputColumns[$key] = $value; |
3883f8fb | 1441 | $field = $key; |
1442 | foreach ($value as $relationField => $relationValue) { | |
1443 | // below block is same as primary block (duplicate) | |
1444 | if (isset($queryFields[$relationField]['title'])) { | |
1445 | if ($queryFields[$relationField]['name'] == 'name') { | |
1446 | $headerName = $field . '-' . $relationField; | |
1447 | } | |
1448 | else { | |
1449 | if ($relationField == 'current_employer') { | |
1450 | $headerName = $field . '-' . 'current_employer'; | |
1451 | } | |
1452 | else { | |
1453 | $headerName = $field . '-' . $queryFields[$relationField]['name']; | |
1454 | } | |
1455 | } | |
1456 | ||
1457 | if (!$processor->isHouseholdMergeRelationshipTypeKey($field)) { | |
1458 | // Do not add to header row if we are only generating for merge reasons. | |
1459 | $headerRows[] = $headerName; | |
1460 | } | |
1461 | ||
1462 | self::sqlColumnDefn($processor, $sqlColumns, $headerName); | |
1463 | } | |
1464 | elseif ($relationField == 'phone_type_id') { | |
1465 | $headerName = $field . '-' . 'Phone Type'; | |
1466 | $headerRows[] = $headerName; | |
1467 | self::sqlColumnDefn($processor, $sqlColumns, $headerName); | |
1468 | } | |
1469 | elseif ($relationField == 'provider_id') { | |
1470 | $headerName = $field . '-' . 'Im Service Provider'; | |
1471 | $headerRows[] = $headerName; | |
1472 | self::sqlColumnDefn($processor, $sqlColumns, $headerName); | |
1473 | } | |
1474 | elseif ($relationField == 'state_province_id') { | |
1475 | $headerName = $field . '-' . 'state_province_id'; | |
1476 | $headerRows[] = $headerName; | |
1477 | self::sqlColumnDefn($processor, $sqlColumns, $headerName); | |
1478 | } | |
1479 | elseif (is_array($relationValue) && $relationField == 'location') { | |
1480 | // fix header for location type case | |
1481 | foreach ($relationValue as $ltype => $val) { | |
1482 | foreach (array_keys($val) as $fld) { | |
1483 | $type = explode('-', $fld); | |
1484 | ||
1485 | $hdr = "{$ltype}-" . $queryFields[$type[0]]['title']; | |
1486 | ||
1487 | if (!empty($type[1])) { | |
1488 | if (CRM_Utils_Array::value(0, $type) == 'phone') { | |
1489 | $hdr .= "-" . CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', $type[1]); | |
1490 | } | |
1491 | elseif (CRM_Utils_Array::value(0, $type) == 'im') { | |
1492 | $hdr .= "-" . CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_IM', 'provider_id', $type[1]); | |
1493 | } | |
1494 | } | |
1495 | $headerName = $field . '-' . $hdr; | |
1496 | $headerRows[] = $headerName; | |
1497 | self::sqlColumnDefn($processor, $sqlColumns, $headerName); | |
1498 | } | |
1499 | } | |
1500 | } | |
1501 | } | |
1502 | self::manipulateHeaderRows($headerRows); | |
12a36993 | 1503 | } |
1504 | else { | |
1505 | foreach ($value as $locationType => $locationFields) { | |
1506 | foreach (array_keys($locationFields) as $locationFieldName) { | |
1507 | $type = explode('-', $locationFieldName); | |
1508 | ||
1509 | $actualDBFieldName = $type[0]; | |
3110c417 | 1510 | $outputFieldName = $locationType . '-' . $queryFields[$actualDBFieldName]['title']; |
12a36993 | 1511 | $daoFieldName = CRM_Utils_String::munge($locationType) . '-' . $actualDBFieldName; |
1512 | ||
1513 | if (!empty($type[1])) { | |
1514 | $daoFieldName .= "-" . $type[1]; | |
1515 | if ($actualDBFieldName == 'phone') { | |
1516 | $outputFieldName .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes); | |
1517 | } | |
1518 | elseif ($actualDBFieldName == 'im') { | |
1519 | $outputFieldName .= "-" . CRM_Utils_Array::value($type[1], $imProviders); | |
1520 | } | |
1521 | } | |
1522 | if ($type[0] == 'im_provider') { | |
1523 | // Warning: shame inducing hack. | |
1524 | $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders'; | |
1525 | } | |
adabfa40 | 1526 | self::sqlColumnDefn($processor, $sqlColumns, $outputFieldName); |
cf1b70b7 | 1527 | $headerRows = self::setHeaderRows($outputFieldName, $headerRows, $processor); |
1528 | self::sqlColumnDefn($processor, $sqlColumns, $outputFieldName); | |
12a36993 | 1529 | if ($actualDBFieldName == 'country' || $actualDBFieldName == 'world_region') { |
1530 | $metadata[$daoFieldName] = array('context' => 'country'); | |
1531 | } | |
1532 | if ($actualDBFieldName == 'state_province') { | |
1533 | $metadata[$daoFieldName] = array('context' => 'province'); | |
1534 | } | |
1535 | $outputColumns[$daoFieldName] = TRUE; | |
1536 | } | |
1537 | } | |
1538 | } | |
1539 | } | |
1540 | return array($outputColumns, $headerRows, $sqlColumns, $metadata); | |
1541 | } | |
1542 | ||
1860fab0 | 1543 | /** |
1544 | * Get the values of linked household contact. | |
1545 | * | |
1546 | * @param CRM_Core_DAO $relDAO | |
1547 | * @param array $value | |
1548 | * @param string $field | |
1549 | * @param array $row | |
1550 | */ | |
1551 | private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) { | |
1552 | $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); | |
1553 | $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); | |
1554 | $i18n = CRM_Core_I18n::singleton(); | |
1555 | foreach ($value as $relationField => $relationValue) { | |
1556 | if (is_object($relDAO) && property_exists($relDAO, $relationField)) { | |
1557 | $fieldValue = $relDAO->$relationField; | |
1558 | if ($relationField == 'phone_type_id') { | |
1559 | $fieldValue = $phoneTypes[$relationValue]; | |
1560 | } | |
1561 | elseif ($relationField == 'provider_id') { | |
1562 | $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders); | |
1563 | } | |
1564 | // CRM-13995 | |
1565 | elseif (is_object($relDAO) && in_array($relationField, array( | |
1566 | 'email_greeting', | |
1567 | 'postal_greeting', | |
1568 | 'addressee', | |
1569 | )) | |
1570 | ) { | |
1571 | //special case for greeting replacement | |
1572 | $fldValue = "{$relationField}_display"; | |
1573 | $fieldValue = $relDAO->$fldValue; | |
1574 | } | |
1575 | } | |
1576 | elseif (is_object($relDAO) && $relationField == 'state_province') { | |
1577 | $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id); | |
1578 | } | |
1579 | elseif (is_object($relDAO) && $relationField == 'country') { | |
1580 | $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id); | |
1581 | } | |
1582 | else { | |
1583 | $fieldValue = ''; | |
1584 | } | |
1585 | $field = $field . '_'; | |
f0d58350 | 1586 | $relPrefix = $field . $relationField; |
1860fab0 | 1587 | |
1588 | if (is_object($relDAO) && $relationField == 'id') { | |
f0d58350 | 1589 | $row[$relPrefix] = $relDAO->contact_id; |
1860fab0 | 1590 | } |
1591 | elseif (is_array($relationValue) && $relationField == 'location') { | |
1592 | foreach ($relationValue as $ltype => $val) { | |
a16a432a | 1593 | // If the location name has a space in it the we need to handle that. This |
1594 | // is kinda hacky but specifically covered in the ExportTest so later efforts to | |
1595 | // improve it should be secure in the knowled it will be caught. | |
1596 | $ltype = str_replace(' ', '_', $ltype); | |
1860fab0 | 1597 | foreach (array_keys($val) as $fld) { |
1598 | $type = explode('-', $fld); | |
1599 | $fldValue = "{$ltype}-" . $type[0]; | |
1600 | if (!empty($type[1])) { | |
1601 | $fldValue .= "-" . $type[1]; | |
1602 | } | |
1603 | // CRM-3157: localise country, region (both have ‘country’ context) | |
1604 | // and state_province (‘province’ context) | |
1605 | switch (TRUE) { | |
1606 | case (!is_object($relDAO)): | |
1607 | $row[$field . '_' . $fldValue] = ''; | |
1608 | break; | |
1609 | ||
1610 | case in_array('country', $type): | |
1611 | case in_array('world_region', $type): | |
1612 | $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue, | |
1613 | array('context' => 'country') | |
1614 | ); | |
1615 | break; | |
1616 | ||
1617 | case in_array('state_province', $type): | |
1618 | $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue, | |
1619 | array('context' => 'province') | |
1620 | ); | |
1621 | break; | |
1622 | ||
1623 | default: | |
1624 | $row[$field . '_' . $fldValue] = $relDAO->$fldValue; | |
1625 | break; | |
1626 | } | |
1627 | } | |
1628 | } | |
1629 | } | |
1630 | elseif (isset($fieldValue) && $fieldValue != '') { | |
1631 | //check for custom data | |
1632 | if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) { | |
f0d58350 | 1633 | $row[$relPrefix] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID); |
1860fab0 | 1634 | } |
1635 | else { | |
1636 | //normal relationship fields | |
1637 | // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context) | |
1638 | switch ($relationField) { | |
1639 | case 'country': | |
1640 | case 'world_region': | |
f0d58350 | 1641 | $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country')); |
1860fab0 | 1642 | break; |
1643 | ||
1644 | case 'state_province': | |
f0d58350 | 1645 | $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province')); |
1860fab0 | 1646 | break; |
1647 | ||
1648 | default: | |
f0d58350 | 1649 | $row[$relPrefix] = $fieldValue; |
1860fab0 | 1650 | break; |
1651 | } | |
1652 | } | |
1653 | } | |
1654 | else { | |
1655 | // if relation field is empty or null | |
f0d58350 | 1656 | $row[$relPrefix] = ''; |
1860fab0 | 1657 | } |
1658 | } | |
1659 | } | |
1660 | ||
814065a3 | 1661 | /** |
1662 | * Get the ids that we want to get related contact details for. | |
1663 | * | |
1664 | * @param array $ids | |
1665 | * @param int $exportMode | |
1666 | * | |
1667 | * @return array | |
1668 | */ | |
1669 | protected static function getIDsForRelatedContact($ids, $exportMode) { | |
1670 | if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) { | |
1671 | return $ids; | |
1672 | } | |
1673 | if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) { | |
1674 | $relIDs = []; | |
1675 | $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source'); | |
1676 | $dao = CRM_Core_DAO::executeQuery(" | |
1677 | SELECT contact_id FROM civicrm_activity_contact | |
1678 | WHERE activity_id IN ( " . implode(',', $ids) . ") AND | |
1679 | record_type_id = {$sourceID} | |
1680 | "); | |
1681 | ||
1682 | while ($dao->fetch()) { | |
1683 | $relIDs[] = $dao->contact_id; | |
1684 | } | |
1685 | return $relIDs; | |
1686 | } | |
1687 | $component = self::exportComponent($exportMode); | |
1688 | ||
1689 | if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) { | |
1690 | return CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids); | |
1691 | } | |
1692 | else { | |
1693 | return CRM_Core_DAO::getContactIDsFromComponent($ids, $component); | |
1694 | } | |
1695 | } | |
1696 | ||
44f8f95c | 1697 | /** |
1698 | * @param $selectAll | |
1699 | * @param $ids | |
439355f5 | 1700 | * @param \CRM_Export_BAO_ExportProcessor $processor |
44f8f95c | 1701 | * @param $componentTable |
44f8f95c | 1702 | * @param $returnProperties |
439355f5 | 1703 | * |
44f8f95c | 1704 | * @return array |
1705 | */ | |
439355f5 | 1706 | protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable, $returnProperties) { |
44f8f95c | 1707 | $allRelContactArray = $relationQuery = array(); |
439355f5 | 1708 | $queryMode = $processor->getQueryMode(); |
1709 | $exportMode = $processor->getExportMode(); | |
2593f7dc | 1710 | foreach (self::$relationshipTypes as $rel => $dnt) { |
44f8f95c | 1711 | if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) { |
1712 | $allRelContactArray[$rel] = array(); | |
1713 | // build Query for each relationship | |
1714 | $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties, | |
1715 | NULL, FALSE, FALSE, $queryMode | |
1716 | ); | |
1717 | list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query(); | |
1718 | ||
1719 | list($id, $direction) = explode('_', $rel, 2); | |
1720 | // identify the relationship direction | |
1721 | $contactA = 'contact_id_a'; | |
1722 | $contactB = 'contact_id_b'; | |
1723 | if ($direction == 'b_a') { | |
1724 | $contactA = 'contact_id_b'; | |
1725 | $contactB = 'contact_id_a'; | |
1726 | } | |
1727 | $relIDs = self::getIDsForRelatedContact($ids, $exportMode); | |
1728 | ||
1729 | $relationshipJoin = $relationshipClause = ''; | |
1730 | if (!$selectAll && $componentTable) { | |
1731 | $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}"; | |
1732 | } | |
1733 | elseif (!empty($relIDs)) { | |
1734 | $relID = implode(',', $relIDs); | |
1735 | $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )"; | |
1736 | } | |
1737 | ||
1738 | $relationFrom = " {$relationFrom} | |
1739 | INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id} | |
1740 | {$relationshipJoin} "; | |
1741 | ||
1742 | //check for active relationship status only | |
1743 | $today = date('Ymd'); | |
1744 | $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )"; | |
1745 | $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}"; | |
1746 | $relationGroupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($relationQuery[$rel]->_select, "crel.{$contactA}"); | |
1747 | $relationSelect = "{$relationSelect}, {$contactA} as refContact "; | |
1748 | $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy"; | |
1749 | ||
1750 | $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString); | |
1751 | while ($allRelContactDAO->fetch()) { | |
1752 | //FIX Me: Migrate this to table rather than array | |
1753 | // build the array of all related contacts | |
1754 | $allRelContactArray[$rel][$allRelContactDAO->refContact] = clone($allRelContactDAO); | |
1755 | } | |
1756 | $allRelContactDAO->free(); | |
1757 | } | |
1758 | } | |
1759 | return array($relationQuery, $allRelContactArray); | |
1760 | } | |
1761 | ||
3663269c | 1762 | /** |
1763 | * @param $field | |
1764 | * @param $iterationDAO | |
1765 | * @param $fieldValue | |
1766 | * @param $i18n | |
1767 | * @param $metadata | |
3663269c | 1768 | * @param $paymentDetails |
c66a5741 | 1769 | * |
1770 | * @param \CRM_Export_BAO_ExportProcessor $processor | |
1771 | * | |
3663269c | 1772 | * @return string |
1773 | */ | |
c66a5741 | 1774 | protected static function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $paymentDetails, $processor) { |
3663269c | 1775 | |
1776 | if ($field == 'id') { | |
1777 | return $iterationDAO->contact_id; | |
1778 | // special case for calculated field | |
1779 | } | |
1780 | elseif ($field == 'source_contact_id') { | |
1781 | return $iterationDAO->contact_id; | |
1782 | } | |
1783 | elseif ($field == 'pledge_balance_amount') { | |
1784 | return $iterationDAO->pledge_amount - $iterationDAO->pledge_total_paid; | |
1785 | // special case for calculated field | |
1786 | } | |
1787 | elseif ($field == 'pledge_next_pay_amount') { | |
1788 | return $iterationDAO->pledge_next_pay_amount + $iterationDAO->pledge_outstanding_amount; | |
1789 | } | |
1790 | elseif (isset($fieldValue) && | |
1791 | $fieldValue != '' | |
1792 | ) { | |
1793 | //check for custom data | |
1794 | if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) { | |
1795 | return CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID); | |
1796 | } | |
1797 | ||
1798 | elseif (in_array($field, array( | |
1799 | 'email_greeting', | |
1800 | 'postal_greeting', | |
1801 | 'addressee', | |
1802 | ))) { | |
1803 | //special case for greeting replacement | |
1804 | $fldValue = "{$field}_display"; | |
1805 | return $iterationDAO->$fldValue; | |
1806 | } | |
1807 | else { | |
1808 | //normal fields with a touch of CRM-3157 | |
1809 | switch ($field) { | |
1810 | case 'country': | |
1811 | case 'world_region': | |
1812 | return $i18n->crm_translate($fieldValue, array('context' => 'country')); | |
1813 | ||
1814 | case 'state_province': | |
1815 | return $i18n->crm_translate($fieldValue, array('context' => 'province')); | |
1816 | ||
1817 | case 'gender': | |
1818 | case 'preferred_communication_method': | |
1819 | case 'preferred_mail_format': | |
1820 | case 'communication_style': | |
1821 | return $i18n->crm_translate($fieldValue); | |
1822 | ||
1823 | default: | |
1824 | if (isset($metadata[$field])) { | |
1825 | // No I don't know why we do it this way & whether we could | |
1826 | // make better use of pseudoConstants. | |
1827 | if (!empty($metadata[$field]['context'])) { | |
1828 | return $i18n->crm_translate($fieldValue, $metadata[$field]); | |
1829 | } | |
1830 | if (!empty($metadata[$field]['pseudoconstant'])) { | |
1831 | // This is not our normal syntax for pseudoconstants but I am a bit loath to | |
1832 | // call an external function until sure it is not increasing php processing given this | |
1833 | // may be iterated 100,000 times & we already have the $imProvider var loaded. | |
1834 | // That can be next refactor... | |
1835 | // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness | |
1836 | // but I have to reach a stable point.... | |
1837 | $varName = $metadata[$field]['pseudoconstant']['var']; | |
1838 | if ($varName === 'imProviders') { | |
1839 | return CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue); | |
1840 | } | |
1841 | if ($varName === 'phoneTypes') { | |
1842 | return CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_Phone', 'phone_type_id', $fieldValue); | |
1843 | } | |
1844 | } | |
1845 | ||
1846 | } | |
1847 | return $fieldValue; | |
1848 | } | |
1849 | } | |
1850 | } | |
c66a5741 | 1851 | elseif ($processor->isExportSpecifiedPaymentFields() && array_key_exists($field, self::componentPaymentFields())) { |
1852 | $paymentTableId = $processor->getPaymentTableID(); | |
3663269c | 1853 | $paymentData = CRM_Utils_Array::value($iterationDAO->$paymentTableId, $paymentDetails); |
1854 | $payFieldMapper = array( | |
1855 | 'componentPaymentField_total_amount' => 'total_amount', | |
1856 | 'componentPaymentField_contribution_status' => 'contribution_status', | |
1857 | 'componentPaymentField_payment_instrument' => 'pay_instru', | |
1858 | 'componentPaymentField_transaction_id' => 'trxn_id', | |
1859 | 'componentPaymentField_received_date' => 'receive_date', | |
1860 | ); | |
1861 | return CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, ''); | |
1862 | } | |
1863 | else { | |
1864 | // if field is empty or null | |
1865 | return ''; | |
1866 | } | |
1867 | } | |
1868 | ||
6a488035 | 1869 | } |