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