| 1 | <?php |
| 2 | /* |
| 3 | +--------------------------------------------------------------------+ |
| 4 | | CiviCRM version 4.7 | |
| 5 | +--------------------------------------------------------------------+ |
| 6 | | Copyright CiviCRM LLC (c) 2004-2016 | |
| 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-2016 |
| 32 | */ |
| 33 | |
| 34 | /** |
| 35 | * This is the heart of the search query building mechanism. |
| 36 | */ |
| 37 | class CRM_Contact_BAO_Query { |
| 38 | |
| 39 | /** |
| 40 | * The various search modes. |
| 41 | * |
| 42 | * @var int |
| 43 | */ |
| 44 | const |
| 45 | NO_RETURN_PROPERTIES = 'CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES', |
| 46 | MODE_CONTACTS = 1, |
| 47 | MODE_CONTRIBUTE = 2, |
| 48 | MODE_MEMBER = 8, |
| 49 | MODE_EVENT = 16, |
| 50 | MODE_GRANT = 128, |
| 51 | MODE_PLEDGEBANK = 256, |
| 52 | MODE_PLEDGE = 512, |
| 53 | MODE_CASE = 2048, |
| 54 | MODE_ALL = 17407, |
| 55 | MODE_ACTIVITY = 4096, |
| 56 | MODE_CAMPAIGN = 8192, |
| 57 | MODE_MAILING = 16384; |
| 58 | |
| 59 | /** |
| 60 | * The default set of return properties. |
| 61 | * |
| 62 | * @var array |
| 63 | */ |
| 64 | static $_defaultReturnProperties = NULL; |
| 65 | |
| 66 | /** |
| 67 | * The default set of hier return properties. |
| 68 | * |
| 69 | * @var array |
| 70 | */ |
| 71 | static $_defaultHierReturnProperties; |
| 72 | |
| 73 | /** |
| 74 | * The set of input params. |
| 75 | * |
| 76 | * @var array |
| 77 | */ |
| 78 | public $_params; |
| 79 | |
| 80 | public $_cfIDs; |
| 81 | |
| 82 | public $_paramLookup; |
| 83 | |
| 84 | public $_sort; |
| 85 | /** |
| 86 | * The set of output params |
| 87 | * |
| 88 | * @var array |
| 89 | */ |
| 90 | public $_returnProperties; |
| 91 | |
| 92 | /** |
| 93 | * The select clause |
| 94 | * |
| 95 | * @var array |
| 96 | */ |
| 97 | public $_select; |
| 98 | |
| 99 | /** |
| 100 | * The name of the elements that are in the select clause |
| 101 | * used to extract the values |
| 102 | * |
| 103 | * @var array |
| 104 | */ |
| 105 | public $_element; |
| 106 | |
| 107 | /** |
| 108 | * The tables involved in the query |
| 109 | * |
| 110 | * @var array |
| 111 | */ |
| 112 | public $_tables; |
| 113 | |
| 114 | /** |
| 115 | * The table involved in the where clause |
| 116 | * |
| 117 | * @var array |
| 118 | */ |
| 119 | public $_whereTables; |
| 120 | |
| 121 | /** |
| 122 | * The where clause |
| 123 | * |
| 124 | * @var array |
| 125 | */ |
| 126 | public $_where; |
| 127 | |
| 128 | /** |
| 129 | * The where string |
| 130 | * |
| 131 | * @var string |
| 132 | */ |
| 133 | public $_whereClause; |
| 134 | |
| 135 | /** |
| 136 | * Additional permission Where Clause |
| 137 | * |
| 138 | * @var string |
| 139 | */ |
| 140 | public $_permissionWhereClause; |
| 141 | |
| 142 | /** |
| 143 | * The from string |
| 144 | * |
| 145 | * @var string |
| 146 | */ |
| 147 | public $_fromClause; |
| 148 | |
| 149 | /** |
| 150 | * Additional permission from clause |
| 151 | * |
| 152 | * @var string |
| 153 | */ |
| 154 | public $_permissionFromClause; |
| 155 | |
| 156 | /** |
| 157 | * The from clause for the simple select and alphabetical |
| 158 | * select |
| 159 | * |
| 160 | * @var string |
| 161 | */ |
| 162 | public $_simpleFromClause; |
| 163 | |
| 164 | /** |
| 165 | * The having values |
| 166 | * |
| 167 | * @var string |
| 168 | */ |
| 169 | public $_having; |
| 170 | |
| 171 | /** |
| 172 | * The english language version of the query |
| 173 | * |
| 174 | * @var array |
| 175 | */ |
| 176 | public $_qill; |
| 177 | |
| 178 | /** |
| 179 | * All the fields that could potentially be involved in |
| 180 | * this query |
| 181 | * |
| 182 | * @var array |
| 183 | */ |
| 184 | public $_fields; |
| 185 | |
| 186 | /** |
| 187 | * The cache to translate the option values into labels. |
| 188 | * |
| 189 | * @var array |
| 190 | */ |
| 191 | public $_options; |
| 192 | |
| 193 | /** |
| 194 | * Are we in search mode. |
| 195 | * |
| 196 | * @var boolean |
| 197 | */ |
| 198 | public $_search = TRUE; |
| 199 | |
| 200 | /** |
| 201 | * Should we skip permission checking. |
| 202 | * |
| 203 | * @var boolean |
| 204 | */ |
| 205 | public $_skipPermission = FALSE; |
| 206 | |
| 207 | /** |
| 208 | * Should we skip adding of delete clause. |
| 209 | * |
| 210 | * @var boolean |
| 211 | */ |
| 212 | public $_skipDeleteClause = FALSE; |
| 213 | |
| 214 | /** |
| 215 | * Are we in strict mode (use equality over LIKE) |
| 216 | * |
| 217 | * @var boolean |
| 218 | */ |
| 219 | public $_strict = FALSE; |
| 220 | |
| 221 | /** |
| 222 | * What operator to use to group the clauses. |
| 223 | * |
| 224 | * @var string |
| 225 | */ |
| 226 | public $_operator = 'AND'; |
| 227 | |
| 228 | public $_mode = 1; |
| 229 | |
| 230 | /** |
| 231 | * Should we only search on primary location. |
| 232 | * |
| 233 | * @var boolean |
| 234 | */ |
| 235 | public $_primaryLocation = TRUE; |
| 236 | |
| 237 | /** |
| 238 | * Are contact ids part of the query. |
| 239 | * |
| 240 | * @var boolean |
| 241 | */ |
| 242 | public $_includeContactIds = FALSE; |
| 243 | |
| 244 | /** |
| 245 | * Should we use the smart group cache. |
| 246 | * |
| 247 | * @var boolean |
| 248 | */ |
| 249 | public $_smartGroupCache = TRUE; |
| 250 | |
| 251 | /** |
| 252 | * Should we display contacts with a specific relationship type. |
| 253 | * |
| 254 | * @var string |
| 255 | */ |
| 256 | public $_displayRelationshipType = NULL; |
| 257 | |
| 258 | /** |
| 259 | * Reference to the query object for custom values. |
| 260 | * |
| 261 | * @var Object |
| 262 | */ |
| 263 | public $_customQuery; |
| 264 | |
| 265 | /** |
| 266 | * Should we enable the distinct clause, used if we are including |
| 267 | * more than one group |
| 268 | * |
| 269 | * @var boolean |
| 270 | */ |
| 271 | public $_useDistinct = FALSE; |
| 272 | |
| 273 | /** |
| 274 | * Should we just display one contact record |
| 275 | */ |
| 276 | public $_useGroupBy = FALSE; |
| 277 | |
| 278 | /** |
| 279 | * The relationship type direction |
| 280 | * |
| 281 | * @var array |
| 282 | */ |
| 283 | static $_relType; |
| 284 | |
| 285 | /** |
| 286 | * The activity role |
| 287 | * |
| 288 | * @var array |
| 289 | */ |
| 290 | static $_activityRole; |
| 291 | |
| 292 | /** |
| 293 | * Consider the component activity type |
| 294 | * during activity search. |
| 295 | * |
| 296 | * @var array |
| 297 | */ |
| 298 | static $_considerCompActivities; |
| 299 | |
| 300 | /** |
| 301 | * Consider with contact activities only, |
| 302 | * during activity search. |
| 303 | * |
| 304 | * @var array |
| 305 | */ |
| 306 | static $_withContactActivitiesOnly; |
| 307 | |
| 308 | /** |
| 309 | * Use distinct component clause for component searches |
| 310 | * |
| 311 | * @var string |
| 312 | */ |
| 313 | public $_distinctComponentClause; |
| 314 | |
| 315 | public $_rowCountClause; |
| 316 | |
| 317 | /** |
| 318 | * Use groupBy component clause for component searches |
| 319 | * |
| 320 | * @var string |
| 321 | */ |
| 322 | public $_groupByComponentClause; |
| 323 | |
| 324 | /** |
| 325 | * Track open panes, useful in advance search |
| 326 | * |
| 327 | * @var array |
| 328 | */ |
| 329 | public static $_openedPanes = array(); |
| 330 | |
| 331 | /** |
| 332 | * For search builder - which custom fields are location-dependent |
| 333 | * @var array |
| 334 | */ |
| 335 | public $_locationSpecificCustomFields = array(); |
| 336 | |
| 337 | /** |
| 338 | * The tables which have a dependency on location and/or address |
| 339 | * |
| 340 | * @var array |
| 341 | */ |
| 342 | static $_dependencies = array( |
| 343 | 'civicrm_state_province' => 1, |
| 344 | 'civicrm_country' => 1, |
| 345 | 'civicrm_county' => 1, |
| 346 | 'civicrm_address' => 1, |
| 347 | 'civicrm_location_type' => 1, |
| 348 | ); |
| 349 | |
| 350 | /** |
| 351 | * List of location specific fields. |
| 352 | */ |
| 353 | static $_locationSpecificFields = array( |
| 354 | 'street_address', |
| 355 | 'street_number', |
| 356 | 'street_name', |
| 357 | 'street_unit', |
| 358 | 'supplemental_address_1', |
| 359 | 'supplemental_address_2', |
| 360 | 'city', |
| 361 | 'postal_code', |
| 362 | 'postal_code_suffix', |
| 363 | 'geo_code_1', |
| 364 | 'geo_code_2', |
| 365 | 'state_province', |
| 366 | 'country', |
| 367 | 'county', |
| 368 | 'phone', |
| 369 | 'email', |
| 370 | 'im', |
| 371 | 'address_name', |
| 372 | 'master_id', |
| 373 | ); |
| 374 | |
| 375 | /** |
| 376 | * Remember if we handle either end of a number or date range |
| 377 | * so we can skip the other |
| 378 | */ |
| 379 | protected $_rangeCache = array(); |
| 380 | /** |
| 381 | * Set to true when $this->relationship is run to avoid adding twice |
| 382 | * @var Boolean |
| 383 | */ |
| 384 | protected $_relationshipValuesAdded = FALSE; |
| 385 | |
| 386 | /** |
| 387 | * Set to the name of the temp table if one has been created |
| 388 | * @var String |
| 389 | */ |
| 390 | static $_relationshipTempTable = NULL; |
| 391 | |
| 392 | public $_pseudoConstantsSelect = array(); |
| 393 | |
| 394 | /** |
| 395 | * Class constructor which also does all the work. |
| 396 | * |
| 397 | * @param array $params |
| 398 | * @param array $returnProperties |
| 399 | * @param array $fields |
| 400 | * @param bool $includeContactIds |
| 401 | * @param bool $strict |
| 402 | * @param bool|int $mode - mode the search is operating on |
| 403 | * |
| 404 | * @param bool $skipPermission |
| 405 | * @param bool $searchDescendentGroups |
| 406 | * @param bool $smartGroupCache |
| 407 | * @param null $displayRelationshipType |
| 408 | * @param string $operator |
| 409 | * @param string $apiEntity |
| 410 | * |
| 411 | * @return \CRM_Contact_BAO_Query |
| 412 | */ |
| 413 | public function __construct( |
| 414 | $params = NULL, $returnProperties = NULL, $fields = NULL, |
| 415 | $includeContactIds = FALSE, $strict = FALSE, $mode = 1, |
| 416 | $skipPermission = FALSE, $searchDescendentGroups = TRUE, |
| 417 | $smartGroupCache = TRUE, $displayRelationshipType = NULL, |
| 418 | $operator = 'AND', |
| 419 | $apiEntity = NULL |
| 420 | ) { |
| 421 | $this->_params = &$params; |
| 422 | if ($this->_params == NULL) { |
| 423 | $this->_params = array(); |
| 424 | } |
| 425 | |
| 426 | if ($returnProperties === self::NO_RETURN_PROPERTIES) { |
| 427 | $this->_returnProperties = array(); |
| 428 | } |
| 429 | elseif (empty($returnProperties)) { |
| 430 | $this->_returnProperties = self::defaultReturnProperties($mode); |
| 431 | } |
| 432 | else { |
| 433 | $this->_returnProperties = &$returnProperties; |
| 434 | } |
| 435 | |
| 436 | $this->_includeContactIds = $includeContactIds; |
| 437 | $this->_strict = $strict; |
| 438 | $this->_mode = $mode; |
| 439 | $this->_skipPermission = $skipPermission; |
| 440 | $this->_smartGroupCache = $smartGroupCache; |
| 441 | $this->_displayRelationshipType = $displayRelationshipType; |
| 442 | $this->setOperator($operator); |
| 443 | |
| 444 | if ($fields) { |
| 445 | $this->_fields = &$fields; |
| 446 | $this->_search = FALSE; |
| 447 | $this->_skipPermission = TRUE; |
| 448 | } |
| 449 | else { |
| 450 | $this->_fields = CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE, TRUE, FALSE, !$skipPermission); |
| 451 | |
| 452 | $fields = CRM_Core_Component::getQueryFields(!$this->_skipPermission); |
| 453 | unset($fields['note']); |
| 454 | $this->_fields = array_merge($this->_fields, $fields); |
| 455 | |
| 456 | // add activity fields |
| 457 | $fields = CRM_Activity_BAO_Activity::exportableFields(); |
| 458 | $this->_fields = array_merge($this->_fields, $fields); |
| 459 | |
| 460 | // add any fields provided by hook implementers |
| 461 | $extFields = CRM_Contact_BAO_Query_Hook::singleton()->getFields(); |
| 462 | $this->_fields = array_merge($this->_fields, $extFields); |
| 463 | } |
| 464 | |
| 465 | // basically do all the work once, and then reuse it |
| 466 | $this->initialize($apiEntity); |
| 467 | } |
| 468 | |
| 469 | /** |
| 470 | * Function which actually does all the work for the constructor. |
| 471 | */ |
| 472 | public function initialize($apiEntity = NULL) { |
| 473 | $this->_select = array(); |
| 474 | $this->_element = array(); |
| 475 | $this->_tables = array(); |
| 476 | $this->_whereTables = array(); |
| 477 | $this->_where = array(); |
| 478 | $this->_qill = array(); |
| 479 | $this->_options = array(); |
| 480 | $this->_cfIDs = array(); |
| 481 | $this->_paramLookup = array(); |
| 482 | $this->_having = array(); |
| 483 | |
| 484 | $this->_customQuery = NULL; |
| 485 | |
| 486 | // reset cached static variables - CRM-5803 |
| 487 | self::$_activityRole = NULL; |
| 488 | self::$_considerCompActivities = NULL; |
| 489 | self::$_withContactActivitiesOnly = NULL; |
| 490 | |
| 491 | $this->_select['contact_id'] = 'contact_a.id as contact_id'; |
| 492 | $this->_element['contact_id'] = 1; |
| 493 | $this->_tables['civicrm_contact'] = 1; |
| 494 | |
| 495 | if (!empty($this->_params)) { |
| 496 | $this->buildParamsLookup(); |
| 497 | } |
| 498 | |
| 499 | $this->_whereTables = $this->_tables; |
| 500 | |
| 501 | $this->selectClause($apiEntity); |
| 502 | $this->_whereClause = $this->whereClause($apiEntity); |
| 503 | if (array_key_exists('civicrm_contribution', $this->_whereTables)) { |
| 504 | $component = 'contribution'; |
| 505 | } |
| 506 | if (array_key_exists('civicrm_membership', $this->_whereTables)) { |
| 507 | $component = 'membership'; |
| 508 | } |
| 509 | if (isset($component)) { |
| 510 | CRM_Financial_BAO_FinancialType::buildPermissionedClause($this->_whereClause, $component); |
| 511 | } |
| 512 | |
| 513 | $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode); |
| 514 | $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode); |
| 515 | |
| 516 | $this->openedSearchPanes(TRUE); |
| 517 | } |
| 518 | |
| 519 | /** |
| 520 | * Function for same purpose as convertFormValues. |
| 521 | * |
| 522 | * Like convert form values this function exists to pre-Process parameters from the form. |
| 523 | * |
| 524 | * It is unclear why they are different functions & likely relates to advances search |
| 525 | * versus search builder. |
| 526 | * |
| 527 | * The direction we are going is having the form convert values to a standardised format & |
| 528 | * moving away from wierd & wonderful where clause switches. |
| 529 | * |
| 530 | * Fix and handle contact deletion nicely. |
| 531 | * |
| 532 | * this code is primarily for search builder use case where different clauses can specify if they want deleted. |
| 533 | * |
| 534 | * CRM-11971 |
| 535 | */ |
| 536 | public function buildParamsLookup() { |
| 537 | $trashParamExists = FALSE; |
| 538 | $paramByGroup = array(); |
| 539 | foreach ($this->_params as $k => $param) { |
| 540 | if (!empty($param[0]) && $param[0] == 'contact_is_deleted') { |
| 541 | $trashParamExists = TRUE; |
| 542 | } |
| 543 | if (!empty($param[3])) { |
| 544 | $paramByGroup[$param[3]][$k] = $param; |
| 545 | } |
| 546 | } |
| 547 | |
| 548 | if ($trashParamExists) { |
| 549 | $this->_skipDeleteClause = TRUE; |
| 550 | |
| 551 | //cycle through group sets and explicitly add trash param if not set |
| 552 | foreach ($paramByGroup as $setID => $set) { |
| 553 | if ( |
| 554 | !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params) && |
| 555 | !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params) |
| 556 | ) { |
| 557 | $this->_params[] = array( |
| 558 | 'contact_is_deleted', |
| 559 | '=', |
| 560 | '0', |
| 561 | $setID, |
| 562 | '0', |
| 563 | ); |
| 564 | } |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | foreach ($this->_params as $value) { |
| 569 | if (empty($value[0])) { |
| 570 | continue; |
| 571 | } |
| 572 | $cfID = CRM_Core_BAO_CustomField::getKeyID($value[0]); |
| 573 | if ($cfID) { |
| 574 | if (!array_key_exists($cfID, $this->_cfIDs)) { |
| 575 | $this->_cfIDs[$cfID] = array(); |
| 576 | } |
| 577 | // Set wildcard value based on "and/or" selection |
| 578 | foreach ($this->_params as $key => $param) { |
| 579 | if ($param[0] == $value[0] . '_operator') { |
| 580 | $value[4] = $param[2] == 'or'; |
| 581 | break; |
| 582 | } |
| 583 | } |
| 584 | $this->_cfIDs[$cfID][] = $value; |
| 585 | } |
| 586 | |
| 587 | if (!array_key_exists($value[0], $this->_paramLookup)) { |
| 588 | $this->_paramLookup[$value[0]] = array(); |
| 589 | } |
| 590 | if ($value[0] !== 'group') { |
| 591 | // Just trying to unravel how group interacts here! This whole function is wieid. |
| 592 | $this->_paramLookup[$value[0]][] = $value; |
| 593 | } |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | /** |
| 598 | * Some composite fields do not appear in the fields array hack to make them part of the query. |
| 599 | */ |
| 600 | public function addSpecialFields($apiEntity) { |
| 601 | static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name'); |
| 602 | // if get called via Contact.get API having address_id as return parameter |
| 603 | if ($apiEntity == 'Contact') { |
| 604 | $special[] = 'address_id'; |
| 605 | } |
| 606 | foreach ($special as $name) { |
| 607 | if (!empty($this->_returnProperties[$name])) { |
| 608 | if ($name == 'address_id') { |
| 609 | $this->_tables['civicrm_address'] = 1; |
| 610 | $this->_select['address_id'] = 'civicrm_address.id as address_id'; |
| 611 | $this->_element['address_id'] = 1; |
| 612 | } |
| 613 | else { |
| 614 | $this->_select[$name] = "contact_a.{$name} as $name"; |
| 615 | $this->_element[$name] = 1; |
| 616 | } |
| 617 | } |
| 618 | } |
| 619 | } |
| 620 | |
| 621 | /** |
| 622 | * Given a list of conditions in params and a list of desired |
| 623 | * return Properties generate the required select and from |
| 624 | * clauses. Note that since the where clause introduces new |
| 625 | * tables, the initial attempt also retrieves all variables used |
| 626 | * in the params list |
| 627 | */ |
| 628 | public function selectClause($apiEntity = NULL) { |
| 629 | |
| 630 | $this->addSpecialFields($apiEntity); |
| 631 | |
| 632 | foreach ($this->_fields as $name => $field) { |
| 633 | // skip component fields |
| 634 | // there are done by the alter query below |
| 635 | // and need not be done on every field |
| 636 | if ( |
| 637 | (substr($name, 0, 12) == 'participant_') || |
| 638 | (substr($name, 0, 7) == 'pledge_') || |
| 639 | (substr($name, 0, 5) == 'case_') || |
| 640 | (substr($name, 0, 13) == 'contribution_' && |
| 641 | (strpos($name, 'source') !== FALSE && strpos($name, 'recur') !== FALSE)) || |
| 642 | (substr($name, 0, 8) == 'payment_') |
| 643 | ) { |
| 644 | continue; |
| 645 | } |
| 646 | |
| 647 | // redirect to activity select clause |
| 648 | if ( |
| 649 | (substr($name, 0, 9) == 'activity_') || |
| 650 | ($name == 'parent_id') |
| 651 | ) { |
| 652 | CRM_Activity_BAO_Query::select($this); |
| 653 | continue; |
| 654 | } |
| 655 | |
| 656 | // if this is a hierarchical name, we ignore it |
| 657 | $names = explode('-', $name); |
| 658 | if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) { |
| 659 | continue; |
| 660 | } |
| 661 | |
| 662 | // make an exception for special cases, to add the field in select clause |
| 663 | $makeException = FALSE; |
| 664 | |
| 665 | //special handling for groups/tags |
| 666 | if (in_array($name, array('groups', 'tags', 'notes')) |
| 667 | && isset($this->_returnProperties[substr($name, 0, -1)]) |
| 668 | ) { |
| 669 | $makeException = TRUE; |
| 670 | } |
| 671 | |
| 672 | // since note has 3 different options we need special handling |
| 673 | // note / note_subject / note_body |
| 674 | if ($name == 'notes') { |
| 675 | foreach (array('note', 'note_subject', 'note_body') as $noteField) { |
| 676 | if (isset($this->_returnProperties[$noteField])) { |
| 677 | $makeException = TRUE; |
| 678 | break; |
| 679 | } |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id', 'communication_style_id'))) { |
| 684 | if (CRM_Utils_Array::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties)) { |
| 685 | $makeException = TRUE; |
| 686 | } |
| 687 | } |
| 688 | |
| 689 | $cfID = CRM_Core_BAO_CustomField::getKeyID($name); |
| 690 | if (!empty($this->_paramLookup[$name]) || !empty($this->_returnProperties[$name]) || |
| 691 | $makeException |
| 692 | ) { |
| 693 | if ($cfID) { |
| 694 | // add to cfIDs array if not present |
| 695 | if (!array_key_exists($cfID, $this->_cfIDs)) { |
| 696 | $this->_cfIDs[$cfID] = array(); |
| 697 | } |
| 698 | } |
| 699 | elseif (isset($field['where'])) { |
| 700 | list($tableName, $fieldName) = explode('.', $field['where'], 2); |
| 701 | if (isset($tableName)) { |
| 702 | if (CRM_Utils_Array::value($tableName, self::$_dependencies)) { |
| 703 | $this->_tables['civicrm_address'] = 1; |
| 704 | $this->_select['address_id'] = 'civicrm_address.id as address_id'; |
| 705 | $this->_element['address_id'] = 1; |
| 706 | } |
| 707 | |
| 708 | if ($tableName == 'im_provider' || $tableName == 'email_greeting' || |
| 709 | $tableName == 'postal_greeting' || $tableName == 'addressee' |
| 710 | ) { |
| 711 | if ($tableName == 'im_provider') { |
| 712 | CRM_Core_OptionValue::select($this); |
| 713 | } |
| 714 | |
| 715 | if (in_array($tableName, |
| 716 | array('email_greeting', 'postal_greeting', 'addressee'))) { |
| 717 | $this->_element["{$name}_id"] = 1; |
| 718 | $this->_select["{$name}_id"] = "contact_a.{$name}_id as {$name}_id"; |
| 719 | $this->_pseudoConstantsSelect[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id"); |
| 720 | $this->_pseudoConstantsSelect[$name]['select'] = "{$name}.{$fieldName} as $name"; |
| 721 | $this->_pseudoConstantsSelect[$name]['element'] = $name; |
| 722 | |
| 723 | if ($tableName == 'email_greeting') { |
| 724 | $this->_pseudoConstantsSelect[$name]['join'] |
| 725 | = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')"; |
| 726 | $this->_pseudoConstantsSelect[$name]['join'] .= |
| 727 | " LEFT JOIN civicrm_option_value email_greeting ON (contact_a.email_greeting_id = email_greeting.value AND option_group_email_greeting.id = email_greeting.option_group_id ) "; |
| 728 | } |
| 729 | elseif ($tableName == 'postal_greeting') { |
| 730 | $this->_pseudoConstantsSelect[$name]['join'] |
| 731 | = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')"; |
| 732 | $this->_pseudoConstantsSelect[$name]['join'] .= |
| 733 | " LEFT JOIN civicrm_option_value postal_greeting ON (contact_a.postal_greeting_id = postal_greeting.value AND option_group_postal_greeting.id = postal_greeting.option_group_id ) "; |
| 734 | } |
| 735 | elseif ($tableName == 'addressee') { |
| 736 | $this->_pseudoConstantsSelect[$name]['join'] |
| 737 | = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')"; |
| 738 | $this->_pseudoConstantsSelect[$name]['join'] .= |
| 739 | " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) "; |
| 740 | } |
| 741 | $this->_pseudoConstantsSelect[$name]['table'] = $tableName; |
| 742 | |
| 743 | //get display |
| 744 | $greetField = "{$name}_display"; |
| 745 | $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}"; |
| 746 | $this->_element[$greetField] = 1; |
| 747 | //get custom |
| 748 | $greetField = "{$name}_custom"; |
| 749 | $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}"; |
| 750 | $this->_element[$greetField] = 1; |
| 751 | } |
| 752 | } |
| 753 | else { |
| 754 | if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) { |
| 755 | $this->_tables[$tableName] = 1; |
| 756 | } |
| 757 | |
| 758 | // also get the id of the tableName |
| 759 | $tName = substr($tableName, 8); |
| 760 | if (in_array($tName, array('country', 'state_province', 'county'))) { |
| 761 | if ($tName == 'state_province') { |
| 762 | $this->_pseudoConstantsSelect['state_province_name'] = array( |
| 763 | 'pseudoField' => "{$tName}", |
| 764 | 'idCol' => "{$tName}_id", |
| 765 | 'bao' => 'CRM_Core_BAO_Address', |
| 766 | 'table' => "civicrm_{$tName}", |
| 767 | 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ", |
| 768 | ); |
| 769 | |
| 770 | $this->_pseudoConstantsSelect[$tName] = array( |
| 771 | 'pseudoField' => 'state_province_abbreviation', |
| 772 | 'idCol' => "{$tName}_id", |
| 773 | 'table' => "civicrm_{$tName}", |
| 774 | 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ", |
| 775 | ); |
| 776 | } |
| 777 | else { |
| 778 | $this->_pseudoConstantsSelect[$name] = array( |
| 779 | 'pseudoField' => "{$tName}_id", |
| 780 | 'idCol' => "{$tName}_id", |
| 781 | 'bao' => 'CRM_Core_BAO_Address', |
| 782 | 'table' => "civicrm_{$tName}", |
| 783 | 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ", |
| 784 | ); |
| 785 | } |
| 786 | |
| 787 | $this->_select["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id"; |
| 788 | $this->_element["{$tName}_id"] = 1; |
| 789 | } |
| 790 | elseif ($tName != 'contact') { |
| 791 | $this->_select["{$tName}_id"] = "{$tableName}.id as {$tName}_id"; |
| 792 | $this->_element["{$tName}_id"] = 1; |
| 793 | } |
| 794 | |
| 795 | //special case for phone |
| 796 | if ($name == 'phone') { |
| 797 | $this->_select['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id"; |
| 798 | $this->_element['phone_type_id'] = 1; |
| 799 | } |
| 800 | |
| 801 | // if IM then select provider_id also |
| 802 | // to get "IM Service Provider" in a file to be exported, CRM-3140 |
| 803 | if ($name == 'im') { |
| 804 | $this->_select['provider_id'] = "civicrm_im.provider_id as provider_id"; |
| 805 | $this->_element['provider_id'] = 1; |
| 806 | } |
| 807 | |
| 808 | if ($tName == 'contact') { |
| 809 | // special case, when current employer is set for Individual contact |
| 810 | if ($fieldName == 'organization_name') { |
| 811 | $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name"; |
| 812 | } |
| 813 | elseif ($fieldName != 'id') { |
| 814 | if ($fieldName == 'prefix_id') { |
| 815 | $this->_pseudoConstantsSelect['individual_prefix'] = array( |
| 816 | 'pseudoField' => 'prefix_id', |
| 817 | 'idCol' => "prefix_id", |
| 818 | 'bao' => 'CRM_Contact_BAO_Contact', |
| 819 | ); |
| 820 | } |
| 821 | if ($fieldName == 'suffix_id') { |
| 822 | $this->_pseudoConstantsSelect['individual_suffix'] = array( |
| 823 | 'pseudoField' => 'suffix_id', |
| 824 | 'idCol' => "suffix_id", |
| 825 | 'bao' => 'CRM_Contact_BAO_Contact', |
| 826 | ); |
| 827 | } |
| 828 | if ($fieldName == 'gender_id') { |
| 829 | $this->_pseudoConstantsSelect['gender'] = array( |
| 830 | 'pseudoField' => 'gender_id', |
| 831 | 'idCol' => "gender_id", |
| 832 | 'bao' => 'CRM_Contact_BAO_Contact', |
| 833 | ); |
| 834 | } |
| 835 | if ($name == 'communication_style_id') { |
| 836 | $this->_pseudoConstantsSelect['communication_style'] = array( |
| 837 | 'pseudoField' => 'communication_style_id', |
| 838 | 'idCol' => "communication_style_id", |
| 839 | 'bao' => 'CRM_Contact_BAO_Contact', |
| 840 | ); |
| 841 | } |
| 842 | $this->_select[$name] = "contact_a.{$fieldName} as `$name`"; |
| 843 | } |
| 844 | } |
| 845 | elseif (in_array($tName, array('country', 'county'))) { |
| 846 | $this->_pseudoConstantsSelect[$name]['select'] = "{$field['where']} as `$name`"; |
| 847 | $this->_pseudoConstantsSelect[$name]['element'] = $name; |
| 848 | } |
| 849 | elseif ($tName == 'state_province') { |
| 850 | $this->_pseudoConstantsSelect[$tName]['select'] = "{$field['where']} as `$name`"; |
| 851 | $this->_pseudoConstantsSelect[$tName]['element'] = $name; |
| 852 | } |
| 853 | elseif (strpos($name, 'contribution_soft_credit') !== FALSE) { |
| 854 | if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled($this->_params)) { |
| 855 | $this->_select[$name] = "{$field['where']} as `$name`"; |
| 856 | } |
| 857 | } |
| 858 | else { |
| 859 | $this->_select[$name] = "{$field['where']} as `$name`"; |
| 860 | } |
| 861 | if (!in_array($tName, array('state_province', 'country', 'county'))) { |
| 862 | $this->_element[$name] = 1; |
| 863 | } |
| 864 | } |
| 865 | } |
| 866 | } |
| 867 | elseif ($name === 'tags') { |
| 868 | $this->_useGroupBy = TRUE; |
| 869 | $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags"; |
| 870 | $this->_element[$name] = 1; |
| 871 | $this->_tables['civicrm_tag'] = 1; |
| 872 | $this->_tables['civicrm_entity_tag'] = 1; |
| 873 | } |
| 874 | elseif ($name === 'groups') { |
| 875 | $this->_useGroupBy = TRUE; |
| 876 | // Duplicates will be created here but better to sort them out in php land. |
| 877 | $this->_select[$name] = " |
| 878 | CONCAT_WS(',', |
| 879 | GROUP_CONCAT(DISTINCT IF(civicrm_group_contact.status = 'Added', civicrm_group_contact.group_id, '')), |
| 880 | GROUP_CONCAT(DISTINCT civicrm_group_contact_cache.group_id) |
| 881 | ) |
| 882 | as groups"; |
| 883 | $this->_element[$name] = 1; |
| 884 | $this->_tables['civicrm_group_contact'] = 1; |
| 885 | $this->_tables['civicrm_group_contact_cache'] = 1; |
| 886 | $this->_pseudoConstantsSelect["{$name}"] = array( |
| 887 | 'pseudoField' => "groups", |
| 888 | 'idCol' => "groups", |
| 889 | ); |
| 890 | } |
| 891 | elseif ($name === 'notes') { |
| 892 | // if note field is subject then return subject else body of the note |
| 893 | $noteColumn = 'note'; |
| 894 | if (isset($noteField) && $noteField == 'note_subject') { |
| 895 | $noteColumn = 'subject'; |
| 896 | } |
| 897 | |
| 898 | $this->_useGroupBy = TRUE; |
| 899 | $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes"; |
| 900 | $this->_element[$name] = 1; |
| 901 | $this->_tables['civicrm_note'] = 1; |
| 902 | } |
| 903 | elseif ($name === 'current_employer') { |
| 904 | $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer"; |
| 905 | $this->_element[$name] = 1; |
| 906 | } |
| 907 | } |
| 908 | |
| 909 | if ($cfID && !empty($field['is_search_range'])) { |
| 910 | // this is a custom field with range search enabled, so we better check for two/from values |
| 911 | if (!empty($this->_paramLookup[$name . '_from'])) { |
| 912 | if (!array_key_exists($cfID, $this->_cfIDs)) { |
| 913 | $this->_cfIDs[$cfID] = array(); |
| 914 | } |
| 915 | foreach ($this->_paramLookup[$name . '_from'] as $pID => $p) { |
| 916 | // search in the cdID array for the same grouping |
| 917 | $fnd = FALSE; |
| 918 | foreach ($this->_cfIDs[$cfID] as $cID => $c) { |
| 919 | if ($c[3] == $p[3]) { |
| 920 | $this->_cfIDs[$cfID][$cID][2]['from'] = $p[2]; |
| 921 | $fnd = TRUE; |
| 922 | } |
| 923 | } |
| 924 | if (!$fnd) { |
| 925 | $p[2] = array('from' => $p[2]); |
| 926 | $this->_cfIDs[$cfID][] = $p; |
| 927 | } |
| 928 | } |
| 929 | } |
| 930 | if (!empty($this->_paramLookup[$name . '_to'])) { |
| 931 | if (!array_key_exists($cfID, $this->_cfIDs)) { |
| 932 | $this->_cfIDs[$cfID] = array(); |
| 933 | } |
| 934 | foreach ($this->_paramLookup[$name . '_to'] as $pID => $p) { |
| 935 | // search in the cdID array for the same grouping |
| 936 | $fnd = FALSE; |
| 937 | foreach ($this->_cfIDs[$cfID] as $cID => $c) { |
| 938 | if ($c[4] == $p[4]) { |
| 939 | $this->_cfIDs[$cfID][$cID][2]['to'] = $p[2]; |
| 940 | $fnd = TRUE; |
| 941 | } |
| 942 | } |
| 943 | if (!$fnd) { |
| 944 | $p[2] = array('to' => $p[2]); |
| 945 | $this->_cfIDs[$cfID][] = $p; |
| 946 | } |
| 947 | } |
| 948 | } |
| 949 | } |
| 950 | } |
| 951 | |
| 952 | // add location as hierarchical elements |
| 953 | $this->addHierarchicalElements(); |
| 954 | |
| 955 | // add multiple field like website |
| 956 | $this->addMultipleElements(); |
| 957 | |
| 958 | //fix for CRM-951 |
| 959 | CRM_Core_Component::alterQuery($this, 'select'); |
| 960 | |
| 961 | CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'select'); |
| 962 | |
| 963 | if (!empty($this->_cfIDs)) { |
| 964 | // @todo This function is the select function but instead of running 'select' it |
| 965 | // is running the whole query. |
| 966 | $this->_customQuery = new CRM_Core_BAO_CustomQuery($this->_cfIDs, TRUE, $this->_locationSpecificCustomFields); |
| 967 | $this->_customQuery->query(); |
| 968 | $this->_select = array_merge($this->_select, $this->_customQuery->_select); |
| 969 | $this->_element = array_merge($this->_element, $this->_customQuery->_element); |
| 970 | $this->_tables = array_merge($this->_tables, $this->_customQuery->_tables); |
| 971 | $this->_whereTables = array_merge($this->_whereTables, $this->_customQuery->_whereTables); |
| 972 | $this->_options = $this->_customQuery->_options; |
| 973 | } |
| 974 | } |
| 975 | |
| 976 | /** |
| 977 | * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values. |
| 978 | */ |
| 979 | public function addHierarchicalElements() { |
| 980 | if (empty($this->_returnProperties['location'])) { |
| 981 | return; |
| 982 | } |
| 983 | if (!is_array($this->_returnProperties['location'])) { |
| 984 | return; |
| 985 | } |
| 986 | |
| 987 | $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); |
| 988 | $processed = array(); |
| 989 | $index = 0; |
| 990 | |
| 991 | $addressCustomFields = CRM_Core_BAO_CustomField::getFieldsForImport('Address'); |
| 992 | $addressCustomFieldIds = array(); |
| 993 | |
| 994 | foreach ($this->_returnProperties['location'] as $name => $elements) { |
| 995 | $lCond = self::getPrimaryCondition($name); |
| 996 | |
| 997 | if (!$lCond) { |
| 998 | $locationTypeId = array_search($name, $locationTypes); |
| 999 | if ($locationTypeId === FALSE) { |
| 1000 | continue; |
| 1001 | } |
| 1002 | $lCond = "location_type_id = $locationTypeId"; |
| 1003 | $this->_useDistinct = TRUE; |
| 1004 | |
| 1005 | //commented for CRM-3256 |
| 1006 | $this->_useGroupBy = TRUE; |
| 1007 | } |
| 1008 | |
| 1009 | $name = str_replace(' ', '_', $name); |
| 1010 | |
| 1011 | $tName = "$name-location_type"; |
| 1012 | $ltName = "`$name-location_type`"; |
| 1013 | $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`"; |
| 1014 | $this->_select["{$tName}"] = "`$tName`.name as `{$tName}`"; |
| 1015 | $this->_element["{$tName}_id"] = 1; |
| 1016 | $this->_element["{$tName}"] = 1; |
| 1017 | |
| 1018 | $locationTypeName = $tName; |
| 1019 | $locationTypeJoin = array(); |
| 1020 | |
| 1021 | $addAddress = FALSE; |
| 1022 | $addWhereCount = 0; |
| 1023 | foreach ($elements as $elementFullName => $dontCare) { |
| 1024 | $index++; |
| 1025 | $elementName = $elementCmpName = $elementFullName; |
| 1026 | |
| 1027 | if (substr($elementCmpName, 0, 5) == 'phone') { |
| 1028 | $elementCmpName = 'phone'; |
| 1029 | } |
| 1030 | |
| 1031 | if (in_array($elementCmpName, array_keys($addressCustomFields))) { |
| 1032 | if ($cfID = CRM_Core_BAO_CustomField::getKeyID($elementCmpName)) { |
| 1033 | $addressCustomFieldIds[$cfID][$name] = 1; |
| 1034 | } |
| 1035 | } |
| 1036 | //add address table only once |
| 1037 | if ((in_array($elementCmpName, self::$_locationSpecificFields) || !empty($addressCustomFieldIds)) |
| 1038 | && !$addAddress |
| 1039 | && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid')) |
| 1040 | ) { |
| 1041 | $tName = "$name-address"; |
| 1042 | $aName = "`$name-address`"; |
| 1043 | $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`"; |
| 1044 | $this->_element["{$tName}_id"] = 1; |
| 1045 | $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)"; |
| 1046 | $this->_tables[$tName] = $addressJoin; |
| 1047 | $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) "; |
| 1048 | $processed[$aName] = 1; |
| 1049 | $addAddress = TRUE; |
| 1050 | } |
| 1051 | |
| 1052 | $cond = $elementType = ''; |
| 1053 | if (strpos($elementName, '-') !== FALSE) { |
| 1054 | // this is either phone, email or IM |
| 1055 | list($elementName, $elementType) = explode('-', $elementName); |
| 1056 | |
| 1057 | if (($elementName != 'phone') && ($elementName != 'im')) { |
| 1058 | $cond = self::getPrimaryCondition($elementType); |
| 1059 | } |
| 1060 | // CRM-13011 : If location type is primary, do not restrict search to the phone |
| 1061 | // type id - we want the primary phone, regardless of what type it is. |
| 1062 | // Otherwise, restrict to the specified phone type for the given field. |
| 1063 | if ((!$cond) && ($elementName == 'phone')) { |
| 1064 | $cond = "phone_type_id = '$elementType'"; |
| 1065 | } |
| 1066 | elseif ((!$cond) && ($elementName == 'im')) { |
| 1067 | // IM service provider id, CRM-3140 |
| 1068 | $cond = "provider_id = '$elementType'"; |
| 1069 | } |
| 1070 | $elementType = '-' . $elementType; |
| 1071 | } |
| 1072 | |
| 1073 | $field = CRM_Utils_Array::value($elementName, $this->_fields); |
| 1074 | |
| 1075 | // hack for profile, add location id |
| 1076 | if (!$field) { |
| 1077 | if ($elementType && |
| 1078 | // fix for CRM-882( to handle phone types ) |
| 1079 | !is_numeric($elementType) |
| 1080 | ) { |
| 1081 | if (is_numeric($name)) { |
| 1082 | $field = CRM_Utils_Array::value($elementName . "-Primary$elementType", $this->_fields); |
| 1083 | } |
| 1084 | else { |
| 1085 | $field = CRM_Utils_Array::value($elementName . "-$locationTypeId$elementType", $this->_fields); |
| 1086 | } |
| 1087 | } |
| 1088 | elseif (is_numeric($name)) { |
| 1089 | //this for phone type to work |
| 1090 | if (in_array($elementName, array('phone', 'phone_ext'))) { |
| 1091 | $field = CRM_Utils_Array::value($elementName . "-Primary" . $elementType, $this->_fields); |
| 1092 | } |
| 1093 | else { |
| 1094 | $field = CRM_Utils_Array::value($elementName . "-Primary", $this->_fields); |
| 1095 | } |
| 1096 | } |
| 1097 | else { |
| 1098 | //this is for phone type to work for profile edit |
| 1099 | if (in_array($elementName, array('phone', 'phone_ext'))) { |
| 1100 | $field = CRM_Utils_Array::value($elementName . "-$locationTypeId$elementType", $this->_fields); |
| 1101 | } |
| 1102 | else { |
| 1103 | $field = CRM_Utils_Array::value($elementName . "-$locationTypeId", $this->_fields); |
| 1104 | } |
| 1105 | } |
| 1106 | } |
| 1107 | |
| 1108 | // Check if there is a value, if so also add to where Clause |
| 1109 | $addWhere = FALSE; |
| 1110 | if ($this->_params) { |
| 1111 | $nm = $elementName; |
| 1112 | if (isset($locationTypeId)) { |
| 1113 | $nm .= "-$locationTypeId"; |
| 1114 | } |
| 1115 | if (!is_numeric($elementType)) { |
| 1116 | $nm .= "$elementType"; |
| 1117 | } |
| 1118 | |
| 1119 | foreach ($this->_params as $id => $values) { |
| 1120 | if ((is_array($values) && $values[0] == $nm) || |
| 1121 | (in_array($elementName, array('phone', 'im')) |
| 1122 | && (strpos($values[0], $nm) !== FALSE) |
| 1123 | ) |
| 1124 | ) { |
| 1125 | $addWhere = TRUE; |
| 1126 | $addWhereCount++; |
| 1127 | break; |
| 1128 | } |
| 1129 | } |
| 1130 | } |
| 1131 | |
| 1132 | if ($field && isset($field['where'])) { |
| 1133 | list($tableName, $fieldName) = explode('.', $field['where'], 2); |
| 1134 | $pf = substr($tableName, 8); |
| 1135 | $tName = $name . '-' . $pf . $elementType; |
| 1136 | if (isset($tableName)) { |
| 1137 | if ($tableName == 'civicrm_state_province' || $tableName == 'civicrm_country' || $tableName == 'civicrm_county') { |
| 1138 | $this->_select["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`"; |
| 1139 | } |
| 1140 | else { |
| 1141 | $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`"; |
| 1142 | } |
| 1143 | |
| 1144 | $this->_element["{$tName}_id"] = 1; |
| 1145 | if (substr($tName, -15) == '-state_province') { |
| 1146 | // FIXME: hack to fix CRM-1900 |
| 1147 | $a = Civi::settings()->get('address_format'); |
| 1148 | |
| 1149 | if (substr_count($a, 'state_province_name') > 0) { |
| 1150 | $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = array( |
| 1151 | 'pseudoField' => "{$pf}_id", |
| 1152 | 'idCol' => "{$tName}_id", |
| 1153 | 'bao' => 'CRM_Core_BAO_Address', |
| 1154 | ); |
| 1155 | $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`"; |
| 1156 | } |
| 1157 | else { |
| 1158 | $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = array( |
| 1159 | 'pseudoField' => 'state_province_abbreviation', |
| 1160 | 'idCol' => "{$tName}_id", |
| 1161 | ); |
| 1162 | $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`"; |
| 1163 | } |
| 1164 | } |
| 1165 | else { |
| 1166 | if (substr($elementFullName, 0, 2) == 'im') { |
| 1167 | $provider = "{$name}-{$elementFullName}-provider_id"; |
| 1168 | $this->_select[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`"; |
| 1169 | $this->_element[$provider] = 1; |
| 1170 | } |
| 1171 | if ($pf == 'country' || $pf == 'county') { |
| 1172 | $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = array( |
| 1173 | 'pseudoField' => "{$pf}_id", |
| 1174 | 'idCol' => "{$tName}_id", |
| 1175 | 'bao' => 'CRM_Core_BAO_Address', |
| 1176 | ); |
| 1177 | $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`"; |
| 1178 | } |
| 1179 | else { |
| 1180 | $this->_select["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`"; |
| 1181 | } |
| 1182 | } |
| 1183 | |
| 1184 | if (in_array($pf, array('state_province', 'country', 'county'))) { |
| 1185 | $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}"; |
| 1186 | } |
| 1187 | else { |
| 1188 | $this->_element["{$name}-{$elementFullName}"] = 1; |
| 1189 | } |
| 1190 | |
| 1191 | if (empty($processed["`$tName`"])) { |
| 1192 | $processed["`$tName`"] = 1; |
| 1193 | $newName = $tableName . '_' . $index; |
| 1194 | switch ($tableName) { |
| 1195 | case 'civicrm_phone': |
| 1196 | case 'civicrm_email': |
| 1197 | case 'civicrm_im': |
| 1198 | case 'civicrm_openid': |
| 1199 | |
| 1200 | $this->_tables[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id"; |
| 1201 | if ($tableName != 'civicrm_phone') { |
| 1202 | $this->_tables[$tName] .= " AND `$tName`.$lCond"; |
| 1203 | } |
| 1204 | elseif (is_numeric($name)) { |
| 1205 | $this->_select[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`"; |
| 1206 | } |
| 1207 | |
| 1208 | // this special case to add phone type |
| 1209 | if ($cond) { |
| 1210 | $phoneTypeCondition = " AND `$tName`.$cond "; |
| 1211 | //gross hack to pickup corrupted data also, CRM-7603 |
| 1212 | if (strpos($cond, 'phone_type_id') !== FALSE) { |
| 1213 | $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) "; |
| 1214 | if (!empty($lCond)) { |
| 1215 | $phoneTypeCondition .= " AND ( `$tName`.$lCond ) "; |
| 1216 | } |
| 1217 | } |
| 1218 | $this->_tables[$tName] .= $phoneTypeCondition; |
| 1219 | } |
| 1220 | |
| 1221 | //build locationType join |
| 1222 | $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )"; |
| 1223 | |
| 1224 | if ($addWhere) { |
| 1225 | $this->_whereTables[$tName] = $this->_tables[$tName]; |
| 1226 | } |
| 1227 | break; |
| 1228 | |
| 1229 | case 'civicrm_state_province': |
| 1230 | $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['table'] = $tName; |
| 1231 | $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['join'] |
| 1232 | = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id"; |
| 1233 | if ($addWhere) { |
| 1234 | $this->_whereTables["{$name}-address"] = $addressJoin; |
| 1235 | } |
| 1236 | break; |
| 1237 | |
| 1238 | case 'civicrm_country': |
| 1239 | $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['table'] = $newName; |
| 1240 | $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['join'] |
| 1241 | = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id"; |
| 1242 | if ($addWhere) { |
| 1243 | $this->_whereTables["{$name}-address"] = $addressJoin; |
| 1244 | } |
| 1245 | break; |
| 1246 | |
| 1247 | case 'civicrm_county': |
| 1248 | $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['table'] = $newName; |
| 1249 | $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['join'] |
| 1250 | = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id"; |
| 1251 | if ($addWhere) { |
| 1252 | $this->_whereTables["{$name}-address"] = $addressJoin; |
| 1253 | } |
| 1254 | break; |
| 1255 | |
| 1256 | default: |
| 1257 | if ($addWhere) { |
| 1258 | $this->_whereTables["{$name}-address"] = $addressJoin; |
| 1259 | } |
| 1260 | break; |
| 1261 | } |
| 1262 | } |
| 1263 | } |
| 1264 | } |
| 1265 | } |
| 1266 | |
| 1267 | // add location type join |
| 1268 | $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )"; |
| 1269 | $this->_tables[$locationTypeName] = $ltypeJoin; |
| 1270 | |
| 1271 | // table should be present in $this->_whereTables, |
| 1272 | // to add its condition in location type join, CRM-3939. |
| 1273 | if ($addWhereCount) { |
| 1274 | $locClause = array(); |
| 1275 | foreach ($this->_whereTables as $tableName => $clause) { |
| 1276 | if (!empty($locationTypeJoin[$tableName])) { |
| 1277 | $locClause[] = $locationTypeJoin[$tableName]; |
| 1278 | } |
| 1279 | } |
| 1280 | |
| 1281 | if (!empty($locClause)) { |
| 1282 | $this->_whereTables[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )"; |
| 1283 | } |
| 1284 | } |
| 1285 | } |
| 1286 | |
| 1287 | if (!empty($addressCustomFieldIds)) { |
| 1288 | $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds); |
| 1289 | foreach ($addressCustomFieldIds as $cfID => $locTypeName) { |
| 1290 | foreach ($locTypeName as $name => $dnc) { |
| 1291 | $this->_locationSpecificCustomFields[$cfID] = array($name, array_search($name, $locationTypes)); |
| 1292 | $fieldName = "$name-custom_{$cfID}"; |
| 1293 | $tName = "$name-address-custom-{$cfID}"; |
| 1294 | $aName = "`$name-address-custom-{$cfID}`"; |
| 1295 | $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`"; |
| 1296 | $this->_element["{$tName}_id"] = 1; |
| 1297 | $this->_select[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`"; |
| 1298 | $this->_element[$fieldName] = 1; |
| 1299 | $this->_tables[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)"; |
| 1300 | } |
| 1301 | } |
| 1302 | } |
| 1303 | } |
| 1304 | |
| 1305 | /** |
| 1306 | * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values. |
| 1307 | */ |
| 1308 | public function addMultipleElements() { |
| 1309 | if (empty($this->_returnProperties['website'])) { |
| 1310 | return; |
| 1311 | } |
| 1312 | if (!is_array($this->_returnProperties['website'])) { |
| 1313 | return; |
| 1314 | } |
| 1315 | |
| 1316 | foreach ($this->_returnProperties['website'] as $key => $elements) { |
| 1317 | foreach ($elements as $elementFullName => $dontCare) { |
| 1318 | $tName = "website-{$key}-{$elementFullName}"; |
| 1319 | $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`"; |
| 1320 | $this->_select["{$tName}"] = "`$tName`.url as `{$tName}`"; |
| 1321 | $this->_element["{$tName}_id"] = 1; |
| 1322 | $this->_element["{$tName}"] = 1; |
| 1323 | |
| 1324 | $type = "website-{$key}-website_type_id"; |
| 1325 | $this->_select[$type] = "`$tName`.website_type_id as `{$type}`"; |
| 1326 | $this->_element[$type] = 1; |
| 1327 | $this->_tables[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )"; |
| 1328 | } |
| 1329 | } |
| 1330 | } |
| 1331 | |
| 1332 | /** |
| 1333 | * Generate the query based on what type of query we need. |
| 1334 | * |
| 1335 | * @param bool $count |
| 1336 | * @param bool $sortByChar |
| 1337 | * @param bool $groupContacts |
| 1338 | * @param bool $onlyDeleted |
| 1339 | * |
| 1340 | * @return array |
| 1341 | * sql query parts as an array |
| 1342 | */ |
| 1343 | public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) { |
| 1344 | // build permission clause |
| 1345 | $this->generatePermissionClause($onlyDeleted, $count); |
| 1346 | |
| 1347 | if ($count) { |
| 1348 | if (isset($this->_rowCountClause)) { |
| 1349 | $select = "SELECT {$this->_rowCountClause}"; |
| 1350 | } |
| 1351 | elseif (isset($this->_distinctComponentClause)) { |
| 1352 | // we add distinct to get the right count for components |
| 1353 | // for the more complex result set, we use GROUP BY the same id |
| 1354 | // CRM-9630 |
| 1355 | $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} ) as rowCount"; |
| 1356 | } |
| 1357 | else { |
| 1358 | $select = 'SELECT count(DISTINCT contact_a.id) as rowCount'; |
| 1359 | } |
| 1360 | $from = $this->_simpleFromClause; |
| 1361 | if ($this->_useDistinct) { |
| 1362 | $this->_useGroupBy = TRUE; |
| 1363 | } |
| 1364 | } |
| 1365 | elseif ($sortByChar) { |
| 1366 | $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name'; |
| 1367 | $from = $this->_simpleFromClause; |
| 1368 | } |
| 1369 | elseif ($groupContacts) { |
| 1370 | $select = 'SELECT contact_a.id as id'; |
| 1371 | if ($this->_useDistinct) { |
| 1372 | $this->_useGroupBy = TRUE; |
| 1373 | } |
| 1374 | $from = $this->_simpleFromClause; |
| 1375 | } |
| 1376 | else { |
| 1377 | if (!empty($this->_paramLookup['group'])) { |
| 1378 | |
| 1379 | list($name, $op, $value, $grouping, $wildcard) = $this->_paramLookup['group'][0]; |
| 1380 | |
| 1381 | if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) { |
| 1382 | $this->_paramLookup['group'][0][1] = key($value); |
| 1383 | } |
| 1384 | |
| 1385 | // Presumably the lines below come into manage groups screen. |
| 1386 | // make sure there is only one element |
| 1387 | // this is used when we are running under smog and need to know |
| 1388 | // how the contact was added (CRM-1203) |
| 1389 | $groups = (array) CRM_Utils_Array::value($this->_paramLookup['group'][0][1], $this->_paramLookup['group'][0][2], $this->_paramLookup['group'][0][2]); |
| 1390 | if ((count($this->_paramLookup['group']) == 1) && |
| 1391 | (count($groups) == 1) |
| 1392 | ) { |
| 1393 | $groupId = $groups[0]; |
| 1394 | |
| 1395 | //check if group is saved search |
| 1396 | $group = new CRM_Contact_BAO_Group(); |
| 1397 | $group->id = $groupId; |
| 1398 | $group->find(TRUE); |
| 1399 | |
| 1400 | if (!isset($group->saved_search_id)) { |
| 1401 | $tbName = "`civicrm_group_contact-{$groupId}`"; |
| 1402 | // CRM-17254 don't retrieve extra fields if contact_id is specifically requested |
| 1403 | // as this will add load to an intentionally light query. |
| 1404 | // ideally this code would be removed as it appears to be to support CRM-1203 |
| 1405 | // and passing in the required returnProperties from the url would |
| 1406 | // make more sense that globally applying the requirements of one form. |
| 1407 | if (($this->_returnProperties != array('contact_id'))) { |
| 1408 | $this->_select['group_contact_id'] = "$tbName.id as group_contact_id"; |
| 1409 | $this->_element['group_contact_id'] = 1; |
| 1410 | $this->_select['status'] = "$tbName.status as status"; |
| 1411 | $this->_element['status'] = 1; |
| 1412 | } |
| 1413 | } |
| 1414 | } |
| 1415 | $this->_useGroupBy = TRUE; |
| 1416 | } |
| 1417 | if ($this->_useDistinct && !isset($this->_distinctComponentClause)) { |
| 1418 | if (!($this->_mode & CRM_Contact_BAO_Query::MODE_ACTIVITY)) { |
| 1419 | // CRM-5954 |
| 1420 | $this->_select['contact_id'] = 'contact_a.id as contact_id'; |
| 1421 | $this->_useDistinct = FALSE; |
| 1422 | $this->_useGroupBy = TRUE; |
| 1423 | } |
| 1424 | } |
| 1425 | |
| 1426 | $select = "SELECT "; |
| 1427 | if (isset($this->_distinctComponentClause)) { |
| 1428 | $select .= "{$this->_distinctComponentClause}, "; |
| 1429 | } |
| 1430 | $select .= implode(', ', $this->_select); |
| 1431 | $from = $this->_fromClause; |
| 1432 | } |
| 1433 | |
| 1434 | $where = ''; |
| 1435 | if (!empty($this->_whereClause)) { |
| 1436 | $where = "WHERE {$this->_whereClause}"; |
| 1437 | } |
| 1438 | |
| 1439 | if (!empty($this->_permissionWhereClause) && empty($this->_displayRelationshipType)) { |
| 1440 | if (empty($where)) { |
| 1441 | $where = "WHERE $this->_permissionWhereClause"; |
| 1442 | } |
| 1443 | else { |
| 1444 | $where = "$where AND $this->_permissionWhereClause"; |
| 1445 | } |
| 1446 | } |
| 1447 | |
| 1448 | $having = ''; |
| 1449 | if (!empty($this->_having)) { |
| 1450 | foreach ($this->_having as $havingSets) { |
| 1451 | foreach ($havingSets as $havingSet) { |
| 1452 | $havingValue[] = $havingSet; |
| 1453 | } |
| 1454 | } |
| 1455 | $having = ' HAVING ' . implode(' AND ', $havingValue); |
| 1456 | } |
| 1457 | |
| 1458 | // if we are doing a transform, do it here |
| 1459 | // use the $from, $where and $having to get the contact ID |
| 1460 | if ($this->_displayRelationshipType) { |
| 1461 | $this->filterRelatedContacts($from, $where, $having); |
| 1462 | } |
| 1463 | |
| 1464 | return array($select, $from, $where, $having); |
| 1465 | } |
| 1466 | |
| 1467 | /** |
| 1468 | * Get where values from the parameters. |
| 1469 | * |
| 1470 | * @param string $name |
| 1471 | * @param mixed $grouping |
| 1472 | * |
| 1473 | * @return mixed |
| 1474 | */ |
| 1475 | public function getWhereValues($name, $grouping) { |
| 1476 | $result = NULL; |
| 1477 | foreach ($this->_params as $values) { |
| 1478 | if ($values[0] == $name && $values[3] == $grouping) { |
| 1479 | return $values; |
| 1480 | } |
| 1481 | } |
| 1482 | |
| 1483 | return $result; |
| 1484 | } |
| 1485 | |
| 1486 | /** |
| 1487 | * Fix date values. |
| 1488 | * |
| 1489 | * @param bool $relative |
| 1490 | * @param string $from |
| 1491 | * @param string $to |
| 1492 | */ |
| 1493 | public static function fixDateValues($relative, &$from, &$to) { |
| 1494 | if ($relative) { |
| 1495 | list($from, $to) = CRM_Utils_Date::getFromTo($relative, $from, $to); |
| 1496 | } |
| 1497 | } |
| 1498 | |
| 1499 | /** |
| 1500 | * Convert values from form-appropriate to query-object appropriate. |
| 1501 | * |
| 1502 | * The query object is increasingly supporting the sql-filter syntax which is the most flexible syntax. |
| 1503 | * So, ideally we would convert all fields to look like |
| 1504 | * array( |
| 1505 | * 0 => $fieldName |
| 1506 | * // Set the operator for legacy reasons, but it is ignored |
| 1507 | * 1 => '=' |
| 1508 | * // array in sql filter syntax |
| 1509 | * 2 => array('BETWEEN' => array(1,60), |
| 1510 | * 3 => null |
| 1511 | * 4 => null |
| 1512 | * ); |
| 1513 | * |
| 1514 | * There are some examples of the syntax in |
| 1515 | * https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples/Relationship |
| 1516 | * |
| 1517 | * More notes at CRM_Core_DAO::createSQLFilter |
| 1518 | * |
| 1519 | * and a list of supported operators in CRM_Core_DAO |
| 1520 | * |
| 1521 | * @param array $formValues |
| 1522 | * @param int $wildcard |
| 1523 | * @param bool $useEquals |
| 1524 | * |
| 1525 | * @param string $apiEntity |
| 1526 | * |
| 1527 | * @param array $entityReferenceFields |
| 1528 | * Field names of any entity reference fields (which will need reformatting to IN syntax). |
| 1529 | * |
| 1530 | * @return array |
| 1531 | */ |
| 1532 | public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL, |
| 1533 | $entityReferenceFields = array()) { |
| 1534 | $params = array(); |
| 1535 | if (empty($formValues)) { |
| 1536 | return $params; |
| 1537 | } |
| 1538 | |
| 1539 | self::filterCountryFromValuesIfStateExists($formValues); |
| 1540 | |
| 1541 | foreach ($formValues as $id => &$val) { |
| 1542 | // CRM-19374 - we don't want to change $val in $formValues. |
| 1543 | // Assign it to a temp variable which operates while iteration. |
| 1544 | $values = $val; |
| 1545 | |
| 1546 | if (self::isAlreadyProcessedForQueryFormat($values)) { |
| 1547 | $params[] = $values; |
| 1548 | continue; |
| 1549 | } |
| 1550 | |
| 1551 | self::legacyConvertFormValues($id, $values); |
| 1552 | |
| 1553 | // The form uses 1 field to represent two db fields |
| 1554 | if ($id == 'contact_type' && $values && (!is_array($values) || !array_intersect(array_keys($values), CRM_Core_DAO::acceptedSQLOperators()))) { |
| 1555 | $contactType = array(); |
| 1556 | $subType = array(); |
| 1557 | foreach ((array) $values as $key => $type) { |
| 1558 | $types = explode('__', is_numeric($type) ? $key : $type); |
| 1559 | $contactType[$types[0]] = $types[0]; |
| 1560 | // Add sub-type if specified |
| 1561 | if (!empty($types[1])) { |
| 1562 | $subType[$types[1]] = $types[1]; |
| 1563 | } |
| 1564 | } |
| 1565 | $params[] = array('contact_type', 'IN', $contactType, 0, 0); |
| 1566 | if ($subType) { |
| 1567 | $params[] = array('contact_sub_type', 'IN', $subType, 0, 0); |
| 1568 | } |
| 1569 | } |
| 1570 | elseif ($id == 'privacy') { |
| 1571 | if (is_array($formValues['privacy'])) { |
| 1572 | $op = !empty($formValues['privacy']['do_not_toggle']) ? '=' : '!='; |
| 1573 | foreach ($formValues['privacy'] as $key => $value) { |
| 1574 | if ($value) { |
| 1575 | $params[] = array($key, $op, $value, 0, 0); |
| 1576 | } |
| 1577 | } |
| 1578 | } |
| 1579 | } |
| 1580 | elseif ($id == 'email_on_hold') { |
| 1581 | if ($formValues['email_on_hold']['on_hold']) { |
| 1582 | $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0); |
| 1583 | } |
| 1584 | } |
| 1585 | elseif (substr($id, 0, 7) == 'custom_' |
| 1586 | && ( |
| 1587 | substr($id, -9, 9) == '_relative' |
| 1588 | || substr($id, -5, 5) == '_from' |
| 1589 | || substr($id, -3, 3) == '_to' |
| 1590 | ) |
| 1591 | ) { |
| 1592 | self::convertCustomRelativeFields($formValues, $params, $values, $id); |
| 1593 | } |
| 1594 | elseif (preg_match('/_date_relative$/', $id) || |
| 1595 | $id == 'event_relative' || |
| 1596 | $id == 'case_from_relative' || |
| 1597 | $id == 'case_to_relative' || |
| 1598 | $id == 'participant_relative' |
| 1599 | ) { |
| 1600 | if ($id == 'event_relative') { |
| 1601 | $fromRange = 'event_start_date_low'; |
| 1602 | $toRange = 'event_end_date_high'; |
| 1603 | } |
| 1604 | elseif ($id == 'participant_relative') { |
| 1605 | $fromRange = 'participant_register_date_low'; |
| 1606 | $toRange = 'participant_register_date_high'; |
| 1607 | } |
| 1608 | elseif ($id == 'case_from_relative') { |
| 1609 | $fromRange = 'case_from_start_date_low'; |
| 1610 | $toRange = 'case_from_start_date_high'; |
| 1611 | } |
| 1612 | elseif ($id == 'case_to_relative') { |
| 1613 | $fromRange = 'case_to_end_date_low'; |
| 1614 | $toRange = 'case_to_end_date_high'; |
| 1615 | } |
| 1616 | else { |
| 1617 | $dateComponent = explode('_date_relative', $id); |
| 1618 | $fromRange = "{$dateComponent[0]}_date_low"; |
| 1619 | $toRange = "{$dateComponent[0]}_date_high"; |
| 1620 | } |
| 1621 | |
| 1622 | if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) { |
| 1623 | // relative dates are not processed correctly as lower date value were ignored, |
| 1624 | // to ensure both high and low date value got added IF there is relative date, |
| 1625 | // we need to reset $formValues by unset and then adding again via CRM_Contact_BAO_Query::fixDateValues(...) |
| 1626 | if (!empty($formValues[$id])) { |
| 1627 | unset($formValues[$fromRange]); |
| 1628 | unset($formValues[$toRange]); |
| 1629 | } |
| 1630 | CRM_Contact_BAO_Query::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]); |
| 1631 | continue; |
| 1632 | } |
| 1633 | } |
| 1634 | elseif (in_array($id, $entityReferenceFields) && !empty($values) && is_string($values) && (strpos($values, ',') != |
| 1635 | FALSE)) { |
| 1636 | $params[] = array($id, 'IN', explode(',', $values), 0, 0); |
| 1637 | } |
| 1638 | else { |
| 1639 | $values = CRM_Contact_BAO_Query::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity); |
| 1640 | |
| 1641 | if (!$values) { |
| 1642 | continue; |
| 1643 | } |
| 1644 | $params[] = $values; |
| 1645 | } |
| 1646 | } |
| 1647 | return $params; |
| 1648 | } |
| 1649 | |
| 1650 | /** |
| 1651 | * Function to support legacy format for groups and tags. |
| 1652 | * |
| 1653 | * @param string $id |
| 1654 | * @param array|int $values |
| 1655 | * |
| 1656 | */ |
| 1657 | public static function legacyConvertFormValues($id, &$values) { |
| 1658 | $legacyElements = array( |
| 1659 | 'group', |
| 1660 | 'tag', |
| 1661 | 'contact_tags', |
| 1662 | 'contact_type', |
| 1663 | 'membership_type_id', |
| 1664 | 'membership_status_id', |
| 1665 | ); |
| 1666 | if (in_array($id, $legacyElements) && is_array($values)) { |
| 1667 | // prior to 4.7, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1), |
| 1668 | // as per the recent Search fixes $values need to be in standard array(id1, id2) format |
| 1669 | $values = CRM_Utils_Array::convertCheckboxFormatToArray($values); |
| 1670 | } |
| 1671 | } |
| 1672 | |
| 1673 | /** |
| 1674 | * Fix values from query from/to something no-one cared enough to document. |
| 1675 | * |
| 1676 | * @param int $id |
| 1677 | * @param array $values |
| 1678 | * @param int $wildcard |
| 1679 | * @param bool $useEquals |
| 1680 | * |
| 1681 | * @param string $apiEntity |
| 1682 | * |
| 1683 | * @return array|null |
| 1684 | */ |
| 1685 | public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) { |
| 1686 | // skip a few search variables |
| 1687 | static $skipWhere = NULL; |
| 1688 | static $likeNames = NULL; |
| 1689 | $result = NULL; |
| 1690 | |
| 1691 | // Change camelCase EntityName to lowercase with underscores |
| 1692 | $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity); |
| 1693 | |
| 1694 | // check if $value is in OK (Operator as Key) format as used by Get API |
| 1695 | if (CRM_Utils_System::isNull($values)) { |
| 1696 | return $result; |
| 1697 | } |
| 1698 | |
| 1699 | if (!$skipWhere) { |
| 1700 | $skipWhere = array( |
| 1701 | 'task', |
| 1702 | 'radio_ts', |
| 1703 | 'uf_group_id', |
| 1704 | 'component_mode', |
| 1705 | 'qfKey', |
| 1706 | 'operator', |
| 1707 | 'display_relationship_type', |
| 1708 | ); |
| 1709 | } |
| 1710 | |
| 1711 | if (in_array($id, $skipWhere) || |
| 1712 | substr($id, 0, 4) == '_qf_' || |
| 1713 | substr($id, 0, 7) == 'hidden_' |
| 1714 | ) { |
| 1715 | return $result; |
| 1716 | } |
| 1717 | |
| 1718 | if ($apiEntity && |
| 1719 | (substr($id, 0, strlen($apiEntity)) != $apiEntity) && |
| 1720 | (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_') && |
| 1721 | (substr($id, 0, 7) != 'custom_') |
| 1722 | ) { |
| 1723 | $id = $apiEntity . '_' . $id; |
| 1724 | } |
| 1725 | |
| 1726 | if (!$likeNames) { |
| 1727 | $likeNames = array('sort_name', 'email', 'note', 'display_name'); |
| 1728 | } |
| 1729 | |
| 1730 | // email comes in via advanced search |
| 1731 | // so use wildcard always |
| 1732 | if ($id == 'email') { |
| 1733 | $wildcard = 1; |
| 1734 | } |
| 1735 | |
| 1736 | if (!$useEquals && in_array($id, $likeNames)) { |
| 1737 | $result = array($id, 'LIKE', $values, 0, 1); |
| 1738 | } |
| 1739 | elseif (is_string($values) && strpos($values, '%') !== FALSE) { |
| 1740 | $result = array($id, 'LIKE', $values, 0, 0); |
| 1741 | } |
| 1742 | elseif ($id == 'contact_type' || |
| 1743 | (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) |
| 1744 | ) { |
| 1745 | $result = array($id, 'IN', $values, 0, $wildcard); |
| 1746 | } |
| 1747 | else { |
| 1748 | $result = array($id, '=', $values, 0, $wildcard); |
| 1749 | } |
| 1750 | |
| 1751 | return $result; |
| 1752 | } |
| 1753 | |
| 1754 | /** |
| 1755 | * Get the where clause for a single field. |
| 1756 | * |
| 1757 | * @param array $values |
| 1758 | * @param string $apiEntity |
| 1759 | */ |
| 1760 | public function whereClauseSingle(&$values, $apiEntity = NULL) { |
| 1761 | // do not process custom fields or prefixed contact ids or component params |
| 1762 | if (CRM_Core_BAO_CustomField::getKeyID($values[0]) || |
| 1763 | (substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) || |
| 1764 | (substr($values[0], 0, 13) == 'contribution_') || |
| 1765 | (substr($values[0], 0, 6) == 'event_') || |
| 1766 | (substr($values[0], 0, 12) == 'participant_') || |
| 1767 | (substr($values[0], 0, 7) == 'member_') || |
| 1768 | (substr($values[0], 0, 6) == 'grant_') || |
| 1769 | (substr($values[0], 0, 7) == 'pledge_') || |
| 1770 | (substr($values[0], 0, 5) == 'case_') || |
| 1771 | (substr($values[0], 0, 10) == 'financial_') || |
| 1772 | (substr($values[0], 0, 8) == 'payment_') || |
| 1773 | (substr($values[0], 0, 11) == 'membership_') |
| 1774 | ) { |
| 1775 | return; |
| 1776 | } |
| 1777 | |
| 1778 | // skip for hook injected fields / params |
| 1779 | $extFields = CRM_Contact_BAO_Query_Hook::singleton()->getFields(); |
| 1780 | if (array_key_exists($values[0], $extFields)) { |
| 1781 | return; |
| 1782 | } |
| 1783 | |
| 1784 | switch ($values[0]) { |
| 1785 | case 'deleted_contacts': |
| 1786 | $this->deletedContacts($values); |
| 1787 | return; |
| 1788 | |
| 1789 | case 'contact_sub_type': |
| 1790 | $this->contactSubType($values); |
| 1791 | return; |
| 1792 | |
| 1793 | case 'group': |
| 1794 | case 'group_type': |
| 1795 | $this->group($values); |
| 1796 | return; |
| 1797 | |
| 1798 | // case tag comes from find contacts |
| 1799 | case 'tag_search': |
| 1800 | $this->tagSearch($values); |
| 1801 | return; |
| 1802 | |
| 1803 | case 'tag': |
| 1804 | case 'contact_tags': |
| 1805 | $this->tag($values); |
| 1806 | return; |
| 1807 | |
| 1808 | case 'note': |
| 1809 | case 'note_body': |
| 1810 | case 'note_subject': |
| 1811 | $this->notes($values); |
| 1812 | return; |
| 1813 | |
| 1814 | case 'uf_user': |
| 1815 | $this->ufUser($values); |
| 1816 | return; |
| 1817 | |
| 1818 | case 'sort_name': |
| 1819 | case 'display_name': |
| 1820 | $this->sortName($values); |
| 1821 | return; |
| 1822 | |
| 1823 | case 'addressee': |
| 1824 | case 'postal_greeting': |
| 1825 | case 'email_greeting': |
| 1826 | $this->greetings($values); |
| 1827 | return; |
| 1828 | |
| 1829 | case 'email': |
| 1830 | case 'email_id': |
| 1831 | $this->email($values, $apiEntity); |
| 1832 | return; |
| 1833 | |
| 1834 | case 'phone_numeric': |
| 1835 | $this->phone_numeric($values); |
| 1836 | return; |
| 1837 | |
| 1838 | case 'phone_phone_type_id': |
| 1839 | case 'phone_location_type_id': |
| 1840 | $this->phone_option_group($values); |
| 1841 | return; |
| 1842 | |
| 1843 | case 'street_address': |
| 1844 | $this->street_address($values); |
| 1845 | return; |
| 1846 | |
| 1847 | case 'street_number': |
| 1848 | $this->street_number($values); |
| 1849 | return; |
| 1850 | |
| 1851 | case 'sortByCharacter': |
| 1852 | $this->sortByCharacter($values); |
| 1853 | return; |
| 1854 | |
| 1855 | case 'location_type': |
| 1856 | $this->locationType($values); |
| 1857 | return; |
| 1858 | |
| 1859 | case 'county': |
| 1860 | $this->county($values); |
| 1861 | return; |
| 1862 | |
| 1863 | case 'state_province': |
| 1864 | case 'state_province_id': |
| 1865 | case 'state_province_name': |
| 1866 | $this->stateProvince($values); |
| 1867 | return; |
| 1868 | |
| 1869 | case 'country': |
| 1870 | case 'country_id': |
| 1871 | $this->country($values, FALSE); |
| 1872 | return; |
| 1873 | |
| 1874 | case 'postal_code': |
| 1875 | case 'postal_code_low': |
| 1876 | case 'postal_code_high': |
| 1877 | $this->postalCode($values); |
| 1878 | return; |
| 1879 | |
| 1880 | case 'activity_date': |
| 1881 | case 'activity_date_low': |
| 1882 | case 'activity_date_high': |
| 1883 | case 'activity_role': |
| 1884 | case 'activity_status_id': |
| 1885 | case 'activity_status': |
| 1886 | case 'followup_parent_id': |
| 1887 | case 'parent_id': |
| 1888 | case 'source_contact_id': |
| 1889 | case 'activity_subject': |
| 1890 | case 'test_activities': |
| 1891 | case 'activity_type_id': |
| 1892 | case 'activity_type': |
| 1893 | case 'activity_survey_id': |
| 1894 | case 'activity_tags': |
| 1895 | case 'activity_taglist': |
| 1896 | case 'activity_test': |
| 1897 | case 'activity_campaign_id': |
| 1898 | case 'activity_engagement_level': |
| 1899 | case 'activity_id': |
| 1900 | case 'activity_result': |
| 1901 | case 'source_contact': |
| 1902 | CRM_Activity_BAO_Query::whereClauseSingle($values, $this); |
| 1903 | return; |
| 1904 | |
| 1905 | case 'age_low': |
| 1906 | case 'age_high': |
| 1907 | case 'birth_date_low': |
| 1908 | case 'birth_date_high': |
| 1909 | case 'deceased_date_low': |
| 1910 | case 'deceased_date_high': |
| 1911 | $this->demographics($values); |
| 1912 | return; |
| 1913 | |
| 1914 | case 'age_asof_date': |
| 1915 | // handled by demographics |
| 1916 | return; |
| 1917 | |
| 1918 | case 'log_date_low': |
| 1919 | case 'log_date_high': |
| 1920 | $this->modifiedDates($values); |
| 1921 | return; |
| 1922 | |
| 1923 | case 'changed_by': |
| 1924 | $this->changeLog($values); |
| 1925 | return; |
| 1926 | |
| 1927 | case 'do_not_phone': |
| 1928 | case 'do_not_email': |
| 1929 | case 'do_not_mail': |
| 1930 | case 'do_not_sms': |
| 1931 | case 'do_not_trade': |
| 1932 | case 'is_opt_out': |
| 1933 | $this->privacy($values); |
| 1934 | return; |
| 1935 | |
| 1936 | case 'privacy_options': |
| 1937 | $this->privacyOptions($values); |
| 1938 | return; |
| 1939 | |
| 1940 | case 'privacy_operator': |
| 1941 | case 'privacy_toggle': |
| 1942 | // these are handled by privacy options |
| 1943 | return; |
| 1944 | |
| 1945 | case 'preferred_communication_method': |
| 1946 | $this->preferredCommunication($values); |
| 1947 | return; |
| 1948 | |
| 1949 | case 'relation_type_id': |
| 1950 | case 'relation_start_date_high': |
| 1951 | case 'relation_start_date_low': |
| 1952 | case 'relation_end_date_high': |
| 1953 | case 'relation_end_date_low': |
| 1954 | case 'relation_target_name': |
| 1955 | case 'relation_status': |
| 1956 | case 'relation_date_low': |
| 1957 | case 'relation_date_high': |
| 1958 | $this->relationship($values); |
| 1959 | $this->_relationshipValuesAdded = TRUE; |
| 1960 | return; |
| 1961 | |
| 1962 | case 'task_status_id': |
| 1963 | $this->task($values); |
| 1964 | return; |
| 1965 | |
| 1966 | case 'task_id': |
| 1967 | // since this case is handled with the above |
| 1968 | return; |
| 1969 | |
| 1970 | case 'prox_distance': |
| 1971 | CRM_Contact_BAO_ProximityQuery::process($this, $values); |
| 1972 | return; |
| 1973 | |
| 1974 | case 'prox_street_address': |
| 1975 | case 'prox_city': |
| 1976 | case 'prox_postal_code': |
| 1977 | case 'prox_state_province_id': |
| 1978 | case 'prox_country_id': |
| 1979 | // handled by the proximity_distance clause |
| 1980 | return; |
| 1981 | |
| 1982 | default: |
| 1983 | $this->restWhere($values); |
| 1984 | return; |
| 1985 | } |
| 1986 | } |
| 1987 | |
| 1988 | /** |
| 1989 | * Given a list of conditions in params generate the required where clause. |
| 1990 | * |
| 1991 | * @param string $apiEntity |
| 1992 | * |
| 1993 | * @return string |
| 1994 | */ |
| 1995 | public function whereClause($apiEntity = NULL) { |
| 1996 | $this->_where[0] = array(); |
| 1997 | $this->_qill[0] = array(); |
| 1998 | |
| 1999 | $this->includeContactIds(); |
| 2000 | if (!empty($this->_params)) { |
| 2001 | foreach (array_keys($this->_params) as $id) { |
| 2002 | if (empty($this->_params[$id][0])) { |
| 2003 | continue; |
| 2004 | } |
| 2005 | // check for both id and contact_id |
| 2006 | if ($this->_params[$id][0] == 'id' || $this->_params[$id][0] == 'contact_id') { |
| 2007 | $this->_where[0][] = self::buildClause("contact_a.id", $this->_params[$id][1], $this->_params[$id][2]); |
| 2008 | } |
| 2009 | else { |
| 2010 | $this->whereClauseSingle($this->_params[$id], $apiEntity); |
| 2011 | } |
| 2012 | } |
| 2013 | |
| 2014 | CRM_Core_Component::alterQuery($this, 'where'); |
| 2015 | |
| 2016 | CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'where'); |
| 2017 | } |
| 2018 | |
| 2019 | if ($this->_customQuery) { |
| 2020 | // Added following if condition to avoid the wrong value display for 'my account' / any UF info. |
| 2021 | // Hope it wont affect the other part of civicrm.. if it does please remove it. |
| 2022 | if (!empty($this->_customQuery->_where)) { |
| 2023 | $this->_where = CRM_Utils_Array::crmArrayMerge($this->_where, $this->_customQuery->_where); |
| 2024 | } |
| 2025 | |
| 2026 | $this->_qill = CRM_Utils_Array::crmArrayMerge($this->_qill, $this->_customQuery->_qill); |
| 2027 | } |
| 2028 | |
| 2029 | $clauses = array(); |
| 2030 | $andClauses = array(); |
| 2031 | |
| 2032 | $validClauses = 0; |
| 2033 | if (!empty($this->_where)) { |
| 2034 | foreach ($this->_where as $grouping => $values) { |
| 2035 | if ($grouping > 0 && !empty($values)) { |
| 2036 | $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) '; |
| 2037 | $validClauses++; |
| 2038 | } |
| 2039 | } |
| 2040 | |
| 2041 | if (!empty($this->_where[0])) { |
| 2042 | $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where[0]) . ' ) '; |
| 2043 | } |
| 2044 | if (!empty($clauses)) { |
| 2045 | $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) '; |
| 2046 | } |
| 2047 | |
| 2048 | if ($validClauses > 1) { |
| 2049 | $this->_useDistinct = TRUE; |
| 2050 | } |
| 2051 | } |
| 2052 | |
| 2053 | return implode(' AND ', $andClauses); |
| 2054 | } |
| 2055 | |
| 2056 | /** |
| 2057 | * Generate where clause for any parameters not already handled. |
| 2058 | * |
| 2059 | * @param array $values |
| 2060 | * |
| 2061 | * @throws Exception |
| 2062 | */ |
| 2063 | public function restWhere(&$values) { |
| 2064 | $name = CRM_Utils_Array::value(0, $values); |
| 2065 | $op = CRM_Utils_Array::value(1, $values); |
| 2066 | $value = CRM_Utils_Array::value(2, $values); |
| 2067 | $grouping = CRM_Utils_Array::value(3, $values); |
| 2068 | $wildcard = CRM_Utils_Array::value(4, $values); |
| 2069 | |
| 2070 | if (isset($grouping) && empty($this->_where[$grouping])) { |
| 2071 | $this->_where[$grouping] = array(); |
| 2072 | } |
| 2073 | |
| 2074 | $multipleFields = array('url'); |
| 2075 | |
| 2076 | //check if the location type exists for fields |
| 2077 | $lType = ''; |
| 2078 | $locType = explode('-', $name); |
| 2079 | |
| 2080 | if (!in_array($locType[0], $multipleFields)) { |
| 2081 | //add phone type if exists |
| 2082 | if (isset($locType[2]) && $locType[2]) { |
| 2083 | $locType[2] = CRM_Core_DAO::escapeString($locType[2]); |
| 2084 | } |
| 2085 | } |
| 2086 | |
| 2087 | $field = CRM_Utils_Array::value($name, $this->_fields); |
| 2088 | |
| 2089 | if (!$field) { |
| 2090 | $field = CRM_Utils_Array::value($locType[0], $this->_fields); |
| 2091 | |
| 2092 | if (!$field) { |
| 2093 | return; |
| 2094 | } |
| 2095 | } |
| 2096 | |
| 2097 | $setTables = TRUE; |
| 2098 | |
| 2099 | $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower'; |
| 2100 | $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); |
| 2101 | if (isset($locType[1]) && is_numeric($locType[1])) { |
| 2102 | $lType = $locationType[$locType[1]]; |
| 2103 | } |
| 2104 | if ($lType) { |
| 2105 | $field['title'] .= " ($lType)"; |
| 2106 | } |
| 2107 | |
| 2108 | if (substr($name, 0, 14) === 'state_province') { |
| 2109 | if (isset($locType[1]) && is_numeric($locType[1])) { |
| 2110 | $setTables = FALSE; |
| 2111 | $aName = "{$lType}-address"; |
| 2112 | $where = "`$aName`.state_province_id"; |
| 2113 | } |
| 2114 | else { |
| 2115 | $where = "civicrm_address.state_province_id"; |
| 2116 | } |
| 2117 | |
| 2118 | $this->_where[$grouping][] = self::buildClause($where, $op, $value); |
| 2119 | list($qillop, $qillVal) = self::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op); |
| 2120 | $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal)); |
| 2121 | } |
| 2122 | elseif (!empty($field['pseudoconstant'])) { |
| 2123 | $this->optionValueQuery( |
| 2124 | $name, $op, $value, $grouping, |
| 2125 | 'CRM_Contact_DAO_Contact', |
| 2126 | $field, |
| 2127 | $field['title'], |
| 2128 | 'String', |
| 2129 | TRUE |
| 2130 | ); |
| 2131 | if ($name == 'gender_id') { |
| 2132 | self::$_openedPanes[ts('Demographics')] = TRUE; |
| 2133 | } |
| 2134 | } |
| 2135 | elseif (substr($name, 0, 7) === 'country' || substr($name, 0, 6) === 'county') { |
| 2136 | $name = (substr($name, 0, 7) === 'country') ? "country_id" : "county_id"; |
| 2137 | if (isset($locType[1]) && is_numeric($locType[1])) { |
| 2138 | $setTables = FALSE; |
| 2139 | $aName = "{$lType}-address"; |
| 2140 | $where = "`$aName`.$name"; |
| 2141 | } |
| 2142 | else { |
| 2143 | $where = "civicrm_address.$name"; |
| 2144 | } |
| 2145 | |
| 2146 | $this->_where[$grouping][] = self::buildClause($where, $op, $value, 'Positive'); |
| 2147 | |
| 2148 | list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $name, $value, $op); |
| 2149 | $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal)); |
| 2150 | } |
| 2151 | elseif ($name === 'world_region') { |
| 2152 | $this->optionValueQuery( |
| 2153 | $name, $op, $value, $grouping, |
| 2154 | NULL, |
| 2155 | $field, |
| 2156 | ts('World Region'), |
| 2157 | 'Positive', |
| 2158 | TRUE |
| 2159 | ); |
| 2160 | } |
| 2161 | elseif ($name === 'is_deceased') { |
| 2162 | $this->setQillAndWhere($name, $op, $value, $grouping, $field); |
| 2163 | self::$_openedPanes[ts('Demographics')] = TRUE; |
| 2164 | } |
| 2165 | elseif ($name === 'created_date' || $name === 'modified_date' || $name === 'deceased_date' || $name === 'birth_date') { |
| 2166 | $appendDateTime = TRUE; |
| 2167 | if ($name === 'deceased_date' || $name === 'birth_date') { |
| 2168 | $appendDateTime = FALSE; |
| 2169 | self::$_openedPanes[ts('Demographics')] = TRUE; |
| 2170 | } |
| 2171 | $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime); |
| 2172 | } |
| 2173 | elseif ($name === 'contact_id') { |
| 2174 | if (is_int($value)) { |
| 2175 | $this->_where[$grouping][] = self::buildClause($field['where'], $op, $value); |
| 2176 | $this->_qill[$grouping][] = "$field[title] $op $value"; |
| 2177 | } |
| 2178 | } |
| 2179 | elseif ($name === 'name') { |
| 2180 | $value = $strtolower(CRM_Core_DAO::escapeString($value)); |
| 2181 | if ($wildcard) { |
| 2182 | $op = 'LIKE'; |
| 2183 | $value = self::getWildCardedValue($wildcard, $op, $value); |
| 2184 | } |
| 2185 | $wc = self::caseImportant($op) ? "LOWER({$field['where']})" : "{$field['where']}"; |
| 2186 | $this->_where[$grouping][] = self::buildClause($wc, $op, "'$value'"); |
| 2187 | $this->_qill[$grouping][] = "$field[title] $op \"$value\""; |
| 2188 | } |
| 2189 | elseif ($name === 'current_employer') { |
| 2190 | if ($wildcard) { |
| 2191 | $op = 'LIKE'; |
| 2192 | $value = self::getWildCardedValue($wildcard, $op, $value); |
| 2193 | } |
| 2194 | $ceWhereClause = self::buildClause("contact_a.organization_name", $op, |
| 2195 | $value |
| 2196 | ); |
| 2197 | $ceWhereClause .= " AND contact_a.contact_type = 'Individual'"; |
| 2198 | $this->_where[$grouping][] = $ceWhereClause; |
| 2199 | $this->_qill[$grouping][] = "$field[title] $op \"$value\""; |
| 2200 | } |
| 2201 | elseif ($name === 'email_greeting') { |
| 2202 | $filterCondition = array('greeting_type' => 'email_greeting'); |
| 2203 | $this->optionValueQuery( |
| 2204 | $name, $op, $value, $grouping, |
| 2205 | CRM_Core_PseudoConstant::greeting($filterCondition), |
| 2206 | $field, |
| 2207 | ts('Email Greeting') |
| 2208 | ); |
| 2209 | } |
| 2210 | elseif ($name === 'postal_greeting') { |
| 2211 | $filterCondition = array('greeting_type' => 'postal_greeting'); |
| 2212 | $this->optionValueQuery( |
| 2213 | $name, $op, $value, $grouping, |
| 2214 | CRM_Core_PseudoConstant::greeting($filterCondition), |
| 2215 | $field, |
| 2216 | ts('Postal Greeting') |
| 2217 | ); |
| 2218 | } |
| 2219 | elseif ($name === 'addressee') { |
| 2220 | $filterCondition = array('greeting_type' => 'addressee'); |
| 2221 | $this->optionValueQuery( |
| 2222 | $name, $op, $value, $grouping, |
| 2223 | CRM_Core_PseudoConstant::greeting($filterCondition), |
| 2224 | $field, |
| 2225 | ts('Addressee') |
| 2226 | ); |
| 2227 | } |
| 2228 | elseif (substr($name, 0, 4) === 'url-') { |
| 2229 | $tName = 'civicrm_website'; |
| 2230 | $this->_whereTables[$tName] = $this->_tables[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )"; |
| 2231 | $value = $strtolower(CRM_Core_DAO::escapeString($value)); |
| 2232 | if ($wildcard) { |
| 2233 | $op = 'LIKE'; |
| 2234 | $value = self::getWildCardedValue($wildcard, $op, $value); |
| 2235 | } |
| 2236 | |
| 2237 | $this->_where[$grouping][] = $d = self::buildClause('civicrm_website.url', $op, $value); |
| 2238 | $this->_qill[$grouping][] = "$field[title] $op \"$value\""; |
| 2239 | } |
| 2240 | elseif ($name === 'contact_is_deleted') { |
| 2241 | $this->setQillAndWhere('is_deleted', $op, $value, $grouping, $field); |
| 2242 | } |
| 2243 | elseif (!empty($field['where'])) { |
| 2244 | $type = NULL; |
| 2245 | if (!empty($field['type'])) { |
| 2246 | $type = CRM_Utils_Type::typeToString($field['type']); |
| 2247 | } |
| 2248 | |
| 2249 | list($tableName, $fieldName) = explode('.', $field['where'], 2); |
| 2250 | |
| 2251 | if (isset($locType[1]) && |
| 2252 | is_numeric($locType[1]) |
| 2253 | ) { |
| 2254 | $setTables = FALSE; |
| 2255 | |
| 2256 | //get the location name |
| 2257 | list($tName, $fldName) = self::getLocationTableName($field['where'], $locType); |
| 2258 | |
| 2259 | $fieldName = "LOWER(`$tName`.$fldName)"; |
| 2260 | |
| 2261 | // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should |
| 2262 | $this->_tables[$tName] = $this->_whereTables[$tName] = 1; |
| 2263 | |
| 2264 | } |
| 2265 | else { |
| 2266 | if ($tableName == 'civicrm_contact') { |
| 2267 | // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811. |
| 2268 | $fieldName = "LOWER(contact_a.{$fieldName})"; |
| 2269 | } |
| 2270 | else { |
| 2271 | if ($op != 'IN' && !is_numeric($value) && !is_array($value)) { |
| 2272 | // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811. |
| 2273 | $fieldName = "LOWER({$field['where']})"; |
| 2274 | } |
| 2275 | else { |
| 2276 | $fieldName = "{$field['where']}"; |
| 2277 | } |
| 2278 | } |
| 2279 | } |
| 2280 | |
| 2281 | list($qillop, $qillVal) = self::buildQillForFieldValue(NULL, $field['title'], $value, $op); |
| 2282 | $this->_qill[$grouping][] = ts("%1 %2 %3", array( |
| 2283 | 1 => $field['title'], |
| 2284 | 2 => $qillop, |
| 2285 | 3 => (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) ? $qillVal : "'$qillVal'")); |
| 2286 | |
| 2287 | if (is_array($value)) { |
| 2288 | // traditionally an array being passed has been a fatal error. We can take advantage of this to add support |
| 2289 | // for api style operators for functions that hit this point without worrying about regression |
| 2290 | // (the previous comments indicated the condition for hitting this point were unknown |
| 2291 | // per CRM-14743 we are adding modified_date & created_date operator support |
| 2292 | $operations = array_keys($value); |
| 2293 | foreach ($operations as $operator) { |
| 2294 | if (!in_array($operator, CRM_Core_DAO::acceptedSQLOperators())) { |
| 2295 | //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators |
| 2296 | //so this condition will satisfy the search for now |
| 2297 | if (strpos($op, 'IN') !== FALSE) { |
| 2298 | $value = array($op => $value); |
| 2299 | } |
| 2300 | // we don't know when this might happen |
| 2301 | else { |
| 2302 | CRM_Core_Error::fatal(ts("%1 is not a valid operator", array(1 => $operator))); |
| 2303 | } |
| 2304 | } |
| 2305 | } |
| 2306 | $this->_where[$grouping][] = CRM_Core_DAO::createSQLFilter($fieldName, $value, $type); |
| 2307 | } |
| 2308 | else { |
| 2309 | if (!strpos($op, 'IN')) { |
| 2310 | $value = $strtolower($value); |
| 2311 | } |
| 2312 | if ($wildcard) { |
| 2313 | $op = 'LIKE'; |
| 2314 | $value = self::getWildCardedValue($wildcard, $op, $value); |
| 2315 | } |
| 2316 | |
| 2317 | $this->_where[$grouping][] = self::buildClause($fieldName, $op, $value, $type); |
| 2318 | } |
| 2319 | } |
| 2320 | |
| 2321 | if ($setTables && isset($field['where'])) { |
| 2322 | list($tableName, $fieldName) = explode('.', $field['where'], 2); |
| 2323 | if (isset($tableName)) { |
| 2324 | $this->_tables[$tableName] = 1; |
| 2325 | $this->_whereTables[$tableName] = 1; |
| 2326 | } |
| 2327 | } |
| 2328 | } |
| 2329 | |
| 2330 | |
| 2331 | /** |
| 2332 | * @param $where |
| 2333 | * @param $locType |
| 2334 | * |
| 2335 | * @return array |
| 2336 | * @throws Exception |
| 2337 | */ |
| 2338 | public static function getLocationTableName(&$where, &$locType) { |
| 2339 | if (isset($locType[1]) && is_numeric($locType[1])) { |
| 2340 | list($tbName, $fldName) = explode(".", $where); |
| 2341 | |
| 2342 | //get the location name |
| 2343 | $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); |
| 2344 | $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext'); |
| 2345 | if (in_array($locType[0], $specialFields)) { |
| 2346 | //hack to fix / special handing for phone_ext |
| 2347 | if ($locType[0] == 'phone_ext') { |
| 2348 | $locType[0] = 'phone'; |
| 2349 | } |
| 2350 | if (isset($locType[2]) && $locType[2]) { |
| 2351 | $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}"; |
| 2352 | } |
| 2353 | else { |
| 2354 | $tName = "{$locationType[$locType[1]]}-{$locType[0]}"; |
| 2355 | } |
| 2356 | } |
| 2357 | elseif (in_array($locType[0], |
| 2358 | array( |
| 2359 | 'address_name', |
| 2360 | 'street_address', |
| 2361 | 'street_name', |
| 2362 | 'street_number_suffix', |
| 2363 | 'street_unit', |
| 2364 | 'supplemental_address_1', |
| 2365 | 'supplemental_address_2', |
| 2366 | 'city', |
| 2367 | 'postal_code', |
| 2368 | 'postal_code_suffix', |
| 2369 | 'geo_code_1', |
| 2370 | 'geo_code_2', |
| 2371 | 'master_id', |
| 2372 | ) |
| 2373 | )) { |
| 2374 | //fix for search by profile with address fields. |
| 2375 | $tName = "{$locationType[$locType[1]]}-address"; |
| 2376 | } |
| 2377 | elseif (in_array($locType[0], |
| 2378 | array( |
| 2379 | 'on_hold', |
| 2380 | 'signature_html', |
| 2381 | 'signature_text', |
| 2382 | 'is_bulkmail', |
| 2383 | ) |
| 2384 | )) { |
| 2385 | $tName = "{$locationType[$locType[1]]}-email"; |
| 2386 | } |
| 2387 | elseif ($locType[0] == 'provider_id') { |
| 2388 | $tName = "{$locationType[$locType[1]]}-im"; |
| 2389 | } |
| 2390 | elseif ($locType[0] == 'openid') { |
| 2391 | $tName = "{$locationType[$locType[1]]}-openid"; |
| 2392 | } |
| 2393 | else { |
| 2394 | $tName = "{$locationType[$locType[1]]}-{$locType[0]}"; |
| 2395 | } |
| 2396 | $tName = str_replace(' ', '_', $tName); |
| 2397 | return array($tName, $fldName); |
| 2398 | } |
| 2399 | CRM_Core_Error::fatal(); |
| 2400 | } |
| 2401 | |
| 2402 | /** |
| 2403 | * Given a result dao, extract the values and return that array |
| 2404 | * |
| 2405 | * @param CRM_Core_DAO $dao |
| 2406 | * |
| 2407 | * @return array |
| 2408 | * values for this query |
| 2409 | */ |
| 2410 | public function store($dao) { |
| 2411 | $value = array(); |
| 2412 | |
| 2413 | foreach ($this->_element as $key => $dontCare) { |
| 2414 | if (property_exists($dao, $key)) { |
| 2415 | if (strpos($key, '-') !== FALSE) { |
| 2416 | $values = explode('-', $key); |
| 2417 | $lastElement = array_pop($values); |
| 2418 | $current = &$value; |
| 2419 | $cnt = count($values); |
| 2420 | $count = 1; |
| 2421 | foreach ($values as $v) { |
| 2422 | if (!array_key_exists($v, $current)) { |
| 2423 | $current[$v] = array(); |
| 2424 | } |
| 2425 | //bad hack for im_provider |
| 2426 | if ($lastElement == 'provider_id') { |
| 2427 | if ($count < $cnt) { |
| 2428 | $current = &$current[$v]; |
| 2429 | } |
| 2430 | else { |
| 2431 | $lastElement = "{$v}_{$lastElement}"; |
| 2432 | } |
| 2433 | } |
| 2434 | else { |
| 2435 | $current = &$current[$v]; |
| 2436 | } |
| 2437 | $count++; |
| 2438 | } |
| 2439 | |
| 2440 | $current[$lastElement] = $dao->$key; |
| 2441 | } |
| 2442 | else { |
| 2443 | $value[$key] = $dao->$key; |
| 2444 | } |
| 2445 | } |
| 2446 | } |
| 2447 | return $value; |
| 2448 | } |
| 2449 | |
| 2450 | /** |
| 2451 | * Getter for tables array. |
| 2452 | * |
| 2453 | * @return array |
| 2454 | */ |
| 2455 | public function tables() { |
| 2456 | return $this->_tables; |
| 2457 | } |
| 2458 | |
| 2459 | /** |
| 2460 | * Where tables is sometimes used to create the from clause, but, not reliably, set this AND set tables |
| 2461 | * It's unclear the intent - there is a 'simpleFrom' clause which takes whereTables into account & a fromClause which doesn't |
| 2462 | * logic may have eroded |
| 2463 | * @return array |
| 2464 | */ |
| 2465 | public function whereTables() { |
| 2466 | return $this->_whereTables; |
| 2467 | } |
| 2468 | |
| 2469 | /** |
| 2470 | * Generate the where clause (used in match contacts and permissions) |
| 2471 | * |
| 2472 | * @param array $params |
| 2473 | * @param array $fields |
| 2474 | * @param array $tables |
| 2475 | * @param $whereTables |
| 2476 | * @param bool $strict |
| 2477 | * |
| 2478 | * @return string |
| 2479 | */ |
| 2480 | public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) { |
| 2481 | $query = new CRM_Contact_BAO_Query($params, NULL, $fields, |
| 2482 | FALSE, $strict |
| 2483 | ); |
| 2484 | |
| 2485 | $tables = array_merge($query->tables(), $tables); |
| 2486 | $whereTables = array_merge($query->whereTables(), $whereTables); |
| 2487 | |
| 2488 | return $query->_whereClause; |
| 2489 | } |
| 2490 | |
| 2491 | /** |
| 2492 | * Create the from clause. |
| 2493 | * |
| 2494 | * @param array $tables |
| 2495 | * Tables that need to be included in this from clause. |
| 2496 | * if null, return mimimal from clause (i.e. civicrm_contact) |
| 2497 | * @param array $inner |
| 2498 | * Tables that should be inner-joined. |
| 2499 | * @param array $right |
| 2500 | * Tables that should be right-joined. |
| 2501 | * |
| 2502 | * @param bool $primaryLocation |
| 2503 | * @param int $mode |
| 2504 | * |
| 2505 | * @return string |
| 2506 | * the from clause |
| 2507 | */ |
| 2508 | public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) { |
| 2509 | |
| 2510 | $from = ' FROM civicrm_contact contact_a'; |
| 2511 | if (empty($tables)) { |
| 2512 | return $from; |
| 2513 | } |
| 2514 | |
| 2515 | if (!empty($tables['civicrm_worldregion'])) { |
| 2516 | $tables = array_merge(array('civicrm_country' => 1), $tables); |
| 2517 | } |
| 2518 | |
| 2519 | if ((!empty($tables['civicrm_state_province']) || !empty($tables['civicrm_country']) || |
| 2520 | CRM_Utils_Array::value('civicrm_county', $tables) |
| 2521 | ) && empty($tables['civicrm_address']) |
| 2522 | ) { |
| 2523 | $tables = array_merge(array('civicrm_address' => 1), |
| 2524 | $tables |
| 2525 | ); |
| 2526 | } |
| 2527 | |
| 2528 | // add group_contact and group table is subscription history is present |
| 2529 | if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) { |
| 2530 | $tables = array_merge(array( |
| 2531 | 'civicrm_group' => 1, |
| 2532 | 'civicrm_group_contact' => 1, |
| 2533 | ), |
| 2534 | $tables |
| 2535 | ); |
| 2536 | } |
| 2537 | |
| 2538 | // to handle table dependencies of components |
| 2539 | CRM_Core_Component::tableNames($tables); |
| 2540 | // to handle table dependencies of hook injected tables |
| 2541 | CRM_Contact_BAO_Query_Hook::singleton()->setTableDependency($tables); |
| 2542 | |
| 2543 | //format the table list according to the weight |
| 2544 | $info = CRM_Core_TableHierarchy::info(); |
| 2545 | |
| 2546 | foreach ($tables as $key => $value) { |
| 2547 | $k = 99; |
| 2548 | if (strpos($key, '-') !== FALSE) { |
| 2549 | $keyArray = explode('-', $key); |
| 2550 | $k = CRM_Utils_Array::value('civicrm_' . $keyArray[1], $info, 99); |
| 2551 | } |
| 2552 | elseif (strpos($key, '_') !== FALSE) { |
| 2553 | $keyArray = explode('_', $key); |
| 2554 | if (is_numeric(array_pop($keyArray))) { |
| 2555 | $k = CRM_Utils_Array::value(implode('_', $keyArray), $info, 99); |
| 2556 | } |
| 2557 | else { |
| 2558 | $k = CRM_Utils_Array::value($key, $info, 99); |
| 2559 | } |
| 2560 | } |
| 2561 | else { |
| 2562 | $k = CRM_Utils_Array::value($key, $info, 99); |
| 2563 | } |
| 2564 | $tempTable[$k . ".$key"] = $key; |
| 2565 | } |
| 2566 | ksort($tempTable); |
| 2567 | $newTables = array(); |
| 2568 | foreach ($tempTable as $key) { |
| 2569 | $newTables[$key] = $tables[$key]; |
| 2570 | } |
| 2571 | |
| 2572 | $tables = $newTables; |
| 2573 | |
| 2574 | foreach ($tables as $name => $value) { |
| 2575 | if (!$value) { |
| 2576 | continue; |
| 2577 | } |
| 2578 | |
| 2579 | if (!empty($inner[$name])) { |
| 2580 | $side = 'INNER'; |
| 2581 | } |
| 2582 | elseif (!empty($right[$name])) { |
| 2583 | $side = 'RIGHT'; |
| 2584 | } |
| 2585 | else { |
| 2586 | $side = 'LEFT'; |
| 2587 | } |
| 2588 | |
| 2589 | if ($value != 1) { |
| 2590 | // if there is already a join statement in value, use value itself |
| 2591 | if (strpos($value, 'JOIN')) { |
| 2592 | $from .= " $value "; |
| 2593 | } |
| 2594 | else { |
| 2595 | $from .= " $side JOIN $name ON ( $value ) "; |
| 2596 | } |
| 2597 | continue; |
| 2598 | } |
| 2599 | switch ($name) { |
| 2600 | case 'civicrm_address': |
| 2601 | if ($primaryLocation) { |
| 2602 | $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )"; |
| 2603 | } |
| 2604 | else { |
| 2605 | //CRM-14263 further handling of address joins further down... |
| 2606 | $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) "; |
| 2607 | } |
| 2608 | continue; |
| 2609 | |
| 2610 | case 'civicrm_phone': |
| 2611 | $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) "; |
| 2612 | continue; |
| 2613 | |
| 2614 | case 'civicrm_email': |
| 2615 | $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) "; |
| 2616 | continue; |
| 2617 | |
| 2618 | case 'civicrm_im': |
| 2619 | $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) "; |
| 2620 | continue; |
| 2621 | |
| 2622 | case 'im_provider': |
| 2623 | $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) "; |
| 2624 | $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'"; |
| 2625 | $from .= " $side JOIN civicrm_option_value im_provider ON (civicrm_im.provider_id = im_provider.value AND option_group_imProvider.id = im_provider.option_group_id)"; |
| 2626 | continue; |
| 2627 | |
| 2628 | case 'civicrm_openid': |
| 2629 | $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )"; |
| 2630 | continue; |
| 2631 | |
| 2632 | case 'civicrm_worldregion': |
| 2633 | $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id "; |
| 2634 | $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id "; |
| 2635 | continue; |
| 2636 | |
| 2637 | case 'civicrm_location_type': |
| 2638 | $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id "; |
| 2639 | continue; |
| 2640 | |
| 2641 | case 'civicrm_group': |
| 2642 | $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id "; |
| 2643 | continue; |
| 2644 | |
| 2645 | case 'civicrm_group_contact': |
| 2646 | $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id "; |
| 2647 | continue; |
| 2648 | |
| 2649 | case 'civicrm_group_contact_cache': |
| 2650 | $from .= " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id "; |
| 2651 | continue; |
| 2652 | |
| 2653 | case 'civicrm_activity': |
| 2654 | case 'civicrm_activity_tag': |
| 2655 | case 'activity_type': |
| 2656 | case 'activity_status': |
| 2657 | case 'parent_id': |
| 2658 | case 'civicrm_activity_contact': |
| 2659 | case 'source_contact': |
| 2660 | $from .= CRM_Activity_BAO_Query::from($name, $mode, $side); |
| 2661 | continue; |
| 2662 | |
| 2663 | case 'civicrm_entity_tag': |
| 2664 | $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND |
| 2665 | civicrm_entity_tag.entity_id = contact_a.id ) "; |
| 2666 | continue; |
| 2667 | |
| 2668 | case 'civicrm_note': |
| 2669 | $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND |
| 2670 | contact_a.id = civicrm_note.entity_id ) "; |
| 2671 | continue; |
| 2672 | |
| 2673 | case 'civicrm_subscription_history': |
| 2674 | $from .= " $side JOIN civicrm_subscription_history |
| 2675 | ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id |
| 2676 | AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id"; |
| 2677 | continue; |
| 2678 | |
| 2679 | case 'civicrm_relationship': |
| 2680 | if (self::$_relType == 'reciprocal') { |
| 2681 | if (self::$_relationshipTempTable) { |
| 2682 | // we have a temptable to join on |
| 2683 | $tbl = self::$_relationshipTempTable; |
| 2684 | $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id"; |
| 2685 | } |
| 2686 | else { |
| 2687 | $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)"; |
| 2688 | $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id OR civicrm_relationship.contact_id_b = contact_b.id)"; |
| 2689 | } |
| 2690 | } |
| 2691 | elseif (self::$_relType == 'b') { |
| 2692 | $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )"; |
| 2693 | $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )"; |
| 2694 | } |
| 2695 | else { |
| 2696 | $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )"; |
| 2697 | $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )"; |
| 2698 | } |
| 2699 | continue; |
| 2700 | |
| 2701 | case 'civicrm_log': |
| 2702 | $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')"; |
| 2703 | $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)"; |
| 2704 | continue; |
| 2705 | |
| 2706 | case 'civicrm_tag': |
| 2707 | $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id "; |
| 2708 | continue; |
| 2709 | |
| 2710 | case 'civicrm_grant': |
| 2711 | $from .= CRM_Grant_BAO_Query::from($name, $mode, $side); |
| 2712 | continue; |
| 2713 | |
| 2714 | case 'civicrm_website': |
| 2715 | $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id "; |
| 2716 | continue; |
| 2717 | |
| 2718 | default: |
| 2719 | $locationTypeName = ''; |
| 2720 | if (strpos($name, '-address') != 0) { |
| 2721 | $locationTypeName = 'address'; |
| 2722 | } |
| 2723 | elseif (strpos($name, '-phone') != 0) { |
| 2724 | $locationTypeName = 'phone'; |
| 2725 | } |
| 2726 | elseif (strpos($name, '-email') != 0) { |
| 2727 | $locationTypeName = 'email'; |
| 2728 | } |
| 2729 | elseif (strpos($name, '-im') != 0) { |
| 2730 | $locationTypeName = 'im'; |
| 2731 | } |
| 2732 | elseif (strpos($name, '-openid') != 0) { |
| 2733 | $locationTypeName = 'openid'; |
| 2734 | } |
| 2735 | |
| 2736 | if ($locationTypeName) { |
| 2737 | //we have a join on an location table - possibly in conjunction with search builder - CRM-14263 |
| 2738 | $parts = explode('-', $name); |
| 2739 | $locationID = array_search($parts[0], CRM_Core_BAO_Address::buildOptions('location_type_id', 'get', array('name' => $parts[0]))); |
| 2740 | $from .= " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID "; |
| 2741 | } |
| 2742 | else { |
| 2743 | $from .= CRM_Core_Component::from($name, $mode, $side); |
| 2744 | } |
| 2745 | $from .= CRM_Contact_BAO_Query_Hook::singleton()->buildSearchfrom($name, $mode, $side); |
| 2746 | |
| 2747 | continue; |
| 2748 | } |
| 2749 | } |
| 2750 | return $from; |
| 2751 | } |
| 2752 | |
| 2753 | /** |
| 2754 | * WHERE / QILL clause for deleted_contacts |
| 2755 | * |
| 2756 | * @param array $values |
| 2757 | */ |
| 2758 | public function deletedContacts($values) { |
| 2759 | list($_, $_, $value, $grouping, $_) = $values; |
| 2760 | if ($value) { |
| 2761 | // *prepend* to the relevant grouping as this is quite an important factor |
| 2762 | array_unshift($this->_qill[$grouping], ts('Search in Trash')); |
| 2763 | } |
| 2764 | } |
| 2765 | |
| 2766 | /** |
| 2767 | * Where / qill clause for contact_type |
| 2768 | * |
| 2769 | * @param $values |
| 2770 | */ |
| 2771 | public function contactType(&$values) { |
| 2772 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 2773 | |
| 2774 | $subTypes = array(); |
| 2775 | $clause = array(); |
| 2776 | |
| 2777 | // account for search builder mapping multiple values |
| 2778 | if (!is_array($value)) { |
| 2779 | $values = self::parseSearchBuilderString($value, 'String'); |
| 2780 | if (is_array($values)) { |
| 2781 | $value = array_flip($values); |
| 2782 | } |
| 2783 | } |
| 2784 | |
| 2785 | if (is_array($value)) { |
| 2786 | foreach ($value as $k => $v) { |
| 2787 | // fix for CRM-771 |
| 2788 | if ($k) { |
| 2789 | $subType = NULL; |
| 2790 | $contactType = $k; |
| 2791 | if (strpos($k, CRM_Core_DAO::VALUE_SEPARATOR)) { |
| 2792 | list($contactType, $subType) = explode(CRM_Core_DAO::VALUE_SEPARATOR, $k, 2); |
| 2793 | } |
| 2794 | |
| 2795 | if (!empty($subType)) { |
| 2796 | $subTypes[$subType] = 1; |
| 2797 | } |
| 2798 | $clause[$contactType] = "'" . CRM_Utils_Type::escape($contactType, 'String') . "'"; |
| 2799 | } |
| 2800 | } |
| 2801 | } |
| 2802 | else { |
| 2803 | $contactTypeANDSubType = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value, 2); |
| 2804 | $contactType = $contactTypeANDSubType[0]; |
| 2805 | $subType = CRM_Utils_Array::value(1, $contactTypeANDSubType); |
| 2806 | if (!empty($subType)) { |
| 2807 | $subTypes[$subType] = 1; |
| 2808 | } |
| 2809 | $clause[$contactType] = "'" . CRM_Utils_Type::escape($contactType, 'String') . "'"; |
| 2810 | } |
| 2811 | |
| 2812 | // fix for CRM-771 |
| 2813 | if (!empty($clause)) { |
| 2814 | $quill = $clause; |
| 2815 | if ($op == 'IN' || $op == 'NOT IN') { |
| 2816 | $this->_where[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')'; |
| 2817 | } |
| 2818 | else { |
| 2819 | $type = array_pop($clause); |
| 2820 | $this->_where[$grouping][] = self::buildClause("contact_a.contact_type", $op, $contactType); |
| 2821 | } |
| 2822 | |
| 2823 | $this->_qill[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill); |
| 2824 | |
| 2825 | if (!empty($subTypes)) { |
| 2826 | $this->includeContactSubTypes($subTypes, $grouping); |
| 2827 | } |
| 2828 | } |
| 2829 | } |
| 2830 | |
| 2831 | /** |
| 2832 | * Where / qill clause for contact_sub_type |
| 2833 | * |
| 2834 | * @param $values |
| 2835 | */ |
| 2836 | public function contactSubType(&$values) { |
| 2837 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 2838 | $this->includeContactSubTypes($value, $grouping, $op); |
| 2839 | } |
| 2840 | |
| 2841 | /** |
| 2842 | * @param $value |
| 2843 | * @param $grouping |
| 2844 | * @param string $op |
| 2845 | */ |
| 2846 | public function includeContactSubTypes($value, $grouping, $op = 'LIKE') { |
| 2847 | |
| 2848 | if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) { |
| 2849 | $op = key($value); |
| 2850 | $value = $value[$op]; |
| 2851 | } |
| 2852 | |
| 2853 | $clause = array(); |
| 2854 | $alias = "contact_a.contact_sub_type"; |
| 2855 | $qillOperators = CRM_Core_SelectValues::getSearchBuilderOperators(); |
| 2856 | |
| 2857 | $op = str_replace('IN', 'LIKE', $op); |
| 2858 | $op = str_replace('=', 'LIKE', $op); |
| 2859 | $op = str_replace('!', 'NOT ', $op); |
| 2860 | |
| 2861 | if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) { |
| 2862 | $this->_where[$grouping][] = self::buildClause($alias, $op, $value, 'String'); |
| 2863 | } |
| 2864 | elseif (is_array($value)) { |
| 2865 | foreach ($value as $k => $v) { |
| 2866 | $clause[$k] = "($alias $op '%" . CRM_Core_DAO::VALUE_SEPARATOR . CRM_Utils_Type::escape($v, 'String') . CRM_Core_DAO::VALUE_SEPARATOR . "%')"; |
| 2867 | } |
| 2868 | } |
| 2869 | else { |
| 2870 | $clause[$value] = "($alias $op '%" . CRM_Core_DAO::VALUE_SEPARATOR . CRM_Utils_Type::escape($value, 'String') . CRM_Core_DAO::VALUE_SEPARATOR . "%')"; |
| 2871 | } |
| 2872 | |
| 2873 | if (!empty($clause)) { |
| 2874 | $this->_where[$grouping][] = "( " . implode(' OR ', $clause) . " )"; |
| 2875 | } |
| 2876 | $this->_qill[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause)); |
| 2877 | } |
| 2878 | |
| 2879 | /** |
| 2880 | * Where / qill clause for groups. |
| 2881 | * |
| 2882 | * @param $values |
| 2883 | */ |
| 2884 | public function group($values) { |
| 2885 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 2886 | |
| 2887 | // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first |
| 2888 | if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) { |
| 2889 | $op = key($value); |
| 2890 | $value = $value[$op]; |
| 2891 | } |
| 2892 | |
| 2893 | // Replace pseudo operators from search builder |
| 2894 | $op = str_replace('EMPTY', 'NULL', $op); |
| 2895 | |
| 2896 | if (strpos($op, 'NULL')) { |
| 2897 | $value = NULL; |
| 2898 | } |
| 2899 | |
| 2900 | if (count($value) > 1) { |
| 2901 | if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) { |
| 2902 | CRM_Core_Error::fatal(ts("%1 is not a valid operator", array(1 => $op))); |
| 2903 | } |
| 2904 | $this->_useDistinct = TRUE; |
| 2905 | } |
| 2906 | |
| 2907 | if (isset($value)) { |
| 2908 | $value = CRM_Utils_Array::value($op, $value, $value); |
| 2909 | } |
| 2910 | |
| 2911 | if ($name == 'group_type') { |
| 2912 | $value = array_keys($this->getGroupsFromTypeCriteria($value)); |
| 2913 | } |
| 2914 | |
| 2915 | $regularGroupIDs = $smartGroupIDs = array(); |
| 2916 | foreach ((array) $value as $id) { |
| 2917 | if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) { |
| 2918 | $smartGroupIDs[] = $id; |
| 2919 | } |
| 2920 | else { |
| 2921 | $regularGroupIDs[] = $id; |
| 2922 | } |
| 2923 | } |
| 2924 | |
| 2925 | $isNotOp = ($op == 'NOT IN' || $op == '!='); |
| 2926 | |
| 2927 | $statii = array(); |
| 2928 | $gcsValues = $this->getWhereValues('group_contact_status', $grouping); |
| 2929 | if ($gcsValues && |
| 2930 | is_array($gcsValues[2]) |
| 2931 | ) { |
| 2932 | foreach ($gcsValues[2] as $k => $v) { |
| 2933 | if ($v) { |
| 2934 | $statii[] = "'" . CRM_Utils_Type::escape($k, 'String') . "'"; |
| 2935 | } |
| 2936 | } |
| 2937 | } |
| 2938 | else { |
| 2939 | $statii[] = "'Added'"; |
| 2940 | } |
| 2941 | |
| 2942 | $groupClause = array(); |
| 2943 | if (count($regularGroupIDs) || empty($value)) { |
| 2944 | $groupIds = implode(',', (array) $regularGroupIDs); |
| 2945 | $gcTable = "`civicrm_group_contact-{$groupIds}`"; |
| 2946 | $joinClause = array("contact_a.id = {$gcTable}.contact_id"); |
| 2947 | if ($statii) { |
| 2948 | $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")"; |
| 2949 | } |
| 2950 | $this->_tables[$gcTable] = $this->_whereTables[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")"; |
| 2951 | if (strpos($op, 'IN') !== FALSE) { |
| 2952 | $clause = "{$gcTable}.group_id $op ( $groupIds ) %s "; |
| 2953 | } |
| 2954 | elseif ($op == '!=') { |
| 2955 | $clause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds %s)"; |
| 2956 | } |
| 2957 | else { |
| 2958 | $clause = "{$gcTable}.group_id $op $groupIds %s "; |
| 2959 | } |
| 2960 | |
| 2961 | // include child groups IDs if any |
| 2962 | $childGroupIds = CRM_Contact_BAO_Group::getChildGroupIds($regularGroupIDs); |
| 2963 | $childClause = ''; |
| 2964 | if (count($childGroupIds)) { |
| 2965 | $gcTable = ($op == '!=') ? 'cgc' : $gcTable; |
| 2966 | $childClause = " OR {$gcTable}.group_id IN (" . implode(',', $childGroupIds) . ") "; |
| 2967 | } |
| 2968 | $groupClause[] = sprintf($clause, $childClause); |
| 2969 | } |
| 2970 | |
| 2971 | //CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table |
| 2972 | if (count($smartGroupIDs)) { |
| 2973 | $groupClause[] = " ( " . $this->addGroupContactCache($smartGroupIDs, NULL, "contact_a", $op) . " ) "; |
| 2974 | } |
| 2975 | |
| 2976 | $and = ($op == 'IS NULL') ? ' AND ' : ' OR '; |
| 2977 | $this->_where[$grouping][] = implode($and, $groupClause); |
| 2978 | |
| 2979 | list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op); |
| 2980 | $this->_qill[$grouping][] = ts("Group(s) %1 %2", array(1 => $qillop, 2 => $qillVal)); |
| 2981 | if (strpos($op, 'NULL') === FALSE) { |
| 2982 | $this->_qill[$grouping][] = ts("Group Status %1", array(1 => implode(' ' . ts('or') . ' ', $statii))); |
| 2983 | } |
| 2984 | } |
| 2985 | |
| 2986 | /** |
| 2987 | * Function translates selection of group type into a list of groups. |
| 2988 | * @param $value |
| 2989 | * |
| 2990 | * @return array |
| 2991 | */ |
| 2992 | public function getGroupsFromTypeCriteria($value) { |
| 2993 | $groupIds = array(); |
| 2994 | foreach ((array) $value as $groupTypeValue) { |
| 2995 | $groupList = CRM_Core_PseudoConstant::group($groupTypeValue); |
| 2996 | $groupIds = ($groupIds + $groupList); |
| 2997 | } |
| 2998 | return $groupIds; |
| 2999 | } |
| 3000 | |
| 3001 | /** |
| 3002 | * @param array $groups |
| 3003 | * @param string $tableAlias |
| 3004 | * @param string $joinTable |
| 3005 | * @param string $op |
| 3006 | * |
| 3007 | * @return null|string |
| 3008 | */ |
| 3009 | public function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a", $op) { |
| 3010 | $isNullOp = (strpos($op, 'NULL') !== FALSE); |
| 3011 | $groupsIds = $groups; |
| 3012 | if (!$isNullOp && !$groups) { |
| 3013 | return NULL; |
| 3014 | } |
| 3015 | elseif (strpos($op, 'IN') !== FALSE) { |
| 3016 | $groups = array($op => $groups); |
| 3017 | } |
| 3018 | elseif (is_array($groups) && count($groups)) { |
| 3019 | $groups = array('IN' => $groups); |
| 3020 | } |
| 3021 | |
| 3022 | // Find all the groups that are part of a saved search. |
| 3023 | $smartGroupClause = self::buildClause("id", $op, $groups, 'Int'); |
| 3024 | $sql = " |
| 3025 | SELECT id, cache_date, saved_search_id, children |
| 3026 | FROM civicrm_group |
| 3027 | WHERE $smartGroupClause |
| 3028 | AND ( saved_search_id != 0 |
| 3029 | OR saved_search_id IS NOT NULL |
| 3030 | OR children IS NOT NULL ) |
| 3031 | "; |
| 3032 | |
| 3033 | $group = CRM_Core_DAO::executeQuery($sql); |
| 3034 | |
| 3035 | while ($group->fetch()) { |
| 3036 | $this->_useDistinct = TRUE; |
| 3037 | if (!$this->_smartGroupCache || $group->cache_date == NULL) { |
| 3038 | CRM_Contact_BAO_GroupContactCache::load($group); |
| 3039 | } |
| 3040 | } |
| 3041 | if ($group->N == 0) { |
| 3042 | return NULL; |
| 3043 | } |
| 3044 | |
| 3045 | if (!$tableAlias) { |
| 3046 | $tableAlias = "`civicrm_group_contact_cache_"; |
| 3047 | $tableAlias .= ($isNullOp) ? "a`" : implode(',', (array) $groupsIds) . "`"; |
| 3048 | } |
| 3049 | |
| 3050 | $this->_tables[$tableAlias] = $this->_whereTables[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.id = {$tableAlias}.contact_id "; |
| 3051 | return self::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int'); |
| 3052 | } |
| 3053 | |
| 3054 | /** |
| 3055 | * Where / qill clause for cms users |
| 3056 | * |
| 3057 | * @param $values |
| 3058 | */ |
| 3059 | public function ufUser(&$values) { |
| 3060 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3061 | |
| 3062 | if ($value == 1) { |
| 3063 | $this->_tables['civicrm_uf_match'] = $this->_whereTables['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id '; |
| 3064 | |
| 3065 | $this->_qill[$grouping][] = ts('CMS User'); |
| 3066 | } |
| 3067 | elseif ($value == 0) { |
| 3068 | $this->_tables['civicrm_uf_match'] = $this->_whereTables['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id '; |
| 3069 | |
| 3070 | $this->_where[$grouping][] = " civicrm_uf_match.contact_id IS NULL"; |
| 3071 | $this->_qill[$grouping][] = ts('Not a CMS User'); |
| 3072 | } |
| 3073 | } |
| 3074 | |
| 3075 | /** |
| 3076 | * All tag search specific. |
| 3077 | * |
| 3078 | * @param array $values |
| 3079 | */ |
| 3080 | public function tagSearch(&$values) { |
| 3081 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3082 | |
| 3083 | $op = "LIKE"; |
| 3084 | $value = "%{$value}%"; |
| 3085 | |
| 3086 | $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping); |
| 3087 | $tagTypesText = $this->getWhereValues('tag_types_text', $grouping); |
| 3088 | |
| 3089 | $etTable = "`civicrm_entity_tag-" . $value . "`"; |
| 3090 | $tTable = "`civicrm_tag-" . $value . "`"; |
| 3091 | |
| 3092 | if ($useAllTagTypes[2]) { |
| 3093 | $this->_tables[$etTable] = $this->_whereTables[$etTable] |
| 3094 | = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id) |
| 3095 | LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )"; |
| 3096 | |
| 3097 | // search tag in cases |
| 3098 | $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`"; |
| 3099 | $tCaseTable = "`civicrm_case_tag-" . $value . "`"; |
| 3100 | $this->_tables[$etCaseTable] = $this->_whereTables[$etCaseTable] |
| 3101 | = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id |
| 3102 | LEFT JOIN civicrm_case |
| 3103 | ON (civicrm_case_contact.case_id = civicrm_case.id |
| 3104 | AND civicrm_case.is_deleted = 0 ) |
| 3105 | LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) |
| 3106 | LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )"; |
| 3107 | // search tag in activities |
| 3108 | $etActTable = "`civicrm_entity_act_tag-" . $value . "`"; |
| 3109 | $tActTable = "`civicrm_act_tag-" . $value . "`"; |
| 3110 | $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); |
| 3111 | $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); |
| 3112 | |
| 3113 | $this->_tables[$etActTable] = $this->_whereTables[$etActTable] |
| 3114 | = " LEFT JOIN civicrm_activity_contact |
| 3115 | ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} ) |
| 3116 | LEFT JOIN civicrm_activity |
| 3117 | ON ( civicrm_activity.id = civicrm_activity_contact.activity_id |
| 3118 | AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 ) |
| 3119 | LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) |
| 3120 | LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )"; |
| 3121 | |
| 3122 | $this->_where[$grouping][] = "({$tTable}.name $op '" . $value . "' OR {$tCaseTable}.name $op '" . $value . "' OR {$tActTable}.name $op '" . $value . "')"; |
| 3123 | $this->_qill[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value; |
| 3124 | } |
| 3125 | else { |
| 3126 | $etTable = "`civicrm_entity_tag-" . $value . "`"; |
| 3127 | $tTable = "`civicrm_tag-" . $value . "`"; |
| 3128 | $this->_tables[$etTable] = $this->_whereTables[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND |
| 3129 | {$etTable}.entity_table = 'civicrm_contact' ) |
| 3130 | LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) "; |
| 3131 | |
| 3132 | $this->_where[$grouping][] = self::buildClause("{$tTable}.name", $op, $value, 'String'); |
| 3133 | $this->_qill[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value; |
| 3134 | } |
| 3135 | } |
| 3136 | |
| 3137 | /** |
| 3138 | * Where / qill clause for tag |
| 3139 | * |
| 3140 | * @param array $values |
| 3141 | */ |
| 3142 | public function tag(&$values) { |
| 3143 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3144 | |
| 3145 | list($qillop, $qillVal) = self::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, array('onlyActive' => FALSE)); |
| 3146 | // API/Search Builder format array(operator => array(values)) |
| 3147 | if (is_array($value)) { |
| 3148 | if (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) { |
| 3149 | $op = key($value); |
| 3150 | $value = $value[$op]; |
| 3151 | } |
| 3152 | if (count($value) > 1) { |
| 3153 | $this->_useDistinct = TRUE; |
| 3154 | } |
| 3155 | $value = implode(',', (array) $value); |
| 3156 | } |
| 3157 | |
| 3158 | $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping); |
| 3159 | $tagTypesText = $this->getWhereValues('tag_types_text', $grouping); |
| 3160 | |
| 3161 | $etTable = "`civicrm_entity_tag-" . $value . "`"; |
| 3162 | |
| 3163 | if ($useAllTagTypes[2]) { |
| 3164 | $this->_tables[$etTable] = $this->_whereTables[$etTable] |
| 3165 | = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') "; |
| 3166 | |
| 3167 | // search tag in cases |
| 3168 | $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`"; |
| 3169 | $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); |
| 3170 | $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); |
| 3171 | |
| 3172 | $this->_tables[$etCaseTable] = $this->_whereTables[$etCaseTable] |
| 3173 | = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id |
| 3174 | LEFT JOIN civicrm_case |
| 3175 | ON (civicrm_case_contact.case_id = civicrm_case.id |
| 3176 | AND civicrm_case.is_deleted = 0 ) |
| 3177 | LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) "; |
| 3178 | // search tag in activities |
| 3179 | $etActTable = "`civicrm_entity_act_tag-" . $value . "`"; |
| 3180 | $this->_tables[$etActTable] = $this->_whereTables[$etActTable] |
| 3181 | = " LEFT JOIN civicrm_activity_contact |
| 3182 | ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} ) |
| 3183 | LEFT JOIN civicrm_activity |
| 3184 | ON ( civicrm_activity.id = civicrm_activity_contact.activity_id |
| 3185 | AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 ) |
| 3186 | LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) "; |
| 3187 | |
| 3188 | // CRM-10338 |
| 3189 | if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) { |
| 3190 | $this->_where[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)"; |
| 3191 | } |
| 3192 | else { |
| 3193 | $this->_where[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))"; |
| 3194 | } |
| 3195 | } |
| 3196 | else { |
| 3197 | $this->_tables[$etTable] = $this->_whereTables[$etTable] |
| 3198 | = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') "; |
| 3199 | |
| 3200 | // CRM-10338 |
| 3201 | if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) { |
| 3202 | // this converts IS (NOT)? EMPTY to IS (NOT)? NULL |
| 3203 | $op = str_replace('EMPTY', 'NULL', $op); |
| 3204 | $this->_where[$grouping][] = "{$etTable}.tag_id $op"; |
| 3205 | } |
| 3206 | // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag |
| 3207 | elseif ($op == '!=') { |
| 3208 | $this->_where[$grouping][] = "{$etTable}.entity_id NOT IN (SELECT entity_id FROM civicrm_entity_tag cet WHERE cet.entity_table = 'civicrm_contact' AND " . self::buildClause("cet.tag_id", '=', $value, 'Int') . ")"; |
| 3209 | } |
| 3210 | elseif ($op == '=' || strstr($op, 'IN')) { |
| 3211 | $op = ($op == '=') ? 'IN' : $op; |
| 3212 | $this->_where[$grouping][] = "{$etTable}.tag_id $op ( $value )"; |
| 3213 | } |
| 3214 | } |
| 3215 | $this->_qill[$grouping][] = ts('Tagged %1 %2', array(1 => $qillop, 2 => $qillVal)); |
| 3216 | } |
| 3217 | |
| 3218 | /** |
| 3219 | * Where/qill clause for notes |
| 3220 | * |
| 3221 | * @param array $values |
| 3222 | */ |
| 3223 | public function notes(&$values) { |
| 3224 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3225 | |
| 3226 | $noteOptionValues = $this->getWhereValues('note_option', $grouping); |
| 3227 | $noteOption = CRM_Utils_Array::value('2', $noteOptionValues, '6'); |
| 3228 | $noteOption = ($name == 'note_body') ? 2 : (($name == 'note_subject') ? 3 : $noteOption); |
| 3229 | |
| 3230 | $this->_useDistinct = TRUE; |
| 3231 | |
| 3232 | $this->_tables['civicrm_note'] = $this->_whereTables['civicrm_note'] |
| 3233 | = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) "; |
| 3234 | |
| 3235 | $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower'; |
| 3236 | $n = trim($value); |
| 3237 | $value = $strtolower(CRM_Core_DAO::escapeString($n)); |
| 3238 | if ($wildcard) { |
| 3239 | if (strpos($value, '%') === FALSE) { |
| 3240 | $value = "%$value%"; |
| 3241 | } |
| 3242 | $op = 'LIKE'; |
| 3243 | } |
| 3244 | elseif ($op == 'IS NULL' || $op == 'IS NOT NULL') { |
| 3245 | $value = NULL; |
| 3246 | } |
| 3247 | |
| 3248 | $label = NULL; |
| 3249 | $clauses = array(); |
| 3250 | if ($noteOption % 2 == 0) { |
| 3251 | $clauses[] = self::buildClause('civicrm_note.note', $op, $value, 'String'); |
| 3252 | $label = ts('Note: Body Only'); |
| 3253 | } |
| 3254 | if ($noteOption % 3 == 0) { |
| 3255 | $clauses[] = self::buildClause('civicrm_note.subject', $op, $value, 'String'); |
| 3256 | $label = $label ? ts('Note: Body and Subject') : ts('Note: Subject Only'); |
| 3257 | } |
| 3258 | $this->_where[$grouping][] = "( " . implode(' OR ', $clauses) . " )"; |
| 3259 | list($qillOp, $qillVal) = self::buildQillForFieldValue(NULL, $name, $n, $op); |
| 3260 | $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillOp, 3 => $qillVal)); |
| 3261 | } |
| 3262 | |
| 3263 | /** |
| 3264 | * @param string $name |
| 3265 | * @param $op |
| 3266 | * @param $grouping |
| 3267 | * |
| 3268 | * @return bool |
| 3269 | */ |
| 3270 | public function nameNullOrEmptyOp($name, $op, $grouping) { |
| 3271 | switch ($op) { |
| 3272 | case 'IS NULL': |
| 3273 | case 'IS NOT NULL': |
| 3274 | $this->_where[$grouping][] = "contact_a.$name $op"; |
| 3275 | $this->_qill[$grouping][] = ts('Name') . ' ' . $op; |
| 3276 | return TRUE; |
| 3277 | |
| 3278 | case 'IS EMPTY': |
| 3279 | $this->_where[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')"; |
| 3280 | $this->_qill[$grouping][] = ts('Name') . ' ' . $op; |
| 3281 | return TRUE; |
| 3282 | |
| 3283 | case 'IS NOT EMPTY': |
| 3284 | $this->_where[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')"; |
| 3285 | $this->_qill[$grouping][] = ts('Name') . ' ' . $op; |
| 3286 | return TRUE; |
| 3287 | |
| 3288 | default: |
| 3289 | return FALSE; |
| 3290 | } |
| 3291 | } |
| 3292 | |
| 3293 | /** |
| 3294 | * Where / qill clause for sort_name |
| 3295 | * |
| 3296 | * @param array $values |
| 3297 | */ |
| 3298 | public function sortName(&$values) { |
| 3299 | list($fieldName, $op, $value, $grouping, $wildcard) = $values; |
| 3300 | |
| 3301 | // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY |
| 3302 | if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) { |
| 3303 | return; |
| 3304 | } |
| 3305 | |
| 3306 | $input = $value = trim($value); |
| 3307 | |
| 3308 | if (!strlen($value)) { |
| 3309 | return; |
| 3310 | } |
| 3311 | |
| 3312 | $config = CRM_Core_Config::singleton(); |
| 3313 | |
| 3314 | $sub = array(); |
| 3315 | |
| 3316 | //By default, $sub elements should be joined together with OR statements (don't change this variable). |
| 3317 | $subGlue = ' OR '; |
| 3318 | |
| 3319 | $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower'; |
| 3320 | |
| 3321 | $firstChar = substr($value, 0, 1); |
| 3322 | $lastChar = substr($value, -1, 1); |
| 3323 | $quotes = array("'", '"'); |
| 3324 | // If string is quoted, strip quotes and otherwise don't alter it |
| 3325 | if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) { |
| 3326 | $value = trim($value, implode('', $quotes)); |
| 3327 | } |
| 3328 | // Replace spaces with wildcards for a LIKE operation |
| 3329 | // UNLESS string contains a comma (this exception is a tiny bit questionable) |
| 3330 | elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) { |
| 3331 | $value = str_replace(' ', '%', $value); |
| 3332 | } |
| 3333 | $value = $strtolower(CRM_Core_DAO::escapeString(trim($value))); |
| 3334 | if (strlen($value)) { |
| 3335 | $fieldsub = array(); |
| 3336 | $value = "'" . self::getWildCardedValue($wildcard, $op, $value) . "'"; |
| 3337 | if ($fieldName == 'sort_name') { |
| 3338 | // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811. |
| 3339 | $wc = self::caseImportant($op) ? "LOWER(contact_a.sort_name)" : "contact_a.sort_name"; |
| 3340 | } |
| 3341 | else { |
| 3342 | // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811. |
| 3343 | $wc = self::caseImportant($op) ? "LOWER(contact_a.display_name)" : "contact_a.display_name"; |
| 3344 | } |
| 3345 | $fieldsub[] = " ( $wc $op $value )"; |
| 3346 | if ($config->includeNickNameInName) { |
| 3347 | // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811. |
| 3348 | $wc = self::caseImportant($op) ? "LOWER(contact_a.nick_name)" : "contact_a.nick_name"; |
| 3349 | $fieldsub[] = " ( $wc $op $value )"; |
| 3350 | } |
| 3351 | if ($config->includeEmailInName) { |
| 3352 | $fieldsub[] = " ( civicrm_email.email $op $value ) "; |
| 3353 | } |
| 3354 | $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) '; |
| 3355 | } |
| 3356 | |
| 3357 | $sub = ' ( ' . implode($subGlue, $sub) . ' ) '; |
| 3358 | |
| 3359 | $this->_where[$grouping][] = $sub; |
| 3360 | if ($config->includeEmailInName) { |
| 3361 | $this->_tables['civicrm_email'] = $this->_whereTables['civicrm_email'] = 1; |
| 3362 | $this->_qill[$grouping][] = ts('Name or Email') . " $op - '$input'"; |
| 3363 | } |
| 3364 | else { |
| 3365 | $this->_qill[$grouping][] = ts('Name') . " $op - '$input'"; |
| 3366 | } |
| 3367 | } |
| 3368 | |
| 3369 | /** |
| 3370 | * Where/qill clause for greeting fields. |
| 3371 | * |
| 3372 | * @param array $values |
| 3373 | */ |
| 3374 | public function greetings(&$values) { |
| 3375 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3376 | $name .= '_display'; |
| 3377 | |
| 3378 | list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $name, $value, $op); |
| 3379 | $this->_qill[$grouping][] = ts('Greeting %1 %2', array(1 => $qillop, 2 => $qillVal)); |
| 3380 | $this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $value, 'String'); |
| 3381 | } |
| 3382 | |
| 3383 | /** |
| 3384 | * Where / qill clause for email |
| 3385 | * |
| 3386 | * @param array $values |
| 3387 | * @param string $apiEntity |
| 3388 | */ |
| 3389 | protected function email(&$values, $apiEntity) { |
| 3390 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3391 | $this->_tables['civicrm_email'] = $this->_whereTables['civicrm_email'] = 1; |
| 3392 | |
| 3393 | // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name} |
| 3394 | // so following code is use build whereClause for contact's primart email id |
| 3395 | if (!empty($apiEntity)) { |
| 3396 | $dataType = 'String'; |
| 3397 | if ($name == 'email_id') { |
| 3398 | $dataType = 'Integer'; |
| 3399 | $name = 'id'; |
| 3400 | } |
| 3401 | |
| 3402 | $this->_where[$grouping][] = self::buildClause('civicrm_email.is_primary', '=', 1, 'Integer'); |
| 3403 | $this->_where[$grouping][] = self::buildClause("civicrm_email.$name", $op, $value, $dataType); |
| 3404 | return; |
| 3405 | } |
| 3406 | |
| 3407 | $n = strtolower(trim($value)); |
| 3408 | if ($n) { |
| 3409 | if (substr($n, 0, 1) == '"' && |
| 3410 | substr($n, -1, 1) == '"' |
| 3411 | ) { |
| 3412 | $n = substr($n, 1, -1); |
| 3413 | $value = CRM_Core_DAO::escapeString($n); |
| 3414 | $op = '='; |
| 3415 | } |
| 3416 | else { |
| 3417 | $value = self::getWildCardedValue($wildcard, $op, $n); |
| 3418 | } |
| 3419 | $this->_qill[$grouping][] = ts('Email') . " $op '$n'"; |
| 3420 | $this->_where[$grouping][] = self::buildClause('civicrm_email.email', $op, $value, 'String'); |
| 3421 | } |
| 3422 | else { |
| 3423 | $this->_qill[$grouping][] = ts('Email') . " $op "; |
| 3424 | $this->_where[$grouping][] = self::buildClause('civicrm_email.email', $op, NULL, 'String'); |
| 3425 | } |
| 3426 | } |
| 3427 | |
| 3428 | /** |
| 3429 | * Where / qill clause for phone number |
| 3430 | * |
| 3431 | * @param array $values |
| 3432 | */ |
| 3433 | public function phone_numeric(&$values) { |
| 3434 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3435 | // Strip non-numeric characters; allow wildcards |
| 3436 | $number = preg_replace('/[^\d%]/', '', $value); |
| 3437 | if ($number) { |
| 3438 | if (strpos($number, '%') === FALSE) { |
| 3439 | $number = "%$number%"; |
| 3440 | } |
| 3441 | |
| 3442 | $this->_qill[$grouping][] = ts('Phone number contains') . " $number"; |
| 3443 | $this->_where[$grouping][] = self::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String'); |
| 3444 | $this->_tables['civicrm_phone'] = $this->_whereTables['civicrm_phone'] = 1; |
| 3445 | } |
| 3446 | } |
| 3447 | |
| 3448 | /** |
| 3449 | * Where / qill clause for phone type/location |
| 3450 | * |
| 3451 | * @param array $values |
| 3452 | */ |
| 3453 | public function phone_option_group($values) { |
| 3454 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3455 | $option = ($name == 'phone_phone_type_id' ? 'phone_type_id' : 'location_type_id'); |
| 3456 | $options = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', $option); |
| 3457 | $optionName = $options[$value]; |
| 3458 | $this->_qill[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ? ts('type') : ('location')) . " $op $optionName"; |
| 3459 | $this->_where[$grouping][] = self::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer'); |
| 3460 | $this->_tables['civicrm_phone'] = $this->_whereTables['civicrm_phone'] = 1; |
| 3461 | } |
| 3462 | |
| 3463 | /** |
| 3464 | * Where / qill clause for street_address. |
| 3465 | * |
| 3466 | * @param array $values |
| 3467 | */ |
| 3468 | public function street_address(&$values) { |
| 3469 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3470 | |
| 3471 | if (!$op) { |
| 3472 | $op = 'LIKE'; |
| 3473 | } |
| 3474 | |
| 3475 | $n = trim($value); |
| 3476 | |
| 3477 | if ($n) { |
| 3478 | $value = strtolower($n); |
| 3479 | if (strpos($value, '%') === FALSE) { |
| 3480 | // only add wild card if not there |
| 3481 | $value = "%{$value}%"; |
| 3482 | } |
| 3483 | $op = 'LIKE'; |
| 3484 | // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811. |
| 3485 | $this->_where[$grouping][] = self::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String'); |
| 3486 | $this->_qill[$grouping][] = ts('Street') . " $op '$n'"; |
| 3487 | } |
| 3488 | else { |
| 3489 | $this->_where[$grouping][] = self::buildClause('civicrm_address.street_address', $op, NULL, 'String'); |
| 3490 | $this->_qill[$grouping][] = ts('Street') . " $op "; |
| 3491 | } |
| 3492 | |
| 3493 | $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1; |
| 3494 | } |
| 3495 | |
| 3496 | /** |
| 3497 | * Where / qill clause for street_unit. |
| 3498 | * |
| 3499 | * @param array $values |
| 3500 | */ |
| 3501 | public function street_number(&$values) { |
| 3502 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3503 | |
| 3504 | if (!$op) { |
| 3505 | $op = '='; |
| 3506 | } |
| 3507 | |
| 3508 | $n = trim($value); |
| 3509 | |
| 3510 | if (strtolower($n) == 'odd') { |
| 3511 | $this->_where[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )"; |
| 3512 | $this->_qill[$grouping][] = ts('Street Number is odd'); |
| 3513 | } |
| 3514 | elseif (strtolower($n) == 'even') { |
| 3515 | $this->_where[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )"; |
| 3516 | $this->_qill[$grouping][] = ts('Street Number is even'); |
| 3517 | } |
| 3518 | else { |
| 3519 | $value = strtolower($n); |
| 3520 | |
| 3521 | // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811. |
| 3522 | $this->_where[$grouping][] = self::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String'); |
| 3523 | $this->_qill[$grouping][] = ts('Street Number') . " $op '$n'"; |
| 3524 | } |
| 3525 | |
| 3526 | $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1; |
| 3527 | } |
| 3528 | |
| 3529 | /** |
| 3530 | * Where / qill clause for sorting by character. |
| 3531 | * |
| 3532 | * @param array $values |
| 3533 | */ |
| 3534 | public function sortByCharacter(&$values) { |
| 3535 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3536 | |
| 3537 | $name = trim($value); |
| 3538 | $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO::escapeWildCardString($name)) . "%'"; |
| 3539 | $this->_where[$grouping][] = $cond; |
| 3540 | $this->_qill[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name)); |
| 3541 | } |
| 3542 | |
| 3543 | /** |
| 3544 | * Where / qill clause for including contact ids. |
| 3545 | */ |
| 3546 | public function includeContactIDs() { |
| 3547 | if (!$this->_includeContactIds || empty($this->_params)) { |
| 3548 | return; |
| 3549 | } |
| 3550 | |
| 3551 | $contactIds = array(); |
| 3552 | foreach ($this->_params as $id => $values) { |
| 3553 | if (substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) { |
| 3554 | $contactIds[] = substr($values[0], CRM_Core_Form::CB_PREFIX_LEN); |
| 3555 | } |
| 3556 | } |
| 3557 | CRM_Utils_Type::validateAll($contactIds, 'Positive'); |
| 3558 | if (!empty($contactIds)) { |
| 3559 | $this->_where[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) "; |
| 3560 | } |
| 3561 | } |
| 3562 | |
| 3563 | /** |
| 3564 | * Where / qill clause for postal code. |
| 3565 | * |
| 3566 | * @param array $values |
| 3567 | */ |
| 3568 | public function postalCode(&$values) { |
| 3569 | // skip if the fields dont have anything to do with postal_code |
| 3570 | if (empty($this->_fields['postal_code'])) { |
| 3571 | return; |
| 3572 | } |
| 3573 | |
| 3574 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3575 | |
| 3576 | // Handle numeric postal code range searches properly by casting the column as numeric |
| 3577 | if (is_numeric($value)) { |
| 3578 | $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]+$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)"; |
| 3579 | $val = CRM_Utils_Type::escape($value, 'Integer'); |
| 3580 | } |
| 3581 | else { |
| 3582 | $field = 'civicrm_address.postal_code'; |
| 3583 | // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string. |
| 3584 | if (!is_array($value)) { |
| 3585 | $val = CRM_Utils_Type::escape($value, 'String'); |
| 3586 | } |
| 3587 | else { |
| 3588 | // Do we need to escape values here? I would expect buildClause does. |
| 3589 | $val = $value; |
| 3590 | } |
| 3591 | } |
| 3592 | |
| 3593 | $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1; |
| 3594 | |
| 3595 | if ($name == 'postal_code') { |
| 3596 | $this->_where[$grouping][] = self::buildClause($field, $op, $val, 'String'); |
| 3597 | $this->_qill[$grouping][] = ts('Postal code') . " {$op} {$value}"; |
| 3598 | } |
| 3599 | elseif ($name == 'postal_code_low') { |
| 3600 | $this->_where[$grouping][] = " ( $field >= '$val' ) "; |
| 3601 | $this->_qill[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value)); |
| 3602 | } |
| 3603 | elseif ($name == 'postal_code_high') { |
| 3604 | $this->_where[$grouping][] = " ( $field <= '$val' ) "; |
| 3605 | $this->_qill[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value)); |
| 3606 | } |
| 3607 | } |
| 3608 | |
| 3609 | /** |
| 3610 | * Where / qill clause for location type. |
| 3611 | * |
| 3612 | * @param array $values |
| 3613 | * @param null $status |
| 3614 | * |
| 3615 | * @return string |
| 3616 | */ |
| 3617 | public function locationType(&$values, $status = NULL) { |
| 3618 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3619 | |
| 3620 | if (is_array($value)) { |
| 3621 | $this->_where[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')'; |
| 3622 | $this->_tables['civicrm_address'] = 1; |
| 3623 | $this->_whereTables['civicrm_address'] = 1; |
| 3624 | |
| 3625 | $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); |
| 3626 | $names = array(); |
| 3627 | foreach ($value as $id) { |
| 3628 | $names[] = $locationType[$id]; |
| 3629 | } |
| 3630 | |
| 3631 | $this->_primaryLocation = FALSE; |
| 3632 | |
| 3633 | if (!$status) { |
| 3634 | $this->_qill[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names); |
| 3635 | } |
| 3636 | else { |
| 3637 | return implode(' ' . ts('or') . ' ', $names); |
| 3638 | } |
| 3639 | } |
| 3640 | } |
| 3641 | |
| 3642 | /** |
| 3643 | * @param $values |
| 3644 | * @param bool $fromStateProvince |
| 3645 | * |
| 3646 | * @return array|NULL |
| 3647 | */ |
| 3648 | public function country(&$values, $fromStateProvince = TRUE) { |
| 3649 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3650 | |
| 3651 | if (!$fromStateProvince) { |
| 3652 | $stateValues = $this->getWhereValues('state_province', $grouping); |
| 3653 | if (!empty($stateValues)) { |
| 3654 | // return back to caller if there are state province values |
| 3655 | // since that handles this case |
| 3656 | return NULL; |
| 3657 | } |
| 3658 | } |
| 3659 | |
| 3660 | $countryClause = $countryQill = NULL; |
| 3661 | if ($values && !empty($value)) { |
| 3662 | $this->_tables['civicrm_address'] = 1; |
| 3663 | $this->_whereTables['civicrm_address'] = 1; |
| 3664 | |
| 3665 | $countryClause = self::buildClause('civicrm_address.country_id', $op, $value, 'Positive'); |
| 3666 | list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, 'country_id', $value, $op); |
| 3667 | $countryQill = ts("%1 %2 %3", array(1 => 'Country', 2 => $qillop, 3 => $qillVal)); |
| 3668 | |
| 3669 | if (!$fromStateProvince) { |
| 3670 | $this->_where[$grouping][] = $countryClause; |
| 3671 | $this->_qill[$grouping][] = $countryQill; |
| 3672 | } |
| 3673 | } |
| 3674 | |
| 3675 | if ($fromStateProvince) { |
| 3676 | if (!empty($countryClause)) { |
| 3677 | return array( |
| 3678 | $countryClause, |
| 3679 | " ...AND... " . $countryQill, |
| 3680 | ); |
| 3681 | } |
| 3682 | else { |
| 3683 | return array(NULL, NULL); |
| 3684 | } |
| 3685 | } |
| 3686 | } |
| 3687 | |
| 3688 | /** |
| 3689 | * Where / qill clause for county (if present). |
| 3690 | * |
| 3691 | * @param array $values |
| 3692 | * @param null $status |
| 3693 | * |
| 3694 | * @return string |
| 3695 | */ |
| 3696 | public function county(&$values, $status = NULL) { |
| 3697 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3698 | |
| 3699 | if (!is_array($value)) { |
| 3700 | // force the county to be an array |
| 3701 | $value = array($value); |
| 3702 | } |
| 3703 | |
| 3704 | // check if the values are ids OR names of the counties |
| 3705 | $inputFormat = 'id'; |
| 3706 | foreach ($value as $v) { |
| 3707 | if (!is_numeric($v)) { |
| 3708 | $inputFormat = 'name'; |
| 3709 | break; |
| 3710 | } |
| 3711 | } |
| 3712 | $names = array(); |
| 3713 | if ($op == '=') { |
| 3714 | $op = 'IN'; |
| 3715 | } |
| 3716 | elseif ($op == '!=') { |
| 3717 | $op = 'NOT IN'; |
| 3718 | } |
| 3719 | else { |
| 3720 | // this converts IS (NOT)? EMPTY to IS (NOT)? NULL |
| 3721 | $op = str_replace('EMPTY', 'NULL', $op); |
| 3722 | } |
| 3723 | |
| 3724 | if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) { |
| 3725 | $clause = "civicrm_address.county_id $op"; |
| 3726 | } |
| 3727 | elseif ($inputFormat == 'id') { |
| 3728 | $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')'; |
| 3729 | |
| 3730 | $county = CRM_Core_PseudoConstant::county(); |
| 3731 | foreach ($value as $id) { |
| 3732 | $names[] = CRM_Utils_Array::value($id, $county); |
| 3733 | } |
| 3734 | } |
| 3735 | else { |
| 3736 | $inputClause = array(); |
| 3737 | $county = CRM_Core_PseudoConstant::county(); |
| 3738 | foreach ($value as $name) { |
| 3739 | $name = trim($name); |
| 3740 | $inputClause[] = CRM_Utils_Array::key($name, $county); |
| 3741 | } |
| 3742 | $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')'; |
| 3743 | $names = $value; |
| 3744 | } |
| 3745 | $this->_tables['civicrm_address'] = 1; |
| 3746 | $this->_whereTables['civicrm_address'] = 1; |
| 3747 | |
| 3748 | $this->_where[$grouping][] = $clause; |
| 3749 | if (!$status) { |
| 3750 | $this->_qill[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names); |
| 3751 | } |
| 3752 | else { |
| 3753 | return implode(' ' . ts('or') . ' ', $names); |
| 3754 | } |
| 3755 | } |
| 3756 | |
| 3757 | /** |
| 3758 | * Where / qill clause for state/province AND country (if present). |
| 3759 | * |
| 3760 | * @param array $values |
| 3761 | * @param null $status |
| 3762 | * |
| 3763 | * @return string |
| 3764 | */ |
| 3765 | public function stateProvince(&$values, $status = NULL) { |
| 3766 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3767 | |
| 3768 | $stateClause = self::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive'); |
| 3769 | $this->_tables['civicrm_address'] = 1; |
| 3770 | $this->_whereTables['civicrm_address'] = 1; |
| 3771 | |
| 3772 | $countryValues = $this->getWhereValues('country', $grouping); |
| 3773 | list($countryClause, $countryQill) = $this->country($countryValues, TRUE); |
| 3774 | if ($countryClause) { |
| 3775 | $clause = "( $stateClause AND $countryClause )"; |
| 3776 | } |
| 3777 | else { |
| 3778 | $clause = $stateClause; |
| 3779 | } |
| 3780 | |
| 3781 | $this->_where[$grouping][] = $clause; |
| 3782 | list($qillop, $qillVal) = self::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op); |
| 3783 | if (!$status) { |
| 3784 | $this->_qill[$grouping][] = ts("State/Province %1 %2 %3", array(1 => $qillop, 2 => $qillVal, 3 => $countryQill)); |
| 3785 | } |
| 3786 | else { |
| 3787 | return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill; |
| 3788 | } |
| 3789 | } |
| 3790 | |
| 3791 | /** |
| 3792 | * Where / qill clause for change log. |
| 3793 | * |
| 3794 | * @param array $values |
| 3795 | */ |
| 3796 | public function changeLog(&$values) { |
| 3797 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3798 | |
| 3799 | $targetName = $this->getWhereValues('changed_by', $grouping); |
| 3800 | if (!$targetName) { |
| 3801 | return; |
| 3802 | } |
| 3803 | |
| 3804 | $name = trim($targetName[2]); |
| 3805 | $name = strtolower(CRM_Core_DAO::escapeString($name)); |
| 3806 | $name = $targetName[4] ? "%$name%" : $name; |
| 3807 | $this->_where[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'"; |
| 3808 | $this->_tables['civicrm_log'] = $this->_whereTables['civicrm_log'] = 1; |
| 3809 | $this->_qill[$grouping][] = ts('Modified By') . " $name"; |
| 3810 | } |
| 3811 | |
| 3812 | /** |
| 3813 | * @param $values |
| 3814 | */ |
| 3815 | public function modifiedDates($values) { |
| 3816 | $this->_useDistinct = TRUE; |
| 3817 | |
| 3818 | // CRM-11281, default to added date if not set |
| 3819 | $fieldTitle = ts('Added Date'); |
| 3820 | $fieldName = 'created_date'; |
| 3821 | foreach (array_keys($this->_params) as $id) { |
| 3822 | if ($this->_params[$id][0] == 'log_date') { |
| 3823 | if ($this->_params[$id][2] == 2) { |
| 3824 | $fieldTitle = ts('Modified Date'); |
| 3825 | $fieldName = 'modified_date'; |
| 3826 | } |
| 3827 | } |
| 3828 | } |
| 3829 | |
| 3830 | $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle); |
| 3831 | |
| 3832 | self::$_openedPanes[ts('Change Log')] = TRUE; |
| 3833 | } |
| 3834 | |
| 3835 | /** |
| 3836 | * @param $values |
| 3837 | */ |
| 3838 | public function demographics(&$values) { |
| 3839 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3840 | |
| 3841 | if (($name == 'age_low') || ($name == 'age_high')) { |
| 3842 | $this->ageRangeQueryBuilder($values, |
| 3843 | 'contact_a', 'age', 'birth_date', ts('Age') |
| 3844 | ); |
| 3845 | } |
| 3846 | elseif (($name == 'birth_date_low') || ($name == 'birth_date_high')) { |
| 3847 | |
| 3848 | $this->dateQueryBuilder($values, |
| 3849 | 'contact_a', 'birth_date', 'birth_date', ts('Birth Date') |
| 3850 | ); |
| 3851 | } |
| 3852 | elseif (($name == 'deceased_date_low') || ($name == 'deceased_date_high')) { |
| 3853 | |
| 3854 | $this->dateQueryBuilder($values, |
| 3855 | 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date') |
| 3856 | ); |
| 3857 | } |
| 3858 | |
| 3859 | self::$_openedPanes[ts('Demographics')] = TRUE; |
| 3860 | } |
| 3861 | |
| 3862 | /** |
| 3863 | * @param $values |
| 3864 | */ |
| 3865 | public function privacy(&$values) { |
| 3866 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3867 | //fixed for profile search listing CRM-4633 |
| 3868 | if (strpbrk($value, "[")) { |
| 3869 | $value = "'{$value}'"; |
| 3870 | $op = "!{$op}"; |
| 3871 | $this->_where[$grouping][] = "contact_a.{$name} $op $value"; |
| 3872 | } |
| 3873 | else { |
| 3874 | $this->_where[$grouping][] = "contact_a.{$name} $op $value"; |
| 3875 | } |
| 3876 | $field = CRM_Utils_Array::value($name, $this->_fields); |
| 3877 | $op = CRM_Utils_Array::value($op, CRM_Core_SelectValues::getSearchBuilderOperators(), $op); |
| 3878 | $title = $field ? $field['title'] : $name; |
| 3879 | $this->_qill[$grouping][] = "$title $op $value"; |
| 3880 | } |
| 3881 | |
| 3882 | /** |
| 3883 | * @param $values |
| 3884 | */ |
| 3885 | public function privacyOptions($values) { |
| 3886 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3887 | |
| 3888 | if (empty($value) || !is_array($value)) { |
| 3889 | return; |
| 3890 | } |
| 3891 | |
| 3892 | // get the operator and toggle values |
| 3893 | $opValues = $this->getWhereValues('privacy_operator', $grouping); |
| 3894 | $operator = 'OR'; |
| 3895 | if ($opValues && |
| 3896 | strtolower($opValues[2] == 'AND') |
| 3897 | ) { |
| 3898 | $operator = 'AND'; |
| 3899 | } |
| 3900 | |
| 3901 | $toggleValues = $this->getWhereValues('privacy_toggle', $grouping); |
| 3902 | $compareOP = '!'; |
| 3903 | if ($toggleValues && |
| 3904 | $toggleValues[2] == 2 |
| 3905 | ) { |
| 3906 | $compareOP = ''; |
| 3907 | } |
| 3908 | |
| 3909 | $clauses = array(); |
| 3910 | $qill = array(); |
| 3911 | foreach ($value as $dontCare => $pOption) { |
| 3912 | $clauses[] = " ( contact_a.{$pOption} = 1 ) "; |
| 3913 | $field = CRM_Utils_Array::value($pOption, $this->_fields); |
| 3914 | $title = $field ? $field['title'] : $pOption; |
| 3915 | $qill[] = " $title = 1 "; |
| 3916 | } |
| 3917 | |
| 3918 | $this->_where[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )'; |
| 3919 | $this->_qill[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )'; |
| 3920 | } |
| 3921 | |
| 3922 | /** |
| 3923 | * @param $values |
| 3924 | */ |
| 3925 | public function preferredCommunication(&$values) { |
| 3926 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3927 | |
| 3928 | if (!is_array($value)) { |
| 3929 | $value = str_replace(array('(', ')'), '', explode(",", $value)); |
| 3930 | } |
| 3931 | elseif (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) { |
| 3932 | $op = key($value); |
| 3933 | $value = $value[$op]; |
| 3934 | } |
| 3935 | list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op); |
| 3936 | |
| 3937 | if (self::caseImportant($op)) { |
| 3938 | $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value); |
| 3939 | $op = (strstr($op, '!') || strstr($op, 'NOT')) ? 'NOT RLIKE' : 'RLIKE'; |
| 3940 | $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]"; |
| 3941 | } |
| 3942 | |
| 3943 | $this->_where[$grouping][] = self::buildClause("contact_a.preferred_communication_method", $op, $value); |
| 3944 | $this->_qill[$grouping][] = ts('Preferred Communication Method %1 %2', array(1 => $qillop, 2 => $qillVal)); |
| 3945 | } |
| 3946 | |
| 3947 | /** |
| 3948 | * Where / qill clause for relationship. |
| 3949 | * |
| 3950 | * @param array $values |
| 3951 | */ |
| 3952 | public function relationship(&$values) { |
| 3953 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 3954 | if ($this->_relationshipValuesAdded) { |
| 3955 | return; |
| 3956 | } |
| 3957 | // also get values array for relation_target_name |
| 3958 | // for relationship search we always do wildcard |
| 3959 | $relationType = $this->getWhereValues('relation_type_id', $grouping); |
| 3960 | $targetName = $this->getWhereValues('relation_target_name', $grouping); |
| 3961 | $relStatus = $this->getWhereValues('relation_status', $grouping); |
| 3962 | $relPermission = $this->getWhereValues('relation_permission', $grouping); |
| 3963 | $targetGroup = $this->getWhereValues('relation_target_group', $grouping); |
| 3964 | |
| 3965 | $nameClause = $name = NULL; |
| 3966 | if ($targetName) { |
| 3967 | $name = trim($targetName[2]); |
| 3968 | if (substr($name, 0, 1) == '"' && |
| 3969 | substr($name, -1, 1) == '"' |
| 3970 | ) { |
| 3971 | $name = substr($name, 1, -1); |
| 3972 | $name = strtolower(CRM_Core_DAO::escapeString($name)); |
| 3973 | $nameClause = "= '$name'"; |
| 3974 | } |
| 3975 | else { |
| 3976 | $name = strtolower(CRM_Core_DAO::escapeString($name)); |
| 3977 | $nameClause = "LIKE '%{$name}%'"; |
| 3978 | } |
| 3979 | } |
| 3980 | |
| 3981 | $rTypeValues = array(); |
| 3982 | if (!empty($relationType)) { |
| 3983 | $rel = explode('_', $relationType[2]); |
| 3984 | self::$_relType = $rel[1]; |
| 3985 | $params = array('id' => $rel[0]); |
| 3986 | $rType = CRM_Contact_BAO_RelationshipType::retrieve($params, $rTypeValues); |
| 3987 | } |
| 3988 | if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) { |
| 3989 | // if we don't know which end of the relationship we are dealing with we'll create a temp table |
| 3990 | //@todo unless we are dealing with a target group |
| 3991 | self::$_relType = 'reciprocal'; |
| 3992 | } |
| 3993 | // if we are creating a temp table we build our own where for the relationship table |
| 3994 | $relationshipTempTable = NULL; |
| 3995 | if (self::$_relType == 'reciprocal' && empty($targetGroup)) { |
| 3996 | $where = array(); |
| 3997 | self::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO::createTempTableName('civicrm_rel'); |
| 3998 | if ($nameClause) { |
| 3999 | $where[$grouping][] = " sort_name $nameClause "; |
| 4000 | } |
| 4001 | } |
| 4002 | else { |
| 4003 | $where = &$this->_where; |
| 4004 | if ($nameClause) { |
| 4005 | $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )"; |
| 4006 | } |
| 4007 | } |
| 4008 | |
| 4009 | $allRelationshipType = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE); |
| 4010 | |
| 4011 | if ($nameClause || !$targetGroup) { |
| 4012 | if (!empty($relationType)) { |
| 4013 | $this->_qill[$grouping][] = $allRelationshipType[$relationType[2]] . " $name"; |
| 4014 | } |
| 4015 | else { |
| 4016 | $this->_qill[$grouping][] = $name; |
| 4017 | } |
| 4018 | } |
| 4019 | |
| 4020 | //check to see if the target contact is in specified group |
| 4021 | if ($targetGroup) { |
| 4022 | //add contacts from static groups |
| 4023 | $this->_tables['civicrm_relationship_group_contact'] = $this->_whereTables['civicrm_relationship_group_contact'] |
| 4024 | = " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id AND civicrm_relationship_group_contact.status = 'Added'"; |
| 4025 | $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" . |
| 4026 | implode(",", $targetGroup[2]) . ") ) "; |
| 4027 | |
| 4028 | //add contacts from saved searches |
| 4029 | $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b", $op); |
| 4030 | |
| 4031 | //set the group where clause |
| 4032 | if ($ssWhere) { |
| 4033 | $groupWhere[] = "( " . $ssWhere . " )"; |
| 4034 | } |
| 4035 | $this->_where[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )"; |
| 4036 | |
| 4037 | //Get the names of the target groups for the qill |
| 4038 | $groupNames = CRM_Core_PseudoConstant::group(); |
| 4039 | $qillNames = array(); |
| 4040 | foreach ($targetGroup[2] as $groupId) { |
| 4041 | if (array_key_exists($groupId, $groupNames)) { |
| 4042 | $qillNames[] = $groupNames[$groupId]; |
| 4043 | } |
| 4044 | } |
| 4045 | if (!empty($relationType)) { |
| 4046 | $this->_qill[$grouping][] = $allRelationshipType[$relationType[2]] . " ( " . implode(", ", $qillNames) . " )"; |
| 4047 | } |
| 4048 | else { |
| 4049 | $this->_qill[$grouping][] = implode(", ", $qillNames); |
| 4050 | } |
| 4051 | } |
| 4052 | |
| 4053 | // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way |
| 4054 | $today = date('Ymd'); |
| 4055 | //check for active, inactive and all relation status |
| 4056 | if ($relStatus[2] == 0) { |
| 4057 | $where[$grouping][] = "( |
| 4058 | civicrm_relationship.is_active = 1 AND |
| 4059 | ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND |
| 4060 | ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} ) |
| 4061 | )"; |
| 4062 | $this->_qill[$grouping][] = ts('Relationship - Active and Current'); |
| 4063 | } |
| 4064 | elseif ($relStatus[2] == 1) { |
| 4065 | $where[$grouping][] = "( |
| 4066 | civicrm_relationship.is_active = 0 OR |
| 4067 | civicrm_relationship.end_date < {$today} OR |
| 4068 | civicrm_relationship.start_date > {$today} |
| 4069 | )"; |
| 4070 | $this->_qill[$grouping][] = ts('Relationship - Inactive or not Current'); |
| 4071 | } |
| 4072 | |
| 4073 | $onlyDeleted = 0; |
| 4074 | if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params)) { |
| 4075 | $onlyDeleted = 1; |
| 4076 | } |
| 4077 | $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})"; |
| 4078 | |
| 4079 | //check for permissioned, non-permissioned and all permissioned relations |
| 4080 | if ($relPermission[2] == 1) { |
| 4081 | $where[$grouping][] = "( |
| 4082 | civicrm_relationship.is_permission_a_b = 1 |
| 4083 | )"; |
| 4084 | $this->_qill[$grouping][] = ts('Relationship - Permissioned'); |
| 4085 | } |
| 4086 | elseif ($relPermission[2] == 2) { |
| 4087 | //non-allowed permission relationship. |
| 4088 | $where[$grouping][] = "( |
| 4089 | civicrm_relationship.is_permission_a_b = 0 |
| 4090 | )"; |
| 4091 | $this->_qill[$grouping][] = ts('Relationship - Non-permissioned'); |
| 4092 | } |
| 4093 | |
| 4094 | $this->addRelationshipDateClauses($grouping, $where); |
| 4095 | if (!empty($relationType) && !empty($rType) && isset($rType->id)) { |
| 4096 | $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id; |
| 4097 | } |
| 4098 | $this->_tables['civicrm_relationship'] = $this->_whereTables['civicrm_relationship'] = 1; |
| 4099 | $this->_useDistinct = TRUE; |
| 4100 | $this->_relationshipValuesAdded = TRUE; |
| 4101 | // it could be a or b, using an OR creates an unindexed join - better to create a temp table & |
| 4102 | // join on that, |
| 4103 | // @todo creating a temp table could be expanded to group filter |
| 4104 | // as even creating a temp table of all relationships is much much more efficient than |
| 4105 | // an OR in the join |
| 4106 | if ($relationshipTempTable) { |
| 4107 | $whereClause = ''; |
| 4108 | if (!empty($where[$grouping])) { |
| 4109 | $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]); |
| 4110 | $whereClause = str_replace('contact_b', 'c', $whereClause); |
| 4111 | } |
| 4112 | $sql = " |
| 4113 | CREATE TEMPORARY TABLE {$relationshipTempTable} |
| 4114 | (SELECT contact_id_b as contact_id, civicrm_relationship.id |
| 4115 | FROM civicrm_relationship |
| 4116 | INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id |
| 4117 | $whereClause ) |
| 4118 | UNION |
| 4119 | (SELECT contact_id_a as contact_id, civicrm_relationship.id |
| 4120 | FROM civicrm_relationship |
| 4121 | INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id |
| 4122 | $whereClause ) |
| 4123 | "; |
| 4124 | CRM_Core_DAO::executeQuery($sql); |
| 4125 | } |
| 4126 | |
| 4127 | } |
| 4128 | |
| 4129 | /** |
| 4130 | * Add start & end date criteria in |
| 4131 | * @param string $grouping |
| 4132 | * @param array $where |
| 4133 | * = array to add where clauses to, in case you are generating a temp table. |
| 4134 | * not the main query. |
| 4135 | */ |
| 4136 | public function addRelationshipDateClauses($grouping, &$where) { |
| 4137 | $dateValues = array(); |
| 4138 | $dateTypes = array( |
| 4139 | 'start_date', |
| 4140 | 'end_date', |
| 4141 | ); |
| 4142 | |
| 4143 | foreach ($dateTypes as $dateField) { |
| 4144 | $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping); |
| 4145 | $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping); |
| 4146 | if (!empty($dateValueLow)) { |
| 4147 | $date = date('Ymd', strtotime($dateValueLow[2])); |
| 4148 | $where[$grouping][] = "civicrm_relationship.$dateField >= $date"; |
| 4149 | $this->_qill[$grouping][] = ($dateField == 'end_date' ? ts('Relationship Ended on or After') : ts('Relationship Recorded Start Date On or After')) . " " . CRM_Utils_Date::customFormat($date); |
| 4150 | } |
| 4151 | if (!empty($dateValueHigh)) { |
| 4152 | $date = date('Ymd', strtotime($dateValueHigh[2])); |
| 4153 | $where[$grouping][] = "civicrm_relationship.$dateField <= $date"; |
| 4154 | $this->_qill[$grouping][] = ($dateField == 'end_date' ? ts('Relationship Ended on or Before') : ts('Relationship Recorded Start Date On or Before')) . " " . CRM_Utils_Date::customFormat($date); |
| 4155 | } |
| 4156 | } |
| 4157 | } |
| 4158 | |
| 4159 | /** |
| 4160 | * Default set of return properties. |
| 4161 | * |
| 4162 | * @param int $mode |
| 4163 | * |
| 4164 | * @return array |
| 4165 | * derault return properties |
| 4166 | */ |
| 4167 | public static function &defaultReturnProperties($mode = 1) { |
| 4168 | if (!isset(self::$_defaultReturnProperties)) { |
| 4169 | self::$_defaultReturnProperties = array(); |
| 4170 | } |
| 4171 | |
| 4172 | if (!isset(self::$_defaultReturnProperties[$mode])) { |
| 4173 | // add activity return properties |
| 4174 | if ($mode & CRM_Contact_BAO_Query::MODE_ACTIVITY) { |
| 4175 | self::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query::defaultReturnProperties($mode, FALSE); |
| 4176 | } |
| 4177 | else { |
| 4178 | self::$_defaultReturnProperties[$mode] = CRM_Core_Component::defaultReturnProperties($mode, FALSE); |
| 4179 | } |
| 4180 | |
| 4181 | if (empty(self::$_defaultReturnProperties[$mode])) { |
| 4182 | self::$_defaultReturnProperties[$mode] = array( |
| 4183 | 'home_URL' => 1, |
| 4184 | 'image_URL' => 1, |
| 4185 | 'legal_identifier' => 1, |
| 4186 | 'external_identifier' => 1, |
| 4187 | 'contact_type' => 1, |
| 4188 | 'contact_sub_type' => 1, |
| 4189 | 'sort_name' => 1, |
| 4190 | 'display_name' => 1, |
| 4191 | 'preferred_mail_format' => 1, |
| 4192 | 'nick_name' => 1, |
| 4193 | 'first_name' => 1, |
| 4194 | 'middle_name' => 1, |
| 4195 | 'last_name' => 1, |
| 4196 | 'prefix_id' => 1, |
| 4197 | 'suffix_id' => 1, |
| 4198 | 'formal_title' => 1, |
| 4199 | 'communication_style_id' => 1, |
| 4200 | 'birth_date' => 1, |
| 4201 | 'gender_id' => 1, |
| 4202 | 'street_address' => 1, |
| 4203 | 'supplemental_address_1' => 1, |
| 4204 | 'supplemental_address_2' => 1, |
| 4205 | 'city' => 1, |
| 4206 | 'postal_code' => 1, |
| 4207 | 'postal_code_suffix' => 1, |
| 4208 | 'state_province' => 1, |
| 4209 | 'country' => 1, |
| 4210 | 'world_region' => 1, |
| 4211 | 'geo_code_1' => 1, |
| 4212 | 'geo_code_2' => 1, |
| 4213 | 'email' => 1, |
| 4214 | 'on_hold' => 1, |
| 4215 | 'phone' => 1, |
| 4216 | 'im' => 1, |
| 4217 | 'household_name' => 1, |
| 4218 | 'organization_name' => 1, |
| 4219 | 'deceased_date' => 1, |
| 4220 | 'is_deceased' => 1, |
| 4221 | 'job_title' => 1, |
| 4222 | 'legal_name' => 1, |
| 4223 | 'sic_code' => 1, |
| 4224 | 'current_employer' => 1, |
| 4225 | // FIXME: should we use defaultHierReturnProperties() for the below? |
| 4226 | 'do_not_email' => 1, |
| 4227 | 'do_not_mail' => 1, |
| 4228 | 'do_not_sms' => 1, |
| 4229 | 'do_not_phone' => 1, |
| 4230 | 'do_not_trade' => 1, |
| 4231 | 'is_opt_out' => 1, |
| 4232 | 'contact_is_deleted' => 1, |
| 4233 | 'preferred_communication_method' => 1, |
| 4234 | 'preferred_language' => 1, |
| 4235 | ); |
| 4236 | } |
| 4237 | } |
| 4238 | return self::$_defaultReturnProperties[$mode]; |
| 4239 | } |
| 4240 | |
| 4241 | /** |
| 4242 | * Get primary condition for a sql clause. |
| 4243 | * |
| 4244 | * @param int $value |
| 4245 | * |
| 4246 | * @return string|NULL |
| 4247 | */ |
| 4248 | public static function getPrimaryCondition($value) { |
| 4249 | if (is_numeric($value)) { |
| 4250 | $value = (int ) $value; |
| 4251 | return ($value == 1) ? 'is_primary = 1' : 'is_primary = 0'; |
| 4252 | } |
| 4253 | return NULL; |
| 4254 | } |
| 4255 | |
| 4256 | /** |
| 4257 | * Wrapper for a simple search query. |
| 4258 | * |
| 4259 | * @param array $params |
| 4260 | * @param array $returnProperties |
| 4261 | * @param bool $count |
| 4262 | * |
| 4263 | * @return string |
| 4264 | */ |
| 4265 | public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) { |
| 4266 | $query = new CRM_Contact_BAO_Query($params, $returnProperties); |
| 4267 | list($select, $from, $where, $having) = $query->query(); |
| 4268 | $groupBy = ($query->_useGroupBy) ? 'GROUP BY contact_a.id' : ''; |
| 4269 | |
| 4270 | return "$select $from $where $groupBy $having"; |
| 4271 | } |
| 4272 | |
| 4273 | /** |
| 4274 | * These are stub comments as this function needs more explanation - particularly in terms of how it |
| 4275 | * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery. |
| 4276 | * |
| 4277 | * This function was originally written as a wrapper for the api query but is called from multiple places |
| 4278 | * in the core code directly so the name is misleading. This function does not use the searchQuery function |
| 4279 | * but it is unclear as to whehter that is historical or there is a reason |
| 4280 | * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function |
| 4281 | * |
| 4282 | * @param array $params |
| 4283 | * @param array $returnProperties |
| 4284 | * @param null $fields |
| 4285 | * @param string $sort |
| 4286 | * @param int $offset |
| 4287 | * @param int $row_count |
| 4288 | * @param bool $smartGroupCache |
| 4289 | * ?? update smart group cache?. |
| 4290 | * @param bool $count |
| 4291 | * Return count obnly. |
| 4292 | * @param bool $skipPermissions |
| 4293 | * Should permissions be ignored or should the logged in user's permissions be applied. |
| 4294 | * @param int $mode |
| 4295 | * This basically correlates to the component. |
| 4296 | * |
| 4297 | * @return array |
| 4298 | */ |
| 4299 | public static function apiQuery( |
| 4300 | $params = NULL, |
| 4301 | $returnProperties = NULL, |
| 4302 | $fields = NULL, |
| 4303 | $sort = NULL, |
| 4304 | $offset = 0, |
| 4305 | $row_count = 25, |
| 4306 | $smartGroupCache = TRUE, |
| 4307 | $count = FALSE, |
| 4308 | $skipPermissions = TRUE, |
| 4309 | $mode = 1, |
| 4310 | $apiEntity = NULL |
| 4311 | ) { |
| 4312 | |
| 4313 | $query = new CRM_Contact_BAO_Query( |
| 4314 | $params, $returnProperties, |
| 4315 | NULL, TRUE, FALSE, $mode, |
| 4316 | $skipPermissions, |
| 4317 | TRUE, $smartGroupCache, |
| 4318 | NULL, 'AND', |
| 4319 | $apiEntity |
| 4320 | ); |
| 4321 | |
| 4322 | //this should add a check for view deleted if permissions are enabled |
| 4323 | if ($skipPermissions) { |
| 4324 | $query->_skipDeleteClause = TRUE; |
| 4325 | } |
| 4326 | $query->generatePermissionClause(FALSE, $count); |
| 4327 | |
| 4328 | // note : this modifies _fromClause and _simpleFromClause |
| 4329 | $query->includePseudoFieldsJoin($sort); |
| 4330 | |
| 4331 | list($select, $from, $where, $having) = $query->query($count); |
| 4332 | |
| 4333 | $options = $query->_options; |
| 4334 | if (!empty($query->_permissionWhereClause)) { |
| 4335 | if (empty($where)) { |
| 4336 | $where = "WHERE $query->_permissionWhereClause"; |
| 4337 | } |
| 4338 | else { |
| 4339 | $where = "$where AND $query->_permissionWhereClause"; |
| 4340 | } |
| 4341 | } |
| 4342 | |
| 4343 | $sql = "$select $from $where $having"; |
| 4344 | |
| 4345 | // add group by |
| 4346 | if ($query->_useGroupBy) { |
| 4347 | $sql .= self::getGroupByFromSelectColumns($query->_select, 'contact_a.id'); |
| 4348 | } |
| 4349 | if (!empty($sort)) { |
| 4350 | $sort = CRM_Utils_Type::escape($sort, 'String'); |
| 4351 | $sql .= " ORDER BY $sort "; |
| 4352 | } |
| 4353 | if ($row_count > 0 && $offset >= 0) { |
| 4354 | $offset = CRM_Utils_Type::escape($offset, 'Int'); |
| 4355 | $row_count = CRM_Utils_Type::escape($row_count, 'Int'); |
| 4356 | $sql .= " LIMIT $offset, $row_count "; |
| 4357 | } |
| 4358 | |
| 4359 | $dao = CRM_Core_DAO::executeQuery($sql); |
| 4360 | |
| 4361 | // @todo derive this from the component class rather than hard-code two options. |
| 4362 | $entityIDField = ($mode == CRM_Contact_BAO_Query::MODE_CONTRIBUTE) ? 'contribution_id' : 'contact_id'; |
| 4363 | |
| 4364 | $values = array(); |
| 4365 | while ($dao->fetch()) { |
| 4366 | if ($count) { |
| 4367 | $noRows = $dao->rowCount; |
| 4368 | $dao->free(); |
| 4369 | return array($noRows, NULL); |
| 4370 | } |
| 4371 | $val = $query->store($dao); |
| 4372 | $convertedVals = $query->convertToPseudoNames($dao, TRUE); |
| 4373 | |
| 4374 | if (!empty($convertedVals)) { |
| 4375 | $val = array_replace_recursive($val, $convertedVals); |
| 4376 | } |
| 4377 | $values[$dao->$entityIDField] = $val; |
| 4378 | } |
| 4379 | $dao->free(); |
| 4380 | return array($values, $options); |
| 4381 | } |
| 4382 | |
| 4383 | /** |
| 4384 | * Get the actual custom field name by stripping off the appended string. |
| 4385 | * |
| 4386 | * The string could be _relative, _from, or _to |
| 4387 | * |
| 4388 | * @todo use metadata rather than convention to do this. |
| 4389 | * |
| 4390 | * @param string $parameterName |
| 4391 | * The name of the parameter submitted to the form. |
| 4392 | * e.g |
| 4393 | * custom_3_relative |
| 4394 | * custom_3_from |
| 4395 | * |
| 4396 | * @return string |
| 4397 | */ |
| 4398 | public static function getCustomFieldName($parameterName) { |
| 4399 | if (substr($parameterName, -5, 5) == '_from') { |
| 4400 | return substr($parameterName, 0, strpos($parameterName, '_from')); |
| 4401 | } |
| 4402 | if (substr($parameterName, -9, 9) == '_relative') { |
| 4403 | return substr($parameterName, 0, strpos($parameterName, '_relative')); |
| 4404 | } |
| 4405 | if (substr($parameterName, -3, 3) == '_to') { |
| 4406 | return substr($parameterName, 0, strpos($parameterName, '_to')); |
| 4407 | } |
| 4408 | } |
| 4409 | |
| 4410 | /** |
| 4411 | * Convert submitted values for relative custom fields to query object format. |
| 4412 | * |
| 4413 | * The query will support the sqlOperator format so convert to that format. |
| 4414 | * |
| 4415 | * @param array $formValues |
| 4416 | * Submitted values. |
| 4417 | * @param array $params |
| 4418 | * Converted parameters for the query object. |
| 4419 | * @param string $values |
| 4420 | * Submitted value. |
| 4421 | * @param string $fieldName |
| 4422 | * Submitted field name. (Matches form field not DB field.) |
| 4423 | */ |
| 4424 | protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) { |
| 4425 | if (empty($values)) { |
| 4426 | // e.g we might have relative set & from & to empty. The form flow is a bit funky & |
| 4427 | // this function gets called again after they fields have been converted which can get ugly. |
| 4428 | return; |
| 4429 | } |
| 4430 | $customFieldName = self::getCustomFieldName($fieldName); |
| 4431 | |
| 4432 | if (substr($fieldName, -9, 9) == '_relative') { |
| 4433 | list($from, $to) = CRM_Utils_Date::getFromTo($values, NULL, NULL); |
| 4434 | } |
| 4435 | else { |
| 4436 | if ($fieldName == $customFieldName . '_to' && CRM_Utils_Array::value($customFieldName . '_from', $formValues)) { |
| 4437 | // Both to & from are set. We only need to acton one, choosing from. |
| 4438 | return; |
| 4439 | } |
| 4440 | |
| 4441 | $from = CRM_Utils_Array::value($customFieldName . '_from', $formValues, NULL); |
| 4442 | $to = CRM_Utils_Array::value($customFieldName . '_to', $formValues, NULL); |
| 4443 | |
| 4444 | if (self::isCustomDateField($customFieldName)) { |
| 4445 | list($from, $to) = CRM_Utils_Date::getFromTo(NULL, $from, $to); |
| 4446 | } |
| 4447 | } |
| 4448 | |
| 4449 | if ($from) { |
| 4450 | if ($to) { |
| 4451 | $relativeFunction = array('BETWEEN' => array($from, $to)); |
| 4452 | } |
| 4453 | else { |
| 4454 | $relativeFunction = array('>=' => $from); |
| 4455 | } |
| 4456 | } |
| 4457 | else { |
| 4458 | $relativeFunction = array('<=' => $to); |
| 4459 | } |
| 4460 | $params[] = array( |
| 4461 | $customFieldName, |
| 4462 | '=', |
| 4463 | $relativeFunction, |
| 4464 | 0, |
| 4465 | 0, |
| 4466 | ); |
| 4467 | } |
| 4468 | |
| 4469 | /** |
| 4470 | * Are we dealing with custom field of type date. |
| 4471 | * |
| 4472 | * @param $fieldName |
| 4473 | * |
| 4474 | * @return bool |
| 4475 | */ |
| 4476 | public static function isCustomDateField($fieldName) { |
| 4477 | if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($fieldName)) == FALSE) { |
| 4478 | return FALSE; |
| 4479 | } |
| 4480 | if ('Date' == civicrm_api3('CustomField', 'getvalue', array('id' => $customFieldID, 'return' => 'data_type'))) { |
| 4481 | return TRUE; |
| 4482 | } |
| 4483 | return FALSE; |
| 4484 | } |
| 4485 | |
| 4486 | /** |
| 4487 | * Has this field already been reformatting to Query object syntax. |
| 4488 | * |
| 4489 | * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems |
| 4490 | * to come with associated double queries & is possibly damaging performance. |
| 4491 | * |
| 4492 | * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns |
| 4493 | * them as they are. |
| 4494 | * |
| 4495 | * @param mixed $values |
| 4496 | * Value in formValues for the field. |
| 4497 | * |
| 4498 | * @return bool; |
| 4499 | */ |
| 4500 | public static function isAlreadyProcessedForQueryFormat($values) { |
| 4501 | if (!is_array($values)) { |
| 4502 | return FALSE; |
| 4503 | } |
| 4504 | if (($operator = CRM_Utils_Array::value(1, $values)) == FALSE) { |
| 4505 | return FALSE; |
| 4506 | } |
| 4507 | return in_array($operator, CRM_Core_DAO::acceptedSQLOperators()); |
| 4508 | } |
| 4509 | |
| 4510 | /** |
| 4511 | * If the state and country are passed remove state. |
| 4512 | * |
| 4513 | * Country is implicit from the state, but including both results in |
| 4514 | * a poor query as there is no combined index on state AND country. |
| 4515 | * |
| 4516 | * CRM-18125 |
| 4517 | * |
| 4518 | * @param array $formValues |
| 4519 | */ |
| 4520 | public static function filterCountryFromValuesIfStateExists(&$formValues) { |
| 4521 | if (!empty($formValues['country']) && !empty($formValues['state_province'])) { |
| 4522 | // The use of array map sanitises the data by ensuring we are dealing with integers. |
| 4523 | $states = implode(', ', array_map('intval', $formValues['state_province'])); |
| 4524 | $countryList = CRM_Core_DAO::singleValueQuery( |
| 4525 | "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)" |
| 4526 | ); |
| 4527 | if ($countryList == $formValues['country']) { |
| 4528 | unset($formValues['country']); |
| 4529 | } |
| 4530 | } |
| 4531 | } |
| 4532 | |
| 4533 | /** |
| 4534 | * For some special cases, grouping by subset of select fields becomes mandatory. |
| 4535 | * Hence, full_group_by mode is handled by appending any_value |
| 4536 | * keyword to select fields not present in groupBy |
| 4537 | * |
| 4538 | * @param array $selectClauses |
| 4539 | * @param array $groupBy - Columns already included in GROUP By clause. |
| 4540 | * |
| 4541 | * @return string |
| 4542 | */ |
| 4543 | public static function appendAnyValueToSelect($selectClauses, $groupBy) { |
| 4544 | $mysqlVersion = CRM_Core_DAO::singleValueQuery('SELECT VERSION()'); |
| 4545 | $sqlMode = explode(',', CRM_Core_DAO::singleValueQuery('SELECT @@sql_mode')); |
| 4546 | |
| 4547 | // Disable only_full_group_by mode for lower sql versions. |
| 4548 | if (version_compare($mysqlVersion, '5.7', '<') || (!empty($sqlMode) && !in_array('ONLY_FULL_GROUP_BY', $sqlMode))) { |
| 4549 | $key = array_search('ONLY_FULL_GROUP_BY', $sqlMode); |
| 4550 | unset($sqlMode[$key]); |
| 4551 | CRM_Core_DAO::executeQuery("SET SESSION sql_mode = '" . implode(',', $sqlMode) . "'"); |
| 4552 | } |
| 4553 | else { |
| 4554 | $groupBy = array_map('trim', (array) $groupBy); |
| 4555 | $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i'; |
| 4556 | foreach ($selectClauses as $key => &$val) { |
| 4557 | list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL); |
| 4558 | // append ANY_VALUE() keyword |
| 4559 | if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) { |
| 4560 | $val = str_replace($selectColumn, "ANY_VALUE({$selectColumn})", $val); |
| 4561 | } |
| 4562 | } |
| 4563 | } |
| 4564 | |
| 4565 | return "SELECT " . implode(', ', $selectClauses) . " "; |
| 4566 | } |
| 4567 | |
| 4568 | /** |
| 4569 | * Include Select columns in groupBy clause. |
| 4570 | * |
| 4571 | * @param array $selectClauses |
| 4572 | * @param array $groupBy - Columns already included in GROUP By clause. |
| 4573 | * |
| 4574 | * @return string |
| 4575 | */ |
| 4576 | public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) { |
| 4577 | $groupBy = (array) $groupBy; |
| 4578 | $mysqlVersion = CRM_Core_DAO::singleValueQuery('SELECT VERSION()'); |
| 4579 | $sqlMode = CRM_Core_DAO::singleValueQuery('SELECT @@sql_mode'); |
| 4580 | |
| 4581 | //return if ONLY_FULL_GROUP_BY is not enabled. |
| 4582 | if (!version_compare($mysqlVersion, '5.7', '<') && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) { |
| 4583 | $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i'; |
| 4584 | foreach ($selectClauses as $key => $val) { |
| 4585 | $aliasArray = preg_split('/ as /i', $val); |
| 4586 | // if more than 1 alias we need to split by ','. |
| 4587 | if (count($aliasArray) > 2) { |
| 4588 | $aliasArray = preg_split('/,/', $val); |
| 4589 | foreach ($aliasArray as $key => $value) { |
| 4590 | $alias = current(preg_split('/ as /i', $value)); |
| 4591 | if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) { |
| 4592 | $groupBy[] = $alias; |
| 4593 | } |
| 4594 | } |
| 4595 | } |
| 4596 | else { |
| 4597 | list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL); |
| 4598 | $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i'; |
| 4599 | $tableName = current(explode('.', $selectColumn)); |
| 4600 | $primaryKey = "{$tableName}.id"; |
| 4601 | // exclude columns which are already included in groupBy and aggregate functions from select |
| 4602 | // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+) |
| 4603 | if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) { |
| 4604 | if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) { |
| 4605 | $groupBy[] = $alias; |
| 4606 | } |
| 4607 | else { |
| 4608 | $groupBy[] = $selectColumn; |
| 4609 | } |
| 4610 | } |
| 4611 | } |
| 4612 | } |
| 4613 | } |
| 4614 | |
| 4615 | if (!empty($groupBy)) { |
| 4616 | return " GROUP BY " . implode(', ', $groupBy); |
| 4617 | } |
| 4618 | return ''; |
| 4619 | } |
| 4620 | |
| 4621 | /** |
| 4622 | * Create and query the db for an contact search. |
| 4623 | * |
| 4624 | * @param int $offset |
| 4625 | * The offset for the query. |
| 4626 | * @param int $rowCount |
| 4627 | * The number of rows to return. |
| 4628 | * @param string|CRM_Utils_Sort $sort |
| 4629 | * The order by string. |
| 4630 | * @param bool $count |
| 4631 | * Is this a count only query ?. |
| 4632 | * @param bool $includeContactIds |
| 4633 | * Should we include contact ids?. |
| 4634 | * @param bool $sortByChar |
| 4635 | * If true returns the distinct array of first characters for search results. |
| 4636 | * @param bool $groupContacts |
| 4637 | * If true, return only the contact ids. |
| 4638 | * @param bool $returnQuery |
| 4639 | * Should we return the query as a string. |
| 4640 | * @param string $additionalWhereClause |
| 4641 | * If the caller wants to further restrict the search (used for components). |
| 4642 | * @param null $sortOrder |
| 4643 | * @param string $additionalFromClause |
| 4644 | * Should be clause with proper joins, effective to reduce where clause load. |
| 4645 | * |
| 4646 | * @param bool $skipOrderAndLimit |
| 4647 | * |
| 4648 | * @return CRM_Core_DAO |
| 4649 | */ |
| 4650 | public function searchQuery( |
| 4651 | $offset = 0, $rowCount = 0, $sort = NULL, |
| 4652 | $count = FALSE, $includeContactIds = FALSE, |
| 4653 | $sortByChar = FALSE, $groupContacts = FALSE, |
| 4654 | $returnQuery = FALSE, |
| 4655 | $additionalWhereClause = NULL, $sortOrder = NULL, |
| 4656 | $additionalFromClause = NULL, $skipOrderAndLimit = FALSE |
| 4657 | ) { |
| 4658 | |
| 4659 | if ($includeContactIds) { |
| 4660 | $this->_includeContactIds = TRUE; |
| 4661 | $this->_whereClause = $this->whereClause(); |
| 4662 | } |
| 4663 | |
| 4664 | $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params); |
| 4665 | |
| 4666 | // if we’re explicitly looking for a certain contact’s contribs, events, etc. |
| 4667 | // and that contact happens to be deleted, set $onlyDeleted to true |
| 4668 | foreach ($this->_params as $values) { |
| 4669 | $name = CRM_Utils_Array::value(0, $values); |
| 4670 | $op = CRM_Utils_Array::value(1, $values); |
| 4671 | $value = CRM_Utils_Array::value(2, $values); |
| 4672 | if ($name == 'contact_id' and $op == '=') { |
| 4673 | if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) { |
| 4674 | $onlyDeleted = TRUE; |
| 4675 | } |
| 4676 | break; |
| 4677 | } |
| 4678 | } |
| 4679 | |
| 4680 | // building the query string |
| 4681 | $groupBy = $groupByCol = NULL; |
| 4682 | if (!$count) { |
| 4683 | if (isset($this->_groupByComponentClause)) { |
| 4684 | $groupBy = $this->_groupByComponentClause; |
| 4685 | $groupCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause)); |
| 4686 | $groupByCol = explode(', ', $groupCols); |
| 4687 | } |
| 4688 | elseif ($this->_useGroupBy) { |
| 4689 | $groupByCol = 'contact_a.id'; |
| 4690 | $groupBy = ' GROUP BY contact_a.id'; |
| 4691 | } |
| 4692 | } |
| 4693 | if ($this->_mode & CRM_Contact_BAO_Query::MODE_ACTIVITY && (!$count)) { |
| 4694 | $groupByCol = 'civicrm_activity.id'; |
| 4695 | $groupBy = 'GROUP BY civicrm_activity.id '; |
| 4696 | } |
| 4697 | |
| 4698 | $order = $orderBy = $limit = ''; |
| 4699 | if (!$count) { |
| 4700 | list($order, $additionalFromClause) = $this->prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause); |
| 4701 | |
| 4702 | if ($rowCount > 0 && $offset >= 0) { |
| 4703 | $offset = CRM_Utils_Type::escape($offset, 'Int'); |
| 4704 | $rowCount = CRM_Utils_Type::escape($rowCount, 'Int'); |
| 4705 | $limit = " LIMIT $offset, $rowCount "; |
| 4706 | } |
| 4707 | } |
| 4708 | |
| 4709 | // CRM-15231 |
| 4710 | $this->_sort = $sort; |
| 4711 | |
| 4712 | //CRM-15967 |
| 4713 | $this->includePseudoFieldsJoin($sort); |
| 4714 | |
| 4715 | list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted); |
| 4716 | |
| 4717 | if (!empty($groupByCol)) { |
| 4718 | $groupBy = self::getGroupByFromSelectColumns($this->_select, $groupByCol); |
| 4719 | } |
| 4720 | |
| 4721 | if ($additionalWhereClause) { |
| 4722 | $where = $where . ' AND ' . $additionalWhereClause; |
| 4723 | } |
| 4724 | |
| 4725 | //additional from clause should be w/ proper joins. |
| 4726 | if ($additionalFromClause) { |
| 4727 | $from .= "\n" . $additionalFromClause; |
| 4728 | } |
| 4729 | |
| 4730 | // if we are doing a transform, do it here |
| 4731 | // use the $from, $where and $having to get the contact ID |
| 4732 | if ($this->_displayRelationshipType) { |
| 4733 | $this->filterRelatedContacts($from, $where, $having); |
| 4734 | } |
| 4735 | |
| 4736 | if ($skipOrderAndLimit) { |
| 4737 | $query = "$select $from $where $having $groupBy"; |
| 4738 | } |
| 4739 | else { |
| 4740 | $query = "$select $from $where $having $groupBy $order $limit"; |
| 4741 | } |
| 4742 | |
| 4743 | if ($returnQuery) { |
| 4744 | return $query; |
| 4745 | } |
| 4746 | if ($count) { |
| 4747 | return CRM_Core_DAO::singleValueQuery($query); |
| 4748 | } |
| 4749 | |
| 4750 | $dao = CRM_Core_DAO::executeQuery($query); |
| 4751 | if ($groupContacts) { |
| 4752 | $ids = array(); |
| 4753 | while ($dao->fetch()) { |
| 4754 | $ids[] = $dao->id; |
| 4755 | } |
| 4756 | $dao->free(); |
| 4757 | return implode(',', $ids); |
| 4758 | } |
| 4759 | |
| 4760 | return $dao; |
| 4761 | } |
| 4762 | |
| 4763 | /** |
| 4764 | * Fetch a list of contacts from the prev/next cache for displaying a search results page |
| 4765 | * |
| 4766 | * @param string $cacheKey |
| 4767 | * @param int $offset |
| 4768 | * @param int $rowCount |
| 4769 | * @param bool $includeContactIds |
| 4770 | * @return CRM_Core_DAO |
| 4771 | */ |
| 4772 | public function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) { |
| 4773 | $this->_includeContactIds = $includeContactIds; |
| 4774 | $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params); |
| 4775 | list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted); |
| 4776 | $from = " FROM civicrm_prevnext_cache pnc INNER JOIN civicrm_contact contact_a ON contact_a.id = pnc.entity_id1 AND pnc.cacheKey = '$cacheKey' " . substr($from, 31); |
| 4777 | $order = " ORDER BY pnc.id"; |
| 4778 | $groupByCol = array('contact_a.id', 'pnc.id'); |
| 4779 | $groupBy = self::getGroupByFromSelectColumns($this->_select, $groupByCol); |
| 4780 | $limit = " LIMIT $offset, $rowCount"; |
| 4781 | $query = "$select $from $where $groupBy $order $limit"; |
| 4782 | |
| 4783 | return CRM_Core_DAO::executeQuery($query); |
| 4784 | } |
| 4785 | |
| 4786 | /** |
| 4787 | * Populate $this->_permissionWhereClause with permission related clause and update other |
| 4788 | * query related properties. |
| 4789 | * |
| 4790 | * Function calls ACL permission class and hooks to filter the query appropriately |
| 4791 | * |
| 4792 | * Note that these 2 params were in the code when extracted from another function |
| 4793 | * and a second round extraction would be to make them properties of the class |
| 4794 | * |
| 4795 | * @param bool $onlyDeleted |
| 4796 | * Only get deleted contacts. |
| 4797 | * @param bool $count |
| 4798 | * Return Count only. |
| 4799 | */ |
| 4800 | public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) { |
| 4801 | if (!$this->_skipPermission) { |
| 4802 | $this->_permissionWhereClause = CRM_ACL_API::whereClause( |
| 4803 | CRM_Core_Permission::VIEW, |
| 4804 | $this->_tables, |
| 4805 | $this->_whereTables, |
| 4806 | NULL, |
| 4807 | $onlyDeleted, |
| 4808 | $this->_skipDeleteClause |
| 4809 | ); |
| 4810 | |
| 4811 | // regenerate fromClause since permission might have added tables |
| 4812 | if ($this->_permissionWhereClause) { |
| 4813 | //fix for row count in qill (in contribute/membership find) |
| 4814 | if (!$count) { |
| 4815 | $this->_useDistinct = TRUE; |
| 4816 | } |
| 4817 | //CRM-15231 |
| 4818 | $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode); |
| 4819 | $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode); |
| 4820 | // note : this modifies _fromClause and _simpleFromClause |
| 4821 | $this->includePseudoFieldsJoin($this->_sort); |
| 4822 | } |
| 4823 | } |
| 4824 | else { |
| 4825 | // add delete clause if needed even if we are skipping permission |
| 4826 | // CRM-7639 |
| 4827 | if (!$this->_skipDeleteClause) { |
| 4828 | if (CRM_Core_Permission::check('access deleted contacts') and $onlyDeleted) { |
| 4829 | $this->_permissionWhereClause = '(contact_a.is_deleted)'; |
| 4830 | } |
| 4831 | else { |
| 4832 | // CRM-6181 |
| 4833 | $this->_permissionWhereClause = '(contact_a.is_deleted = 0)'; |
| 4834 | } |
| 4835 | } |
| 4836 | } |
| 4837 | } |
| 4838 | |
| 4839 | /** |
| 4840 | * @param $val |
| 4841 | */ |
| 4842 | public function setSkipPermission($val) { |
| 4843 | $this->_skipPermission = $val; |
| 4844 | } |
| 4845 | |
| 4846 | /** |
| 4847 | * @param null $context |
| 4848 | * |
| 4849 | * @return array |
| 4850 | */ |
| 4851 | public function &summaryContribution($context = NULL) { |
| 4852 | list($innerselect, $from, $where, $having) = $this->query(TRUE); |
| 4853 | |
| 4854 | // hack $select |
| 4855 | $select = " |
| 4856 | SELECT COUNT( conts.total_amount ) as total_count, |
| 4857 | SUM( conts.total_amount ) as total_amount, |
| 4858 | AVG( conts.total_amount ) as total_avg, |
| 4859 | conts.currency as currency"; |
| 4860 | if ($this->_permissionWhereClause) { |
| 4861 | $where .= " AND " . $this->_permissionWhereClause; |
| 4862 | } |
| 4863 | if ($context == 'search') { |
| 4864 | $where .= " AND contact_a.is_deleted = 0 "; |
| 4865 | } |
| 4866 | CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes); |
| 4867 | if (!empty($financialTypes)) { |
| 4868 | $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL"; |
| 4869 | $from .= " LEFT JOIN civicrm_line_item li |
| 4870 | ON civicrm_contribution.id = li.contribution_id AND |
| 4871 | li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") "; |
| 4872 | } |
| 4873 | else { |
| 4874 | $where .= " AND civicrm_contribution.financial_type_id IN (0)"; |
| 4875 | } |
| 4876 | |
| 4877 | // make sure contribution is completed - CRM-4989 |
| 4878 | $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 "; |
| 4879 | |
| 4880 | $summary = array(); |
| 4881 | $summary['total'] = array(); |
| 4882 | $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a"; |
| 4883 | $innerQuery = "SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count, |
| 4884 | civicrm_contribution.currency $from $completedWhere"; |
| 4885 | $query = "$select FROM ( |
| 4886 | $innerQuery GROUP BY civicrm_contribution.id |
| 4887 | ) as conts |
| 4888 | GROUP BY currency"; |
| 4889 | |
| 4890 | $dao = CRM_Core_DAO::executeQuery($query); |
| 4891 | |
| 4892 | $summary['total']['count'] = 0; |
| 4893 | $summary['total']['amount'] = $summary['total']['avg'] = array(); |
| 4894 | while ($dao->fetch()) { |
| 4895 | $summary['total']['count'] += $dao->total_count; |
| 4896 | $summary['total']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency); |
| 4897 | $summary['total']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency); |
| 4898 | } |
| 4899 | |
| 4900 | $orderBy = 'ORDER BY civicrm_contribution_total_amount_count DESC'; |
| 4901 | $groupBy = 'GROUP BY currency, civicrm_contribution.total_amount'; |
| 4902 | $modeSQL = "$select, SUBSTRING_INDEX(GROUP_CONCAT(conts.total_amount |
| 4903 | ORDER BY conts.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount, |
| 4904 | MAX(conts.civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count |
| 4905 | FROM ($innerQuery |
| 4906 | $groupBy $orderBy) as conts |
| 4907 | GROUP BY currency"; |
| 4908 | |
| 4909 | $summary['total']['mode'] = CRM_Contribute_BAO_Contribution::computeStats('mode', $modeSQL); |
| 4910 | |
| 4911 | $medianSQL = "{$from} {$completedWhere}"; |
| 4912 | $summary['total']['median'] = CRM_Contribute_BAO_Contribution::computeStats('median', $medianSQL, 'civicrm_contribution'); |
| 4913 | $summary['total']['currencyCount'] = count($summary['total']['median']); |
| 4914 | |
| 4915 | if (!empty($summary['total']['amount'])) { |
| 4916 | $summary['total']['amount'] = implode(', ', $summary['total']['amount']); |
| 4917 | $summary['total']['avg'] = implode(', ', $summary['total']['avg']); |
| 4918 | $summary['total']['mode'] = implode(', ', $summary['total']['mode']); |
| 4919 | $summary['total']['median'] = implode(', ', $summary['total']['median']); |
| 4920 | } |
| 4921 | else { |
| 4922 | $summary['total']['amount'] = $summary['total']['avg'] = $summary['total']['median'] = 0; |
| 4923 | } |
| 4924 | |
| 4925 | // soft credit summary |
| 4926 | if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) { |
| 4927 | $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL"; |
| 4928 | $query = " |
| 4929 | $select FROM ( |
| 4930 | SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere |
| 4931 | GROUP BY civicrm_contribution_soft.id |
| 4932 | ) as conts |
| 4933 | GROUP BY currency"; |
| 4934 | $dao = CRM_Core_DAO::executeQuery($query); |
| 4935 | $summary['soft_credit']['count'] = 0; |
| 4936 | $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array(); |
| 4937 | while ($dao->fetch()) { |
| 4938 | $summary['soft_credit']['count'] += $dao->total_count; |
| 4939 | $summary['soft_credit']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency); |
| 4940 | $summary['soft_credit']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency); |
| 4941 | } |
| 4942 | if (!empty($summary['soft_credit']['amount'])) { |
| 4943 | $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']); |
| 4944 | $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']); |
| 4945 | } |
| 4946 | else { |
| 4947 | $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0; |
| 4948 | } |
| 4949 | } |
| 4950 | |
| 4951 | // hack $select |
| 4952 | //@todo - this could be one query using the IF in mysql - eg |
| 4953 | // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM ( |
| 4954 | // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency , |
| 4955 | // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed, |
| 4956 | // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed, |
| 4957 | // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled, |
| 4958 | // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled |
| 4959 | // FROM civicrm_contact contact_a |
| 4960 | // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id |
| 4961 | // WHERE ( ... where clause.... |
| 4962 | // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1) |
| 4963 | // ) as conts |
| 4964 | |
| 4965 | $select = " |
| 4966 | SELECT COUNT( conts.total_amount ) as cancel_count, |
| 4967 | SUM( conts.total_amount ) as cancel_amount, |
| 4968 | AVG( conts.total_amount ) as cancel_avg, |
| 4969 | conts.currency as currency"; |
| 4970 | |
| 4971 | $where .= " AND civicrm_contribution.cancel_date IS NOT NULL "; |
| 4972 | if ($context == 'search') { |
| 4973 | $where .= " AND contact_a.is_deleted = 0 "; |
| 4974 | } |
| 4975 | |
| 4976 | $query = "$select FROM ( |
| 4977 | SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where |
| 4978 | GROUP BY civicrm_contribution.id |
| 4979 | ) as conts |
| 4980 | GROUP BY currency"; |
| 4981 | |
| 4982 | $dao = CRM_Core_DAO::executeQuery($query); |
| 4983 | |
| 4984 | if ($dao->N <= 1) { |
| 4985 | if ($dao->fetch()) { |
| 4986 | $summary['cancel']['count'] = $dao->cancel_count; |
| 4987 | $summary['cancel']['amount'] = CRM_Utils_Money::format($dao->cancel_amount, $dao->currency); |
| 4988 | $summary['cancel']['avg'] = CRM_Utils_Money::format($dao->cancel_avg, $dao->currency); |
| 4989 | } |
| 4990 | } |
| 4991 | else { |
| 4992 | $summary['cancel']['count'] = 0; |
| 4993 | $summary['cancel']['amount'] = $summary['cancel']['avg'] = array(); |
| 4994 | while ($dao->fetch()) { |
| 4995 | $summary['cancel']['count'] += $dao->cancel_count; |
| 4996 | $summary['cancel']['amount'][] = CRM_Utils_Money::format($dao->cancel_amount, $dao->currency); |
| 4997 | $summary['cancel']['avg'][] = CRM_Utils_Money::format($dao->cancel_avg, $dao->currency); |
| 4998 | } |
| 4999 | $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']); |
| 5000 | $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']); |
| 5001 | } |
| 5002 | |
| 5003 | return $summary; |
| 5004 | } |
| 5005 | |
| 5006 | /** |
| 5007 | * Getter for the qill object. |
| 5008 | * |
| 5009 | * @return string |
| 5010 | */ |
| 5011 | public function qill() { |
| 5012 | return $this->_qill; |
| 5013 | } |
| 5014 | |
| 5015 | /** |
| 5016 | * Default set of return default hier return properties. |
| 5017 | * |
| 5018 | * @return array |
| 5019 | */ |
| 5020 | public static function &defaultHierReturnProperties() { |
| 5021 | if (!isset(self::$_defaultHierReturnProperties)) { |
| 5022 | self::$_defaultHierReturnProperties = array( |
| 5023 | 'home_URL' => 1, |
| 5024 | 'image_URL' => 1, |
| 5025 | 'legal_identifier' => 1, |
| 5026 | 'external_identifier' => 1, |
| 5027 | 'contact_type' => 1, |
| 5028 | 'contact_sub_type' => 1, |
| 5029 | 'sort_name' => 1, |
| 5030 | 'display_name' => 1, |
| 5031 | 'nick_name' => 1, |
| 5032 | 'first_name' => 1, |
| 5033 | 'middle_name' => 1, |
| 5034 | 'last_name' => 1, |
| 5035 | 'prefix_id' => 1, |
| 5036 | 'suffix_id' => 1, |
| 5037 | 'formal_title' => 1, |
| 5038 | 'communication_style_id' => 1, |
| 5039 | 'email_greeting' => 1, |
| 5040 | 'postal_greeting' => 1, |
| 5041 | 'addressee' => 1, |
| 5042 | 'birth_date' => 1, |
| 5043 | 'gender_id' => 1, |
| 5044 | 'preferred_communication_method' => 1, |
| 5045 | 'do_not_phone' => 1, |
| 5046 | 'do_not_email' => 1, |
| 5047 | 'do_not_mail' => 1, |
| 5048 | 'do_not_sms' => 1, |
| 5049 | 'do_not_trade' => 1, |
| 5050 | 'location' => array( |
| 5051 | '1' => array( |
| 5052 | 'location_type' => 1, |
| 5053 | 'street_address' => 1, |
| 5054 | 'city' => 1, |
| 5055 | 'state_province' => 1, |
| 5056 | 'postal_code' => 1, |
| 5057 | 'postal_code_suffix' => 1, |
| 5058 | 'country' => 1, |
| 5059 | 'phone-Phone' => 1, |
| 5060 | 'phone-Mobile' => 1, |
| 5061 | 'phone-Fax' => 1, |
| 5062 | 'phone-1' => 1, |
| 5063 | 'phone-2' => 1, |
| 5064 | 'phone-3' => 1, |
| 5065 | 'im-1' => 1, |
| 5066 | 'im-2' => 1, |
| 5067 | 'im-3' => 1, |
| 5068 | 'email-1' => 1, |
| 5069 | 'email-2' => 1, |
| 5070 | 'email-3' => 1, |
| 5071 | ), |
| 5072 | '2' => array( |
| 5073 | 'location_type' => 1, |
| 5074 | 'street_address' => 1, |
| 5075 | 'city' => 1, |
| 5076 | 'state_province' => 1, |
| 5077 | 'postal_code' => 1, |
| 5078 | 'postal_code_suffix' => 1, |
| 5079 | 'country' => 1, |
| 5080 | 'phone-Phone' => 1, |
| 5081 | 'phone-Mobile' => 1, |
| 5082 | 'phone-1' => 1, |
| 5083 | 'phone-2' => 1, |
| 5084 | 'phone-3' => 1, |
| 5085 | 'im-1' => 1, |
| 5086 | 'im-2' => 1, |
| 5087 | 'im-3' => 1, |
| 5088 | 'email-1' => 1, |
| 5089 | 'email-2' => 1, |
| 5090 | 'email-3' => 1, |
| 5091 | ), |
| 5092 | ), |
| 5093 | ); |
| 5094 | } |
| 5095 | return self::$_defaultHierReturnProperties; |
| 5096 | } |
| 5097 | |
| 5098 | /** |
| 5099 | * Build query for a date field. |
| 5100 | * |
| 5101 | * @param array $values |
| 5102 | * @param string $tableName |
| 5103 | * @param string $fieldName |
| 5104 | * @param string $dbFieldName |
| 5105 | * @param string $fieldTitle |
| 5106 | * @param bool $appendTimeStamp |
| 5107 | */ |
| 5108 | public function dateQueryBuilder( |
| 5109 | &$values, $tableName, $fieldName, |
| 5110 | $dbFieldName, $fieldTitle, |
| 5111 | $appendTimeStamp = TRUE |
| 5112 | ) { |
| 5113 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 5114 | |
| 5115 | if ($name == "{$fieldName}_low" || |
| 5116 | $name == "{$fieldName}_high" |
| 5117 | ) { |
| 5118 | if (isset($this->_rangeCache[$fieldName]) || !$value) { |
| 5119 | return; |
| 5120 | } |
| 5121 | $this->_rangeCache[$fieldName] = 1; |
| 5122 | |
| 5123 | $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL; |
| 5124 | |
| 5125 | if ($name == $fieldName . '_low') { |
| 5126 | $firstOP = '>='; |
| 5127 | $firstPhrase = ts('greater than or equal to'); |
| 5128 | $firstDate = CRM_Utils_Date::processDate($value); |
| 5129 | |
| 5130 | $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping); |
| 5131 | if (!empty($secondValues) && $secondValues[2]) { |
| 5132 | $secondOP = '<='; |
| 5133 | $secondPhrase = ts('less than or equal to'); |
| 5134 | $secondValue = $secondValues[2]; |
| 5135 | |
| 5136 | if ($appendTimeStamp && strlen($secondValue) == 10) { |
| 5137 | $secondValue .= ' 23:59:59'; |
| 5138 | } |
| 5139 | $secondDate = CRM_Utils_Date::processDate($secondValue); |
| 5140 | } |
| 5141 | } |
| 5142 | elseif ($name == $fieldName . '_high') { |
| 5143 | $firstOP = '<='; |
| 5144 | $firstPhrase = ts('less than or equal to'); |
| 5145 | |
| 5146 | if ($appendTimeStamp && strlen($value) == 10) { |
| 5147 | $value .= ' 23:59:59'; |
| 5148 | } |
| 5149 | $firstDate = CRM_Utils_Date::processDate($value); |
| 5150 | |
| 5151 | $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping); |
| 5152 | if (!empty($secondValues) && $secondValues[2]) { |
| 5153 | $secondOP = '>='; |
| 5154 | $secondPhrase = ts('greater than or equal to'); |
| 5155 | $secondValue = $secondValues[2]; |
| 5156 | $secondDate = CRM_Utils_Date::processDate($secondValue); |
| 5157 | } |
| 5158 | } |
| 5159 | |
| 5160 | if (!$appendTimeStamp) { |
| 5161 | $firstDate = substr($firstDate, 0, 8); |
| 5162 | } |
| 5163 | $firstDateFormat = CRM_Utils_Date::customFormat($firstDate); |
| 5164 | |
| 5165 | if ($secondDate) { |
| 5166 | if (!$appendTimeStamp) { |
| 5167 | $secondDate = substr($secondDate, 0, 8); |
| 5168 | } |
| 5169 | $secondDateFormat = CRM_Utils_Date::customFormat($secondDate); |
| 5170 | } |
| 5171 | |
| 5172 | $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1; |
| 5173 | if ($secondDate) { |
| 5174 | $this->_where[$grouping][] = " |
| 5175 | ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND |
| 5176 | ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' ) |
| 5177 | "; |
| 5178 | $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\""; |
| 5179 | } |
| 5180 | else { |
| 5181 | $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'"; |
| 5182 | $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\""; |
| 5183 | } |
| 5184 | } |
| 5185 | |
| 5186 | if ($name == $fieldName) { |
| 5187 | //In Get API, for operators other then '=' the $value is in array(op => value) format |
| 5188 | if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) { |
| 5189 | $op = key($value); |
| 5190 | $value = $value[$op]; |
| 5191 | } |
| 5192 | |
| 5193 | $date = $format = NULL; |
| 5194 | if (strstr($op, 'IN')) { |
| 5195 | $format = array(); |
| 5196 | foreach ($value as &$date) { |
| 5197 | $date = CRM_Utils_Date::processDate($date); |
| 5198 | if (!$appendTimeStamp) { |
| 5199 | $date = substr($date, 0, 8); |
| 5200 | } |
| 5201 | $format[] = CRM_Utils_Date::customFormat($date); |
| 5202 | } |
| 5203 | $date = "('" . implode("','", $value) . "')"; |
| 5204 | $format = implode(', ', $format); |
| 5205 | } |
| 5206 | elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) { |
| 5207 | $date = CRM_Utils_Date::processDate($value); |
| 5208 | if (!$appendTimeStamp) { |
| 5209 | $date = substr($date, 0, 8); |
| 5210 | } |
| 5211 | $format = CRM_Utils_Date::customFormat($date); |
| 5212 | $date = "'$date'"; |
| 5213 | } |
| 5214 | |
| 5215 | if ($date) { |
| 5216 | $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op $date"; |
| 5217 | } |
| 5218 | else { |
| 5219 | $this->_where[$grouping][] = self::buildClause("{$tableName}.{$dbFieldName}", $op); |
| 5220 | } |
| 5221 | |
| 5222 | $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1; |
| 5223 | |
| 5224 | $op = CRM_Utils_Array::value($op, CRM_Core_SelectValues::getSearchBuilderOperators(), $op); |
| 5225 | $this->_qill[$grouping][] = "$fieldTitle $op $format"; |
| 5226 | } |
| 5227 | } |
| 5228 | |
| 5229 | /** |
| 5230 | * @param $values |
| 5231 | * @param string $tableName |
| 5232 | * @param string $fieldName |
| 5233 | * @param string $dbFieldName |
| 5234 | * @param $fieldTitle |
| 5235 | * @param null $options |
| 5236 | */ |
| 5237 | public function numberRangeBuilder( |
| 5238 | &$values, |
| 5239 | $tableName, $fieldName, |
| 5240 | $dbFieldName, $fieldTitle, |
| 5241 | $options = NULL |
| 5242 | ) { |
| 5243 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 5244 | |
| 5245 | if ($name == "{$fieldName}_low" || |
| 5246 | $name == "{$fieldName}_high" |
| 5247 | ) { |
| 5248 | if (isset($this->_rangeCache[$fieldName])) { |
| 5249 | return; |
| 5250 | } |
| 5251 | $this->_rangeCache[$fieldName] = 1; |
| 5252 | |
| 5253 | $secondOP = $secondPhrase = $secondValue = NULL; |
| 5254 | |
| 5255 | if ($name == "{$fieldName}_low") { |
| 5256 | $firstOP = '>='; |
| 5257 | $firstPhrase = ts('greater than'); |
| 5258 | |
| 5259 | $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping); |
| 5260 | if (!empty($secondValues)) { |
| 5261 | $secondOP = '<='; |
| 5262 | $secondPhrase = ts('less than'); |
| 5263 | $secondValue = $secondValues[2]; |
| 5264 | } |
| 5265 | } |
| 5266 | else { |
| 5267 | $firstOP = '<='; |
| 5268 | $firstPhrase = ts('less than'); |
| 5269 | |
| 5270 | $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping); |
| 5271 | if (!empty($secondValues)) { |
| 5272 | $secondOP = '>='; |
| 5273 | $secondPhrase = ts('greater than'); |
| 5274 | $secondValue = $secondValues[2]; |
| 5275 | } |
| 5276 | } |
| 5277 | |
| 5278 | if ($secondOP) { |
| 5279 | $this->_where[$grouping][] = " |
| 5280 | ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND |
| 5281 | ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} ) |
| 5282 | "; |
| 5283 | $displayValue = $options ? $options[$value] : $value; |
| 5284 | $secondDisplayValue = $options ? $options[$secondValue] : $secondValue; |
| 5285 | |
| 5286 | $this->_qill[$grouping][] |
| 5287 | = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\""; |
| 5288 | } |
| 5289 | else { |
| 5290 | $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}"; |
| 5291 | $displayValue = $options ? $options[$value] : $value; |
| 5292 | $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\""; |
| 5293 | } |
| 5294 | $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1; |
| 5295 | |
| 5296 | return; |
| 5297 | } |
| 5298 | |
| 5299 | if ($name == $fieldName) { |
| 5300 | $op = '='; |
| 5301 | $phrase = '='; |
| 5302 | |
| 5303 | $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}"; |
| 5304 | |
| 5305 | $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1; |
| 5306 | $displayValue = $options ? $options[$value] : $value; |
| 5307 | $this->_qill[$grouping][] = "$fieldTitle - $phrase \"$displayValue\""; |
| 5308 | } |
| 5309 | } |
| 5310 | |
| 5311 | |
| 5312 | /** |
| 5313 | * @param $values |
| 5314 | * @param string $tableName |
| 5315 | * @param string $fieldName |
| 5316 | * @param string $dbFieldName |
| 5317 | * @param $fieldTitle |
| 5318 | * @param null $options |
| 5319 | */ |
| 5320 | public function ageRangeQueryBuilder( |
| 5321 | &$values, |
| 5322 | $tableName, $fieldName, |
| 5323 | $dbFieldName, $fieldTitle, |
| 5324 | $options = NULL |
| 5325 | ) { |
| 5326 | list($name, $op, $value, $grouping, $wildcard) = $values; |
| 5327 | |
| 5328 | $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping); |
| 5329 | $asofDate = NULL; // will be treated as current day |
| 5330 | if ($asofDateValues) { |
| 5331 | $asofDate = CRM_Utils_Date::processDate($asofDateValues[2]); |
| 5332 | $asofDateFormat = CRM_Utils_Date::customFormat(substr($asofDate, 0, 8)); |
| 5333 | $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat; |
| 5334 | } |
| 5335 | |
| 5336 | if ($name == "{$fieldName}_low" || |
| 5337 | $name == "{$fieldName}_high" |
| 5338 | ) { |
| 5339 | if (isset($this->_rangeCache[$fieldName])) { |
| 5340 | return; |
| 5341 | } |
| 5342 | $this->_rangeCache[$fieldName] = 1; |
| 5343 | |
| 5344 | $secondOP = $secondPhrase = $secondValue = NULL; |
| 5345 | |
| 5346 | if ($name == "{$fieldName}_low") { |
| 5347 | $firstPhrase = ts('greater than or equal to'); |
| 5348 | // NB: age > X means date of birth < Y |
| 5349 | $firstOP = '<='; |
| 5350 | $firstDate = self::calcDateFromAge($asofDate, $value, 'min'); |
| 5351 | |
| 5352 | $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping); |
| 5353 | if (!empty($secondValues)) { |
| 5354 | $secondOP = '>='; |
| 5355 | $secondPhrase = ts('less than or equal to'); |
| 5356 | $secondValue = $secondValues[2]; |
| 5357 | $secondDate = self::calcDateFromAge($asofDate, $secondValue, 'max'); |
| 5358 | } |
| 5359 | } |
| 5360 | else { |
| 5361 | $firstOP = '>='; |
| 5362 | $firstPhrase = ts('less than or equal to'); |
| 5363 | $firstDate = self::calcDateFromAge($asofDate, $value, 'max'); |
| 5364 | |
| 5365 | $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping); |
| 5366 | if (!empty($secondValues)) { |
| 5367 | $secondOP = '<='; |
| 5368 | $secondPhrase = ts('greater than or equal to'); |
| 5369 | $secondValue = $secondValues[2]; |
| 5370 | $secondDate = self::calcDateFromAge($asofDate, $secondValue, 'min'); |
| 5371 | } |
| 5372 | } |
| 5373 | |
| 5374 | if ($secondOP) { |
| 5375 | $this->_where[$grouping][] = " |
| 5376 | ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND |
| 5377 | ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' ) |
| 5378 | "; |
| 5379 | $displayValue = $options ? $options[$value] : $value; |
| 5380 | $secondDisplayValue = $options ? $options[$secondValue] : $secondValue; |
| 5381 | |
| 5382 | $this->_qill[$grouping][] |
| 5383 | = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\""; |
| 5384 | } |
| 5385 | else { |
| 5386 | $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'"; |
| 5387 | $displayValue = $options ? $options[$value] : $value; |
| 5388 | $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\""; |
| 5389 | } |
| 5390 | $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1; |
| 5391 | return; |
| 5392 | } |
| 5393 | } |
| 5394 | |
| 5395 | /** |
| 5396 | * Calculate date from age. |
| 5397 | * |
| 5398 | * @param string $asofDate |
| 5399 | * @param int $age |
| 5400 | * @param string $type |
| 5401 | * |
| 5402 | * @return string |
| 5403 | */ |
| 5404 | public static function calcDateFromAge($asofDate, $age, $type) { |
| 5405 | $date = new DateTime($asofDate); |
| 5406 | if ($type == "min") { |
| 5407 | // minimum age is $age: dob <= date - age "235959" |
| 5408 | $date->sub(new DateInterval("P" . $age . "Y")); |
| 5409 | return $date->format('Ymd') . "235959"; |
| 5410 | } |
| 5411 | else { |
| 5412 | // max age is $age: dob >= date - (age + 1y) + 1d "000000" |
| 5413 | $date->sub(new DateInterval("P" . ($age + 1) . "Y"))->add(new DateInterval("P1D")); |
| 5414 | return $date->format('Ymd') . "000000"; |
| 5415 | } |
| 5416 | } |
| 5417 | |
| 5418 | /** |
| 5419 | * Given the field name, operator, value & its data type |
| 5420 | * builds the where Clause for the query |
| 5421 | * used for handling 'IS NULL'/'IS NOT NULL' operators |
| 5422 | * |
| 5423 | * @param string $field |
| 5424 | * Fieldname. |
| 5425 | * @param string $op |
| 5426 | * Operator. |
| 5427 | * @param string $value |
| 5428 | * Value. |
| 5429 | * @param string $dataType |
| 5430 | * Data type of the field. |
| 5431 | * |
| 5432 | * @return string |
| 5433 | * Where clause for the query. |
| 5434 | */ |
| 5435 | public static function buildClause($field, $op, $value = NULL, $dataType = NULL) { |
| 5436 | $op = trim($op); |
| 5437 | $clause = "$field $op"; |
| 5438 | |
| 5439 | switch ($op) { |
| 5440 | case 'IS NULL': |
| 5441 | case 'IS NOT NULL': |
| 5442 | return $clause; |
| 5443 | |
| 5444 | case 'IS EMPTY': |
| 5445 | $clause = " (NULLIF($field, '') IS NULL) "; |
| 5446 | return $clause; |
| 5447 | |
| 5448 | case 'IS NOT EMPTY': |
| 5449 | $clause = " (NULLIF($field, '') IS NOT NULL) "; |
| 5450 | return $clause; |
| 5451 | |
| 5452 | case 'IN': |
| 5453 | case 'NOT IN': |
| 5454 | // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter. |
| 5455 | if (!empty($value) && (!is_array($value) || !array_key_exists($op, $value))) { |
| 5456 | $value = array($op => (array) $value); |
| 5457 | } |
| 5458 | |
| 5459 | default: |
| 5460 | if (empty($dataType)) { |
| 5461 | $dataType = 'String'; |
| 5462 | } |
| 5463 | if (is_array($value)) { |
| 5464 | //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more |
| 5465 | // widely used and consistent across the codebase |
| 5466 | // adding this here won't accept the search functions which don't submit an array |
| 5467 | if (($queryString = CRM_Core_DAO::createSqlFilter($field, $value, $dataType)) != FALSE) { |
| 5468 | |
| 5469 | return $queryString; |
| 5470 | } |
| 5471 | |
| 5472 | // This is the here-be-dragons zone. We have no other hopes left for an array so lets assume it 'should' be array('IN' => array(2,5)) |
| 5473 | // but we got only array(2,5) from the form. |
| 5474 | // We could get away with keeping this in 4.6 if we make it such that it throws an enotice in 4.7 so |
| 5475 | // people have to de-slopify it. |
| 5476 | if (!empty($value[0])) { |
| 5477 | if ($op != 'BETWEEN') { |
| 5478 | $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReport; |
| 5479 | } |
| 5480 | if (($queryString = CRM_Core_DAO::createSqlFilter($field, array($op => $value), $dataType)) != FALSE) { |
| 5481 | return $queryString; |
| 5482 | } |
| 5483 | } |
| 5484 | else { |
| 5485 | $op = 'IN'; |
| 5486 | $dragonPlace = $iAmAnIntentionalENoticeThatWarnsOfAProblemYouShouldReportUsingOldFormat; |
| 5487 | if (($queryString = CRM_Core_DAO::createSqlFilter($field, array($op => array_keys($value)), $dataType)) != FALSE) { |
| 5488 | return $queryString; |
| 5489 | } |
| 5490 | } |
| 5491 | } |
| 5492 | |
| 5493 | $value = CRM_Utils_Type::escape($value, $dataType); |
| 5494 | // if we don't have a dataType we should assume |
| 5495 | if ($dataType == 'String' || $dataType == 'Text') { |
| 5496 | $value = "'" . strtolower($value) . "'"; |
| 5497 | } |
| 5498 | return "$clause $value"; |
| 5499 | } |
| 5500 | } |
| 5501 | |
| 5502 | /** |
| 5503 | * @param bool $reset |
| 5504 | * |
| 5505 | * @return array |
| 5506 | */ |
| 5507 | public function openedSearchPanes($reset = FALSE) { |
| 5508 | if (!$reset || empty($this->_whereTables)) { |
| 5509 | return self::$_openedPanes; |
| 5510 | } |
| 5511 | |
| 5512 | // pane name to table mapper |
| 5513 | $panesMapper = array( |
| 5514 | ts('Contributions') => 'civicrm_contribution', |
| 5515 | ts('Memberships') => 'civicrm_membership', |
| 5516 | ts('Events') => 'civicrm_participant', |
| 5517 | ts('Relationships') => 'civicrm_relationship', |
| 5518 | ts('Activities') => 'civicrm_activity', |
| 5519 | ts('Pledges') => 'civicrm_pledge', |
| 5520 | ts('Cases') => 'civicrm_case', |
| 5521 | ts('Grants') => 'civicrm_grant', |
| 5522 | ts('Address Fields') => 'civicrm_address', |
| 5523 | ts('Notes') => 'civicrm_note', |
| 5524 | ts('Change Log') => 'civicrm_log', |
| 5525 | ts('Mailings') => 'civicrm_mailing', |
| 5526 | ); |
| 5527 | CRM_Contact_BAO_Query_Hook::singleton()->getPanesMapper($panesMapper); |
| 5528 | |
| 5529 | foreach (array_keys($this->_whereTables) as $table) { |
| 5530 | if ($panName = array_search($table, $panesMapper)) { |
| 5531 | self::$_openedPanes[$panName] = TRUE; |
| 5532 | } |
| 5533 | } |
| 5534 | |
| 5535 | return self::$_openedPanes; |
| 5536 | } |
| 5537 | |
| 5538 | /** |
| 5539 | * @param $operator |
| 5540 | */ |
| 5541 | public function setOperator($operator) { |
| 5542 | $validOperators = array('AND', 'OR'); |
| 5543 | if (!in_array($operator, $validOperators)) { |
| 5544 | $operator = 'AND'; |
| 5545 | } |
| 5546 | $this->_operator = $operator; |
| 5547 | } |
| 5548 | |
| 5549 | /** |
| 5550 | * @return string |
| 5551 | */ |
| 5552 | public function getOperator() { |
| 5553 | return $this->_operator; |
| 5554 | } |
| 5555 | |
| 5556 | /** |
| 5557 | * @param $from |
| 5558 | * @param $where |
| 5559 | * @param $having |
| 5560 | */ |
| 5561 | public function filterRelatedContacts(&$from, &$where, &$having) { |
| 5562 | static $_rTypeProcessed = NULL; |
| 5563 | static $_rTypeFrom = NULL; |
| 5564 | static $_rTypeWhere = NULL; |
| 5565 | |
| 5566 | if (!$_rTypeProcessed) { |
| 5567 | $_rTypeProcessed = TRUE; |
| 5568 | |
| 5569 | // create temp table with contact ids |
| 5570 | $tableName = CRM_Core_DAO::createTempTableName('civicrm_transform', TRUE); |
| 5571 | $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP"; |
| 5572 | CRM_Core_DAO::executeQuery($sql); |
| 5573 | |
| 5574 | $sql = " |
| 5575 | REPLACE INTO $tableName ( contact_id ) |
| 5576 | SELECT contact_a.id |
| 5577 | $from |
| 5578 | $where |
| 5579 | $having |
| 5580 | "; |
| 5581 | CRM_Core_DAO::executeQuery($sql); |
| 5582 | |
| 5583 | $qillMessage = ts('Contacts with a Relationship Type of: '); |
| 5584 | $rTypes = CRM_Core_PseudoConstant::relationshipType(); |
| 5585 | |
| 5586 | if (is_numeric($this->_displayRelationshipType)) { |
| 5587 | $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType]['label_a_b']; |
| 5588 | $_rTypeFrom = " |
| 5589 | INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id ) |
| 5590 | INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b ) |
| 5591 | "; |
| 5592 | $_rTypeWhere = " |
| 5593 | WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType} |
| 5594 | AND displayRelType.is_active = 1 |
| 5595 | "; |
| 5596 | } |
| 5597 | else { |
| 5598 | list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType); |
| 5599 | if ($dirOne == 'a') { |
| 5600 | $relationshipTypeLabel = $rTypes[$relType]['label_a_b']; |
| 5601 | $_rTypeFrom .= " |
| 5602 | INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id ) |
| 5603 | INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b ) |
| 5604 | "; |
| 5605 | } |
| 5606 | else { |
| 5607 | $relationshipTypeLabel = $rTypes[$relType]['label_b_a']; |
| 5608 | $_rTypeFrom .= " |
| 5609 | INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id ) |
| 5610 | INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a ) |
| 5611 | "; |
| 5612 | } |
| 5613 | $_rTypeWhere = " |
| 5614 | WHERE displayRelType.relationship_type_id = $relType |
| 5615 | AND displayRelType.is_active = 1 |
| 5616 | "; |
| 5617 | } |
| 5618 | $this->_qill[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'"; |
| 5619 | } |
| 5620 | |
| 5621 | if (!empty($this->_permissionWhereClause)) { |
| 5622 | $_rTypeWhere .= "AND $this->_permissionWhereClause"; |
| 5623 | } |
| 5624 | |
| 5625 | if (strpos($from, $_rTypeFrom) === FALSE) { |
| 5626 | // lets replace all the INNER JOIN's in the $from so we dont exclude other data |
| 5627 | // this happens when we have an event_type in the quert (CRM-7969) |
| 5628 | $from = str_replace("INNER JOIN", "LEFT JOIN", $from); |
| 5629 | $from .= $_rTypeFrom; |
| 5630 | $where = $_rTypeWhere; |
| 5631 | } |
| 5632 | |
| 5633 | $having = NULL; |
| 5634 | } |
| 5635 | |
| 5636 | /** |
| 5637 | * See CRM-19811 for why this is database hurty without apparent benefit. |
| 5638 | * |
| 5639 | * @param $op |
| 5640 | * |
| 5641 | * @return bool |
| 5642 | */ |
| 5643 | public static function caseImportant($op) { |
| 5644 | return |
| 5645 | in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ? FALSE : TRUE; |
| 5646 | } |
| 5647 | |
| 5648 | /** |
| 5649 | * @param $returnProperties |
| 5650 | * @param $prefix |
| 5651 | * |
| 5652 | * @return bool |
| 5653 | */ |
| 5654 | public static function componentPresent(&$returnProperties, $prefix) { |
| 5655 | foreach ($returnProperties as $name => $dontCare) { |
| 5656 | if (substr($name, 0, strlen($prefix)) == $prefix) { |
| 5657 | return TRUE; |
| 5658 | } |
| 5659 | } |
| 5660 | return FALSE; |
| 5661 | } |
| 5662 | |
| 5663 | /** |
| 5664 | * Builds the necessary structures for all fields that are similar to option value look-ups. |
| 5665 | * |
| 5666 | * @param string $name |
| 5667 | * the name of the field. |
| 5668 | * @param string $op |
| 5669 | * the sql operator, this function should handle ALL SQL operators. |
| 5670 | * @param string $value |
| 5671 | * depends on the operator and who's calling the query builder. |
| 5672 | * @param int $grouping |
| 5673 | * the index where to place the where clause. |
| 5674 | * @param string $daoName |
| 5675 | * DAO Name. |
| 5676 | * @param array $field |
| 5677 | * an array that contains various properties of the field identified by $name. |
| 5678 | * @param string $label |
| 5679 | * The label for this field element. |
| 5680 | * @param string $dataType |
| 5681 | * The data type for this element. |
| 5682 | * @param bool $useIDsOnly |
| 5683 | */ |
| 5684 | public function optionValueQuery( |
| 5685 | $name, |
| 5686 | $op, |
| 5687 | $value, |
| 5688 | $grouping, |
| 5689 | $daoName = NULL, |
| 5690 | $field, |
| 5691 | $label, |
| 5692 | $dataType = 'String', |
| 5693 | $useIDsOnly = FALSE |
| 5694 | ) { |
| 5695 | |
| 5696 | $pseudoFields = array( |
| 5697 | 'email_greeting', |
| 5698 | 'postal_greeting', |
| 5699 | 'addressee', |
| 5700 | 'gender_id', |
| 5701 | 'prefix_id', |
| 5702 | 'suffix_id', |
| 5703 | 'communication_style_id', |
| 5704 | ); |
| 5705 | |
| 5706 | if ($useIDsOnly) { |
| 5707 | list($tableName, $fieldName) = explode('.', $field['where'], 2); |
| 5708 | if ($tableName == 'civicrm_contact') { |
| 5709 | $wc = "contact_a.$fieldName"; |
| 5710 | } |
| 5711 | else { |
| 5712 | $wc = "$tableName.id"; |
| 5713 | } |
| 5714 | } |
| 5715 | else { |
| 5716 | // LOWER roughly translates to 'hurt my database without deriving any benefit' See CRM-19811. |
| 5717 | $wc = self::caseImportant($op) ? "LOWER({$field['where']})" : "{$field['where']}"; |
| 5718 | } |
| 5719 | if (in_array($name, $pseudoFields)) { |
| 5720 | if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) { |
| 5721 | $wc = "contact_a.{$name}_id"; |
| 5722 | } |
| 5723 | $dataType = 'Positive'; |
| 5724 | $value = (!$value) ? 0 : $value; |
| 5725 | } |
| 5726 | if ($name == "world_region") { |
| 5727 | $field['name'] = $name; |
| 5728 | } |
| 5729 | |
| 5730 | list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue($daoName, $field['name'], $value, $op); |
| 5731 | $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillop, 3 => $qillVal)); |
| 5732 | $this->_where[$grouping][] = self::buildClause($wc, $op, $value, $dataType); |
| 5733 | } |
| 5734 | |
| 5735 | /** |
| 5736 | * Check and explode a user defined numeric string into an array |
| 5737 | * this was the protocol used by search builder in the old old days before we had |
| 5738 | * super nice js widgets to do the hard work |
| 5739 | * |
| 5740 | * @param string $string |
| 5741 | * @param string $dataType |
| 5742 | * The dataType we should check for the values, default integer. |
| 5743 | * |
| 5744 | * @return bool|array |
| 5745 | * false if string does not match the pattern |
| 5746 | * array of numeric values if string does match the pattern |
| 5747 | */ |
| 5748 | public static function parseSearchBuilderString($string, $dataType = 'Integer') { |
| 5749 | $string = trim($string); |
| 5750 | if (substr($string, 0, 1) != '(' || substr($string, -1, 1) != ')') { |
| 5751 | Return FALSE; |
| 5752 | } |
| 5753 | |
| 5754 | $string = substr($string, 1, -1); |
| 5755 | $values = explode(',', $string); |
| 5756 | if (empty($values)) { |
| 5757 | return FALSE; |
| 5758 | } |
| 5759 | |
| 5760 | $returnValues = array(); |
| 5761 | foreach ($values as $v) { |
| 5762 | if ($dataType == 'Integer' && !is_numeric($v)) { |
| 5763 | return FALSE; |
| 5764 | } |
| 5765 | elseif ($dataType == 'String' && !is_string($v)) { |
| 5766 | return FALSE; |
| 5767 | } |
| 5768 | $returnValues[] = trim($v); |
| 5769 | } |
| 5770 | |
| 5771 | if (empty($returnValues)) { |
| 5772 | return FALSE; |
| 5773 | } |
| 5774 | |
| 5775 | return $returnValues; |
| 5776 | } |
| 5777 | |
| 5778 | /** |
| 5779 | * Convert the pseudo constants id's to their names |
| 5780 | * |
| 5781 | * @param CRM_Core_DAO $dao |
| 5782 | * @param bool $return |
| 5783 | * @param bool $usedForAPI |
| 5784 | * |
| 5785 | * @return array|NULL |
| 5786 | */ |
| 5787 | public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) { |
| 5788 | if (empty($this->_pseudoConstantsSelect)) { |
| 5789 | return NULL; |
| 5790 | } |
| 5791 | $values = array(); |
| 5792 | foreach ($this->_pseudoConstantsSelect as $key => $value) { |
| 5793 | if (!empty($this->_pseudoConstantsSelect[$key]['sorting'])) { |
| 5794 | continue; |
| 5795 | } |
| 5796 | |
| 5797 | if (is_object($dao) && property_exists($dao, $value['idCol'])) { |
| 5798 | $val = $dao->{$value['idCol']}; |
| 5799 | if ($key == 'groups') { |
| 5800 | $dao->groups = $this->convertGroupIDStringToLabelString($dao, $val); |
| 5801 | return; |
| 5802 | } |
| 5803 | |
| 5804 | if (CRM_Utils_System::isNull($val)) { |
| 5805 | $dao->$key = NULL; |
| 5806 | } |
| 5807 | elseif ($baoName = CRM_Utils_Array::value('bao', $value, NULL)) { |
| 5808 | //preserve id value |
| 5809 | $idColumn = "{$key}_id"; |
| 5810 | $dao->$idColumn = $val; |
| 5811 | |
| 5812 | if ($key == 'state_province_name') { |
| 5813 | $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant::stateProvinceAbbreviation($val); |
| 5814 | } |
| 5815 | else { |
| 5816 | $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant::getLabel($baoName, $value['pseudoField'], $val); |
| 5817 | } |
| 5818 | } |
| 5819 | elseif ($value['pseudoField'] == 'state_province_abbreviation') { |
| 5820 | $dao->$key = CRM_Core_PseudoConstant::stateProvinceAbbreviation($val); |
| 5821 | } |
| 5822 | // FIX ME: we should potentially move this to component Query and write a wrapper function that |
| 5823 | // handles pseudoconstant fixes for all component |
| 5824 | elseif (in_array($value['pseudoField'], array('participant_role_id', 'participant_role'))) { |
| 5825 | $viewValues = explode(CRM_Core_DAO::VALUE_SEPARATOR, $val); |
| 5826 | |
| 5827 | if ($value['pseudoField'] == 'participant_role') { |
| 5828 | $pseudoOptions = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'role_id'); |
| 5829 | foreach ($viewValues as $k => $v) { |
| 5830 | $viewValues[$k] = $pseudoOptions[$v]; |
| 5831 | } |
| 5832 | } |
| 5833 | $dao->$key = ($usedForAPI && count($viewValues) > 1) ? $viewValues : implode(', ', $viewValues); |
| 5834 | } |
| 5835 | else { |
| 5836 | $labels = CRM_Core_OptionGroup::values($value['pseudoField']); |
| 5837 | $dao->$key = $labels[$val]; |
| 5838 | } |
| 5839 | |
| 5840 | // return converted values in array format |
| 5841 | if ($return) { |
| 5842 | if (strpos($key, '-') !== FALSE) { |
| 5843 | $keyVal = explode('-', $key); |
| 5844 | $current = &$values; |
| 5845 | $lastElement = array_pop($keyVal); |
| 5846 | foreach ($keyVal as $v) { |
| 5847 | if (!array_key_exists($v, $current)) { |
| 5848 | $current[$v] = array(); |
| 5849 | } |
| 5850 | $current = &$current[$v]; |
| 5851 | } |
| 5852 | $current[$lastElement] = $dao->$key; |
| 5853 | } |
| 5854 | else { |
| 5855 | $values[$key] = $dao->$key; |
| 5856 | } |
| 5857 | } |
| 5858 | } |
| 5859 | } |
| 5860 | return $values; |
| 5861 | } |
| 5862 | |
| 5863 | /** |
| 5864 | * Include pseudo fields LEFT JOIN. |
| 5865 | * @param string|array $sort can be a object or string |
| 5866 | * |
| 5867 | * @return array|NULL |
| 5868 | */ |
| 5869 | public function includePseudoFieldsJoin($sort) { |
| 5870 | if (!$sort || empty($this->_pseudoConstantsSelect)) { |
| 5871 | return NULL; |
| 5872 | } |
| 5873 | $sort = is_string($sort) ? $sort : $sort->orderBy(); |
| 5874 | $present = array(); |
| 5875 | |
| 5876 | foreach ($this->_pseudoConstantsSelect as $name => $value) { |
| 5877 | if (!empty($value['table'])) { |
| 5878 | $regex = "/({$value['table']}\.|{$name})/"; |
| 5879 | if (preg_match($regex, $sort)) { |
| 5880 | $this->_elemnt[$value['element']] = 1; |
| 5881 | $this->_select[$value['element']] = $value['select']; |
| 5882 | $this->_pseudoConstantsSelect[$name]['sorting'] = 1; |
| 5883 | $present[$value['table']] = $value['join']; |
| 5884 | } |
| 5885 | } |
| 5886 | } |
| 5887 | $presentSimpleFrom = $present; |
| 5888 | |
| 5889 | if (array_key_exists('civicrm_worldregion', $this->_whereTables) && |
| 5890 | array_key_exists('civicrm_country', $presentSimpleFrom) |
| 5891 | ) { |
| 5892 | unset($presentSimpleFrom['civicrm_country']); |
| 5893 | } |
| 5894 | if (array_key_exists('civicrm_worldregion', $this->_tables) && |
| 5895 | array_key_exists('civicrm_country', $present) |
| 5896 | ) { |
| 5897 | unset($present['civicrm_country']); |
| 5898 | } |
| 5899 | |
| 5900 | $presentClause = $presentSimpleFromClause = NULL; |
| 5901 | if (!empty($present)) { |
| 5902 | $presentClause = implode(' ', $present); |
| 5903 | } |
| 5904 | if (!empty($presentSimpleFrom)) { |
| 5905 | $presentSimpleFromClause = implode(' ', $presentSimpleFrom); |
| 5906 | } |
| 5907 | |
| 5908 | $this->_fromClause = $this->_fromClause . $presentClause; |
| 5909 | $this->_simpleFromClause = $this->_simpleFromClause . $presentSimpleFromClause; |
| 5910 | |
| 5911 | return array($presentClause, $presentSimpleFromClause); |
| 5912 | } |
| 5913 | |
| 5914 | /** |
| 5915 | * Build qill for field. |
| 5916 | * |
| 5917 | * Qill refers to the query detail visible on the UI. |
| 5918 | * |
| 5919 | * @param string $daoName |
| 5920 | * @param string $fieldName |
| 5921 | * @param mixed $fieldValue |
| 5922 | * @param string $op |
| 5923 | * @param array $pseudoExtraParam |
| 5924 | * @param int $type |
| 5925 | * Type of the field per CRM_Utils_Type |
| 5926 | * |
| 5927 | * @return array |
| 5928 | */ |
| 5929 | public static function buildQillForFieldValue( |
| 5930 | $daoName, |
| 5931 | $fieldName, |
| 5932 | $fieldValue, |
| 5933 | $op, |
| 5934 | $pseudoExtraParam = array(), |
| 5935 | $type = CRM_Utils_Type::T_STRING |
| 5936 | ) { |
| 5937 | $qillOperators = CRM_Core_SelectValues::getSearchBuilderOperators(); |
| 5938 | |
| 5939 | //API usually have fieldValue format as array(operator => array(values)), |
| 5940 | //so we need to separate operator out of fieldValue param |
| 5941 | if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) { |
| 5942 | $op = key($fieldValue); |
| 5943 | $fieldValue = $fieldValue[$op]; |
| 5944 | } |
| 5945 | |
| 5946 | // if Operator chosen is NULL/EMPTY then |
| 5947 | if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) { |
| 5948 | return array(CRM_Utils_Array::value($op, $qillOperators, $op), ''); |
| 5949 | } |
| 5950 | |
| 5951 | if ($fieldName == 'activity_type_id') { |
| 5952 | $pseudoOptions = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE); |
| 5953 | } |
| 5954 | elseif ($fieldName == 'country_id') { |
| 5955 | $pseudoOptions = CRM_Core_PseudoConstant::country(); |
| 5956 | } |
| 5957 | elseif ($fieldName == 'county_id') { |
| 5958 | $pseudoOptions = CRM_Core_PseudoConstant::county(); |
| 5959 | } |
| 5960 | elseif ($fieldName == 'world_region') { |
| 5961 | $pseudoOptions = CRM_Core_PseudoConstant::worldRegion(); |
| 5962 | } |
| 5963 | elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') { |
| 5964 | $pseudoOptions = CRM_Event_BAO_Event::getEvents(0, $fieldValue, TRUE, TRUE, TRUE); |
| 5965 | } |
| 5966 | elseif ($fieldName == 'contribution_product_id') { |
| 5967 | $pseudoOptions = CRM_Contribute_PseudoConstant::products(); |
| 5968 | } |
| 5969 | elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') { |
| 5970 | $pseudoOptions = CRM_Core_PseudoConstant::group(); |
| 5971 | } |
| 5972 | elseif ($daoName == 'CRM_Batch_BAO_EntityBatch' && $fieldName == 'batch_id') { |
| 5973 | $pseudoOptions = CRM_Contribute_PseudoConstant::batch(); |
| 5974 | } |
| 5975 | elseif ($daoName) { |
| 5976 | $pseudoOptions = CRM_Core_PseudoConstant::get($daoName, $fieldName, $pseudoExtraParam); |
| 5977 | } |
| 5978 | |
| 5979 | if (is_array($fieldValue)) { |
| 5980 | $qillString = array(); |
| 5981 | if (!empty($pseudoOptions)) { |
| 5982 | foreach ((array) $fieldValue as $val) { |
| 5983 | $qillString[] = CRM_Utils_Array::value($val, $pseudoOptions, $val); |
| 5984 | } |
| 5985 | $fieldValue = implode(', ', $qillString); |
| 5986 | } |
| 5987 | else { |
| 5988 | if ($type == CRM_Utils_Type::T_DATE) { |
| 5989 | foreach ($fieldValue as $index => $value) { |
| 5990 | $fieldValue[$index] = CRM_Utils_Date::customFormat($value); |
| 5991 | } |
| 5992 | } |
| 5993 | $separator = ', '; |
| 5994 | // @todo - this is a bit specific (one operator). |
| 5995 | // However it is covered by a unit test so can be altered later with |
| 5996 | // some confidence. |
| 5997 | if ($op == 'BETWEEN') { |
| 5998 | $separator = ' AND '; |
| 5999 | } |
| 6000 | $fieldValue = implode($separator, $fieldValue); |
| 6001 | } |
| 6002 | } |
| 6003 | elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) { |
| 6004 | $fieldValue = $pseudoOptions[$fieldValue]; |
| 6005 | } |
| 6006 | elseif ($type === CRM_Utils_Type::T_DATE) { |
| 6007 | $fieldValue = CRM_Utils_Date::customFormat($fieldValue); |
| 6008 | } |
| 6009 | |
| 6010 | return array(CRM_Utils_Array::value($op, $qillOperators, $op), $fieldValue); |
| 6011 | } |
| 6012 | |
| 6013 | /** |
| 6014 | * Alter value to reflect wildcard settings. |
| 6015 | * |
| 6016 | * The form will have tried to guess whether this is a good field to wildcard but there is |
| 6017 | * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning |
| 6018 | * or only the end of the string |
| 6019 | * |
| 6020 | * @param bool $wildcard |
| 6021 | * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard. |
| 6022 | * @param string $op |
| 6023 | * Generally '=' or 'LIKE'. |
| 6024 | * @param string $value |
| 6025 | * The search string. |
| 6026 | * |
| 6027 | * @return string |
| 6028 | */ |
| 6029 | public static function getWildCardedValue($wildcard, $op, $value) { |
| 6030 | if ($wildcard && $op == 'LIKE') { |
| 6031 | if (CRM_Core_Config::singleton()->includeWildCardInName && (substr($value, 0, 1) != '%')) { |
| 6032 | return "%$value%"; |
| 6033 | } |
| 6034 | else { |
| 6035 | return "$value%"; |
| 6036 | } |
| 6037 | } |
| 6038 | else { |
| 6039 | return "$value"; |
| 6040 | } |
| 6041 | } |
| 6042 | |
| 6043 | /** |
| 6044 | * Process special fields of Search Form in OK (Operator in Key) format |
| 6045 | * |
| 6046 | * @param array $formValues |
| 6047 | * @param array $specialFields |
| 6048 | * Special params to be processed |
| 6049 | * @param array $changeNames |
| 6050 | * Array of fields whose name should be changed |
| 6051 | */ |
| 6052 | public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = array()) { |
| 6053 | // Array of special fields whose value are considered only for NULL or EMPTY operators |
| 6054 | $nullableFields = array('contribution_batch_id'); |
| 6055 | |
| 6056 | foreach ($specialFields as $element) { |
| 6057 | $value = CRM_Utils_Array::value($element, $formValues); |
| 6058 | if ($value) { |
| 6059 | if (is_array($value)) { |
| 6060 | if (in_array($element, array_keys($changeNames))) { |
| 6061 | unset($formValues[$element]); |
| 6062 | $element = $changeNames[$element]; |
| 6063 | } |
| 6064 | $formValues[$element] = array('IN' => $value); |
| 6065 | } |
| 6066 | elseif (in_array($value, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) { |
| 6067 | $formValues[$element] = array($value => 1); |
| 6068 | } |
| 6069 | elseif (!in_array($element, $nullableFields)) { |
| 6070 | // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard |
| 6071 | $isWilcard = strstr($value, '%') ? FALSE : CRM_Core_Config::singleton()->includeWildCardInName; |
| 6072 | $formValues[$element] = array('LIKE' => self::getWildCardedValue($isWilcard, 'LIKE', $value)); |
| 6073 | } |
| 6074 | } |
| 6075 | } |
| 6076 | } |
| 6077 | |
| 6078 | /** |
| 6079 | * Parse and assimilate the various sort options. |
| 6080 | * |
| 6081 | * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`, |
| 6082 | * `email`), the related table may be joined automatically. |
| 6083 | * |
| 6084 | * At time of writing, this code is deeply flawed and should be rewritten. For the moment, |
| 6085 | * it's been extracted to a standalone function. |
| 6086 | * |
| 6087 | * @param string|CRM_Utils_Sort $sort |
| 6088 | * The order by string. |
| 6089 | * @param bool $sortByChar |
| 6090 | * If true returns the distinct array of first characters for search results. |
| 6091 | * @param null $sortOrder |
| 6092 | * Who knows? Hu knows. He who knows Hu knows who. |
| 6093 | * @param string $additionalFromClause |
| 6094 | * Should be clause with proper joins, effective to reduce where clause load. |
| 6095 | * @return array |
| 6096 | * list(string $orderByClause, string $additionalFromClause). |
| 6097 | */ |
| 6098 | protected function prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause) { |
| 6099 | $order = NULL; |
| 6100 | $config = CRM_Core_Config::singleton(); |
| 6101 | if ($config->includeOrderByClause || |
| 6102 | isset($this->_distinctComponentClause) |
| 6103 | ) { |
| 6104 | if ($sort) { |
| 6105 | if (is_string($sort)) { |
| 6106 | $orderBy = $sort; |
| 6107 | } |
| 6108 | else { |
| 6109 | $orderBy = trim($sort->orderBy()); |
| 6110 | } |
| 6111 | // Deliberately remove the backticks again, as they mess up the evil |
| 6112 | // string munging below. This balanced by re-escaping before use. |
| 6113 | $orderBy = str_replace('`', '', $orderBy); |
| 6114 | |
| 6115 | if (!empty($orderBy)) { |
| 6116 | // this is special case while searching for |
| 6117 | // change log CRM-1718 |
| 6118 | if (preg_match('/sort_name/i', $orderBy)) { |
| 6119 | $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy); |
| 6120 | } |
| 6121 | |
| 6122 | $order = " ORDER BY $orderBy"; |
| 6123 | |
| 6124 | if ($sortOrder) { |
| 6125 | $order .= " $sortOrder"; |
| 6126 | } |
| 6127 | |
| 6128 | // always add contact_a.id to the ORDER clause |
| 6129 | // so the order is deterministic |
| 6130 | if (strpos('contact_a.id', $order) === FALSE) { |
| 6131 | $order .= ", contact_a.id"; |
| 6132 | } |
| 6133 | } |
| 6134 | } |
| 6135 | elseif ($sortByChar) { |
| 6136 | $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc"; |
| 6137 | } |
| 6138 | else { |
| 6139 | $order = " ORDER BY contact_a.sort_name asc, contact_a.id"; |
| 6140 | } |
| 6141 | } |
| 6142 | |
| 6143 | // hack for order clause |
| 6144 | if ($order) { |
| 6145 | $fieldStr = trim(str_replace('ORDER BY', '', $order)); |
| 6146 | $fieldOrder = explode(' ', $fieldStr); |
| 6147 | $field = $fieldOrder[0]; |
| 6148 | |
| 6149 | if ($field) { |
| 6150 | switch ($field) { |
| 6151 | case 'city': |
| 6152 | case 'postal_code': |
| 6153 | $this->_tables["civicrm_address"] = $this->_whereTables["civicrm_address"] = 1; |
| 6154 | $order = str_replace($field, "civicrm_address.{$field}", $order); |
| 6155 | break; |
| 6156 | |
| 6157 | case 'country': |
| 6158 | case 'state_province': |
| 6159 | $this->_tables["civicrm_{$field}"] = $this->_whereTables["civicrm_{$field}"] = 1; |
| 6160 | if (is_array($this->_returnProperties) && empty($this->_returnProperties)) { |
| 6161 | $additionalFromClause .= " LEFT JOIN civicrm_{$field} ON civicrm_{$field}.id = civicrm_address.{$field}_id"; |
| 6162 | } |
| 6163 | $order = str_replace($field, "civicrm_{$field}.name", $order); |
| 6164 | break; |
| 6165 | |
| 6166 | case 'email': |
| 6167 | $this->_tables["civicrm_email"] = $this->_whereTables["civicrm_email"] = 1; |
| 6168 | $order = str_replace($field, "civicrm_email.{$field}", $order); |
| 6169 | break; |
| 6170 | |
| 6171 | default: |
| 6172 | //CRM-12565 add "`" around $field if it is a pseudo constant |
| 6173 | foreach ($this->_pseudoConstantsSelect as $key => $value) { |
| 6174 | if (!empty($value['element']) && $value['element'] == $field) { |
| 6175 | $order = str_replace($field, "`{$field}`", $order); |
| 6176 | } |
| 6177 | } |
| 6178 | } |
| 6179 | $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode); |
| 6180 | $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode); |
| 6181 | } |
| 6182 | } |
| 6183 | |
| 6184 | // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY |
| 6185 | // clause. But this magic helper which forgivingly reescapes ORDER BY. |
| 6186 | // Note: $sortByChar implies that $order was hard-coded/trusted, so it can do funky things. |
| 6187 | if ($order && !$sortByChar) { |
| 6188 | $order = ' ORDER BY ' . CRM_Utils_Type::escape(preg_replace('/^\s*ORDER BY\s*/', '', $order), 'MysqlOrderBy'); |
| 6189 | return array($order, $additionalFromClause); |
| 6190 | } |
| 6191 | return array($order, $additionalFromClause); |
| 6192 | } |
| 6193 | |
| 6194 | /** |
| 6195 | * Convert a string of group IDs to a string of group labels. |
| 6196 | * |
| 6197 | * The original string may include duplicates and groups the user does not have |
| 6198 | * permission to see. |
| 6199 | * |
| 6200 | * @param CRM_Core_DAO $dao |
| 6201 | * @param string $val |
| 6202 | * |
| 6203 | * @return string |
| 6204 | */ |
| 6205 | public function convertGroupIDStringToLabelString(&$dao, $val) { |
| 6206 | $groupIDs = explode(',', $val); |
| 6207 | |
| 6208 | // The pseudoConstant function does not actually cache. |
| 6209 | static $allGroups; |
| 6210 | if (!$allGroups) { |
| 6211 | $allGroups = CRM_Core_PseudoConstant::group(); |
| 6212 | } |
| 6213 | // Note that groups that the user does not have permission to will be excluded (good). |
| 6214 | $groups = array_intersect_key($allGroups, array_flip($groupIDs)); |
| 6215 | return implode(', ', $groups); |
| 6216 | |
| 6217 | } |
| 6218 | |
| 6219 | /** |
| 6220 | * Set the qill and where properties for a field. |
| 6221 | * |
| 6222 | * This function is intended as a short-term function to encourage refactoring |
| 6223 | * & re-use - but really we should just have less special-casing. |
| 6224 | * |
| 6225 | * @param string $name |
| 6226 | * @param string $op |
| 6227 | * @param string|array $value |
| 6228 | * @param string $grouping |
| 6229 | * @param string $field |
| 6230 | */ |
| 6231 | public function setQillAndWhere($name, $op, $value, $grouping, $field) { |
| 6232 | $this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $value); |
| 6233 | list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $name, $value, $op); |
| 6234 | $this->_qill[$grouping][] = ts("%1 %2 %3", array( |
| 6235 | 1 => $field['title'], |
| 6236 | 2 => $qillop, |
| 6237 | 3 => $qillVal, |
| 6238 | )); |
| 6239 | } |
| 6240 | |
| 6241 | } |