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