3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Include parent class definition
17 * Test contact custom search functions
22 class CRM_Contact_SelectorTest
extends CiviUnitTestCase
{
25 * Test the query from the selector class is consistent with the dataset expectation.
27 * @param array $dataSet
28 * The data set to be tested. Note that when adding new datasets often only form_values and expected where
29 * clause will need changing.
31 * @dataProvider querySets
34 public function testSelectorQuery($dataSet) {
35 $tag = $this->callAPISuccess('Tag', 'create', [
36 'name' => 'Test Tag Name' . uniqid(),
39 if (!empty($dataSet['limitedPermissions'])) {
40 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= [
42 'access deleted contacts',
45 $params = CRM_Contact_BAO_Query
::convertFormValues($dataSet['form_values'], 0, FALSE, NULL, []);
46 $isDeleted = in_array(['deleted_contacts', '=', 1, 0, 0], $params);
47 foreach ($dataSet['settings'] as $setting) {
48 $this->callAPISuccess('Setting', 'create', [$setting['name'] => $setting['value']]);
50 $selector = new CRM_Contact_Selector(
52 $dataSet['form_values'],
54 $dataSet['return_properties'],
56 $dataSet['includeContactIds'],
57 $dataSet['searchDescendentGroups'],
60 $queryObject = $selector->getQueryObject();
61 // Make sure there is no fail on alphabet query.
62 $selector->alphabetQuery()->fetchAll();
63 $sql = $queryObject->query(FALSE, FALSE, FALSE, $isDeleted);
64 $this->wrangleDefaultClauses($dataSet['expected_query']);
65 foreach ($dataSet['expected_query'] as $index => $queryString) {
66 $this->assertLike($this->strWrangle($queryString), $this->strWrangle($sql[$index]));
68 if (!empty($dataSet['where_contains'])) {
69 $this->assertStringContainsString($this->strWrangle(str_replace('@tagid', $tag['id'], $dataSet['where_contains'])), $this->strWrangle($sql[2]));
71 // Ensure that search builder return individual contact as per criteria
72 if ($dataSet['context'] === 'builder') {
73 $contactID = $this->individualCreate(['first_name' => 'James', 'last_name' => 'Bond']);
74 if ('Search builder behaviour for Activity' === $dataSet['description']) {
75 $this->callAPISuccess('Activity', 'create', [
76 'activity_type_id' => 'Meeting',
78 'source_contact_id' => $contactID,
80 $rows = CRM_Core_DAO
::executeQuery(implode(' ', $sql))->fetchAll();
81 $this->assertCount(1, $rows);
82 $this->assertEquals($contactID, $rows[0]['source_contact_id']);
85 $this->callAPISuccess('EntityTag', 'create', [
86 'entity_id' => $contactID,
87 'tag_id' => $tag['id'],
88 'entity_table' => 'civicrm_contact',
90 $this->callAPISuccess('Address', 'create', [
91 'contact_id' => $contactID,
92 'location_type_id' => 'Home',
96 $rows = $selector->getRows(CRM_Core_Action
::VIEW
, 0, 50, '');
97 $this->assertEquals(1, count($rows));
99 CRM_Core_DAO
::reenableFullGroupByMode();
100 $rows = $selector->getRows(CRM_Core_Action
::VIEW
, 0, 50, '');
102 $sortChar = $selector->alphabetQuery()->fetchAll();
103 // sort name is stored in '<last_name>, <first_name>' format, as per which the first character would be B of Bond
104 $this->assertEquals('B', $sortChar[0]['sort_name']);
105 $this->assertEquals($contactID, key($rows));
107 CRM_Core_DAO
::reenableFullGroupByMode();
108 $selector->getQueryObject()->getCachedContacts([$contactID], FALSE);
111 if (!empty($dataSet['limitedPermissions'])) {
112 $this->cleanUpAfterACLs();
114 $this->callAPISuccess('Tag', 'delete', ['id' => $tag['id']]);
118 * Test advanced search results by uf_group_id.
120 public function testSearchByProfile() {
121 //Create search profile for contacts.
122 $ufGroup = $this->callAPISuccess('uf_group', 'create', [
123 'group_type' => 'Contact',
124 'name' => 'test_search_profile',
125 'title' => 'Test Search Profile',
126 'api.uf_field.create' => [
128 'field_name' => 'email',
129 'visibility' => 'Public Pages and Listings',
130 'field_type' => 'Contact',
136 $contactID = $this->individualCreate(['email' => 'mickey@mouseville.com']);
137 //Put the email on hold.
138 $email = $this->callAPISuccess('Email', 'get', [
140 'contact_id' => $contactID,
142 $this->callAPISuccess('Email', 'create', [
143 'id' => $email['id'],
148 'description' => 'Normal default behaviour',
149 'class' => 'CRM_Contact_Selector',
151 'form_values' => ['email' => 'mickey@mouseville.com', 'uf_group_id' => $ufGroup['id']],
153 'return_properties' => NULL,
154 'context' => 'advanced',
155 'action' => CRM_Core_Action
::ADVANCED
,
156 'includeContactIds' => NULL,
157 'searchDescendentGroups' => FALSE,
159 $params = CRM_Contact_BAO_Query
::convertFormValues($dataSet['form_values'], 0, FALSE, NULL, []);
160 // create CRM_Contact_Selector instance and set desired query params
161 $selector = new CRM_Contact_Selector(
163 $dataSet['form_values'],
165 $dataSet['return_properties'],
167 $dataSet['includeContactIds'],
168 $dataSet['searchDescendentGroups'],
171 $rows = $selector->getRows(CRM_Core_Action
::VIEW
, 0, 50, '');
172 $this->assertEquals(1, count($rows));
173 $this->assertEquals($contactID, key($rows));
175 //Check if email column contains (On Hold) string.
176 foreach ($rows[$contactID] as $key => $value) {
177 if (strpos($key, 'email') !== FALSE) {
178 $this->assertStringContainsString("(On Hold)", (string) $value);
184 * Test the civicrm_prevnext_cache entry if it correctly stores the search query result
186 public function testPrevNextCache() {
187 $contactID = $this->individualCreate(['email' => 'mickey@mouseville.com']);
189 'description' => 'Normal default behaviour',
190 'class' => 'CRM_Contact_Selector',
192 'form_values' => ['email' => 'mickey@mouseville.com'],
194 'return_properties' => NULL,
195 'context' => 'advanced',
196 'action' => CRM_Core_Action
::ADVANCED
,
197 'includeContactIds' => NULL,
198 'searchDescendentGroups' => FALSE,
199 'expected_query' => [
202 2 => "WHERE ( civicrm_email.email LIKE '%mickey@mouseville.com%' ) AND (contact_a.is_deleted = 0)",
205 $params = CRM_Contact_BAO_Query
::convertFormValues($dataSet['form_values'], 0, FALSE, NULL, []);
207 // create CRM_Contact_Selector instance and set desired query params
208 $selector = new CRM_Contact_Selector(
210 $dataSet['form_values'],
212 $dataSet['return_properties'],
214 $dataSet['includeContactIds'],
215 $dataSet['searchDescendentGroups'],
219 $key = substr(sha1(rand()), 0, 7);
220 $selector->setKey($key);
222 // fetch row and check the result
223 $rows = $selector->getRows(CRM_Core_Action
::VIEW
, 0, 1, NULL);
224 $this->assertEquals(1, count($rows));
225 $this->assertEquals($contactID, key($rows));
227 // build cache key and use to it to fetch prev-next cache record
228 $cacheKey = 'civicrm search ' . $key;
229 $contacts = CRM_Utils_SQL_Select
::from('civicrm_prevnext_cache')
230 ->select(['entity_id1', 'cachekey'])
231 ->where("cachekey = @key")
232 ->param('key', $cacheKey)
235 $this->assertEquals(1, count($contacts));
236 // check the prevNext record matches
238 'entity_id1' => $contactID,
239 'cachekey' => $cacheKey,
241 $this->checkArrayEquals($contacts[0], $expectedEntry);
245 * Data sets for testing.
247 public function querySets() {
251 'description' => 'Empty group test',
252 'class' => 'CRM_Contact_Selector',
254 'form_values' => [['contact_type', '=', 'Individual', 1, 0], ['group', 'IS NULL', '', 1, 0]],
256 'return_properties' => NULL,
257 'context' => 'builder',
258 'action' => CRM_Core_Action
::NONE
,
259 'includeContactIds' => NULL,
260 'searchDescendentGroups' => FALSE,
261 'expected_query' => [],
266 'description' => 'Tag Equals Test',
267 'class' => 'CRM_Contact_Selector',
269 'form_values' => [['contact_type', '=', 'Individual', 1, 0], ['tag', '=', '1', 1, 0]],
271 'return_properties' => NULL,
272 'context' => 'builder',
273 'action' => CRM_Core_Action
::NONE
,
274 'includeContactIds' => NULL,
275 'searchDescendentGroups' => FALSE,
276 'expected_query' => [],
277 'where_contains' => 'tag_id IN ( 1,@tagid )',
282 'description' => 'Normal default behaviour',
283 'class' => 'CRM_Contact_Selector',
285 'form_values' => ['email' => 'mickey@mouseville.com'],
287 'return_properties' => NULL,
288 'context' => 'advanced',
289 'action' => CRM_Core_Action
::ADVANCED
,
290 'includeContactIds' => NULL,
291 'searchDescendentGroups' => FALSE,
292 'expected_query' => [
295 2 => "WHERE ( civicrm_email.email LIKE '%mickey@mouseville.com%' ) AND ( 1 ) AND (contact_a.is_deleted = 0)",
301 'description' => 'Normal default + user added wildcard',
302 'class' => 'CRM_Contact_Selector',
304 'form_values' => ['email' => '%mickey@mouseville.com', 'sort_name' => 'Mouse'],
306 'return_properties' => NULL,
307 'context' => 'advanced',
308 'action' => CRM_Core_Action
::ADVANCED
,
309 'includeContactIds' => NULL,
310 'searchDescendentGroups' => FALSE,
311 'expected_query' => [
314 2 => "WHERE ( civicrm_email.email LIKE '%mickey@mouseville.com%' AND ( ( ( contact_a.sort_name LIKE '%Mouse%' ) OR ( civicrm_email.email LIKE '%Mouse%' ) ) ) ) AND ( 1 ) AND (contact_a.is_deleted = 0)",
320 'description' => 'Site set to not pre-pend wildcard',
321 'class' => 'CRM_Contact_Selector',
322 'settings' => [['name' => 'includeWildCardInName', 'value' => FALSE]],
323 'form_values' => ['email' => 'mickey@mouseville.com', 'sort_name' => 'Mouse'],
325 'return_properties' => NULL,
326 'context' => 'advanced',
327 'action' => CRM_Core_Action
::ADVANCED
,
328 'includeContactIds' => NULL,
329 'searchDescendentGroups' => FALSE,
330 'expected_query' => [
333 2 => "WHERE ( civicrm_email.email LIKE 'mickey@mouseville.com%' AND ( ( ( contact_a.sort_name LIKE 'Mouse%' ) OR ( civicrm_email.email LIKE 'Mouse%' ) ) ) ) AND ( 1 ) AND (contact_a.is_deleted = 0)",
339 'description' => 'Site set to not pre-pend wildcard and check that trash value is respected',
340 'class' => 'CRM_Contact_Selector',
341 'settings' => [['name' => 'includeWildCardInName', 'value' => FALSE]],
342 'form_values' => ['email' => 'mickey@mouseville.com', 'sort_name' => 'Mouse', 'deleted_contacts' => 1],
344 'return_properties' => NULL,
345 'context' => 'advanced',
346 'action' => CRM_Core_Action
::ADVANCED
,
347 'includeContactIds' => NULL,
348 'searchDescendentGroups' => FALSE,
349 'expected_query' => [
352 2 => "WHERE ( civicrm_email.email LIKE 'mickey@mouseville.com%' AND ( ( ( contact_a.sort_name LIKE 'Mouse%' ) OR ( civicrm_email.email LIKE 'Mouse%' ) ) ) ) AND ( 1 ) AND (contact_a.is_deleted)",
358 'description' => 'Ensure that the Join to the acl contact cache is correct and that if we are searching in deleted contacts appropriate where clause is added',
359 'class' => 'CRM_Contact_Selector',
360 'settings' => [['name' => 'includeWildCardInName', 'value' => FALSE]],
361 'form_values' => ['email' => 'mickey@mouseville.com', 'sort_name' => 'Mouse', 'deleted_contacts' => 1],
363 'return_properties' => NULL,
364 'context' => 'advanced',
365 'action' => CRM_Core_Action
::ADVANCED
,
366 'includeContactIds' => NULL,
367 'searchDescendentGroups' => FALSE,
368 'limitedPermissions' => TRUE,
369 'expected_query' => [
371 1 => 'FROM civicrm_contact contact_a LEFT JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 ) LEFT JOIN civicrm_country ON ( civicrm_address.country_id = civicrm_country.id ) LEFT JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) LEFT JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) LEFT JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) LEFT JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id INNER JOIN civicrm_acl_contact_cache aclContactCache ON contact_a.id = aclContactCache.contact_id',
372 2 => "WHERE ( civicrm_email.email LIKE 'mickey@mouseville.com%' AND ( ( ( contact_a.sort_name LIKE 'Mouse%' ) OR ( civicrm_email.email LIKE 'Mouse%' ) ) ) ) AND aclContactCache.user_id = 0 AND (contact_a.is_deleted)",
378 'description' => 'Ensure that the Join to the acl contact cache is correct and that if we are not searching in the trash trashed contacts are not returned',
379 'class' => 'CRM_Contact_Selector',
380 'settings' => [['name' => 'includeWildCardInName', 'value' => FALSE]],
381 'form_values' => ['email' => 'mickey@mouseville.com', 'sort_name' => 'Mouse'],
383 'return_properties' => NULL,
384 'context' => 'advanced',
385 'action' => CRM_Core_Action
::ADVANCED
,
386 'includeContactIds' => NULL,
387 'searchDescendentGroups' => FALSE,
388 'limitedPermissions' => TRUE,
389 'expected_query' => [
391 1 => 'FROM civicrm_contact contact_a LEFT JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 ) LEFT JOIN civicrm_country ON ( civicrm_address.country_id = civicrm_country.id ) LEFT JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) LEFT JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) LEFT JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) LEFT JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id INNER JOIN civicrm_acl_contact_cache aclContactCache ON contact_a.id = aclContactCache.contact_id',
392 2 => "WHERE ( civicrm_email.email LIKE 'mickey@mouseville.com%' AND ( ( ( contact_a.sort_name LIKE 'Mouse%' ) OR ( civicrm_email.email LIKE 'Mouse%' ) ) ) ) AND aclContactCache.user_id = 0 AND (contact_a.is_deleted = 0)",
398 'description' => 'Use of quotes for exact string',
399 'use_case_comments' => 'This is something that was in the code but seemingly not working. No UI info on it though!',
400 'class' => 'CRM_Contact_Selector',
401 'settings' => [['name' => 'includeWildCardInName', 'value' => FALSE]],
402 'form_values' => ['email' => '"mickey@mouseville.com"', 'sort_name' => 'Mouse'],
404 'return_properties' => NULL,
405 'context' => 'advanced',
406 'action' => CRM_Core_Action
::ADVANCED
,
407 'includeContactIds' => NULL,
408 'searchDescendentGroups' => FALSE,
409 'expected_query' => [
412 2 => "WHERE ( civicrm_email.email = 'mickey@mouseville.com' AND ( ( ( contact_a.sort_name LIKE 'Mouse%' ) OR ( civicrm_email.email LIKE 'Mouse%' ) ) ) ) AND ( 1 ) AND (contact_a.is_deleted = 0)",
418 'description' => 'Normal search builder behaviour',
419 'class' => 'CRM_Contact_Selector',
421 'form_values' => ['contact_type' => 'Individual', 'country' => ['IS NOT NULL' => 1]],
423 'return_properties' => [
425 'contact_sub_type' => 1,
428 'context' => 'builder',
429 'action' => CRM_Core_Action
::NONE
,
430 'includeContactIds' => NULL,
431 'searchDescendentGroups' => FALSE,
432 'expected_query' => [
433 0 => 'SELECT contact_a.id as contact_id, contact_a.contact_type as `contact_type`, contact_a.contact_sub_type as `contact_sub_type`, contact_a.sort_name as `sort_name`, civicrm_address.id as address_id, civicrm_address.country_id as country_id',
434 1 => ' FROM civicrm_contact contact_a LEFT JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )',
435 2 => 'WHERE ( contact_a.contact_type IN ("Individual") AND civicrm_address.country_id IS NOT NULL ) AND ( 1 ) AND (contact_a.is_deleted = 0)',
441 'description' => 'Search builder behaviour for Activity',
442 'class' => 'CRM_Contact_Selector',
444 'form_values' => ['source_contact_id' => ['IS NOT NULL' => 1]],
446 'return_properties' => [
447 'source_contact_id' => 1,
449 'context' => 'builder',
450 'action' => CRM_Core_Action
::NONE
,
451 'includeContactIds' => NULL,
452 'searchDescendentGroups' => FALSE,
453 'expected_query' => [
454 0 => 'SELECT contact_a.id as contact_id, source_contact.id as source_contact_id',
455 2 => 'WHERE ( source_contact.id IS NOT NULL ) AND ( 1 ) AND (contact_a.is_deleted = 0)',
461 'description' => 'Test display relationships',
462 'class' => 'CRM_Contact_Selector',
464 'form_values' => ['display_relationship_type' => '1_b_a'],
465 'return_properties' => NULL,
467 'context' => 'advanced',
468 'action' => CRM_Core_Action
::NONE
,
469 'includeContactIds' => NULL,
470 'searchDescendentGroups' => FALSE,
471 'expected_query' => [
472 0 => 'SELECT contact_a.id as contact_id, contact_a.contact_type as `contact_type`, contact_a.contact_sub_type as `contact_sub_type`, contact_a.sort_name as `sort_name`, contact_a.display_name as `display_name`, contact_a.do_not_email as `do_not_email`, contact_a.do_not_phone as `do_not_phone`, contact_a.do_not_mail as `do_not_mail`, contact_a.do_not_sms as `do_not_sms`, contact_a.do_not_trade as `do_not_trade`, contact_a.is_opt_out as `is_opt_out`, contact_a.legal_identifier as `legal_identifier`, contact_a.external_identifier as `external_identifier`, contact_a.nick_name as `nick_name`, contact_a.legal_name as `legal_name`, contact_a.image_URL as `image_URL`, contact_a.preferred_communication_method as `preferred_communication_method`, contact_a.preferred_language as `preferred_language`, contact_a.preferred_mail_format as `preferred_mail_format`, contact_a.first_name as `first_name`, contact_a.middle_name as `middle_name`, contact_a.last_name as `last_name`, contact_a.prefix_id as `prefix_id`, contact_a.suffix_id as `suffix_id`, contact_a.formal_title as `formal_title`, contact_a.communication_style_id as `communication_style_id`, contact_a.job_title as `job_title`, contact_a.gender_id as `gender_id`, contact_a.birth_date as `birth_date`, contact_a.is_deceased as `is_deceased`, contact_a.deceased_date as `deceased_date`, contact_a.household_name as `household_name`, IF ( contact_a.contact_type = \'Individual\', NULL, contact_a.organization_name ) as organization_name, contact_a.sic_code as `sic_code`, contact_a.is_deleted as `contact_is_deleted`, IF ( contact_a.contact_type = \'Individual\', contact_a.organization_name, NULL ) as current_employer, civicrm_address.id as address_id, civicrm_address.street_address as `street_address`, civicrm_address.supplemental_address_1 as `supplemental_address_1`, civicrm_address.supplemental_address_2 as `supplemental_address_2`, civicrm_address.supplemental_address_3 as `supplemental_address_3`, civicrm_address.city as `city`, civicrm_address.postal_code_suffix as `postal_code_suffix`, civicrm_address.postal_code as `postal_code`, civicrm_address.geo_code_1 as `geo_code_1`, civicrm_address.geo_code_2 as `geo_code_2`, civicrm_address.state_province_id as state_province_id, civicrm_address.country_id as country_id, civicrm_phone.id as phone_id, civicrm_phone.phone_type_id as phone_type_id, civicrm_phone.phone as `phone`, civicrm_email.id as email_id, civicrm_email.email as `email`, civicrm_email.on_hold as `on_hold`, civicrm_im.id as im_id, civicrm_im.provider_id as provider_id, civicrm_im.name as `im`, civicrm_worldregion.id as worldregion_id, civicrm_worldregion.name as `world_region`',
473 2 => 'WHERE 1 AND displayRelType.relationship_type_id = 1
474 AND displayRelType.is_active = 1
475 AND ( 1 ) AND (contact_a.is_deleted = 0)',
483 * Test the contact ID query does not fail on country search.
485 public function testContactIDQuery() {
496 $searchOBJ = new CRM_Contact_Selector(NULL);
497 $searchOBJ->contactIDQuery($params, '1_u');
501 * Test the Search Builder using Non ASCII location type for email filter
503 public function testSelectorQueryOnNonASCIIlocationType() {
504 $contactID = $this->individualCreate();
505 $locationTypeID = $this->locationTypeCreate([
506 'name' => 'Non ASCII Location Type',
507 'display_name' => 'Дом Location type',
508 'vcard_name' => 'Non ASCII Location Type',
511 $this->callAPISuccess('Email', 'create', [
512 'contact_id' => $contactID,
513 'location_type_id' => $locationTypeID,
514 'email' => 'test@test.com',
517 $selector = new CRM_Contact_Selector(
518 'CRM_Contact_Selector',
519 ['email' => ['IS NOT NULL' => 1]],
522 0 => 'email-' . $locationTypeID,
531 'contact_sub_type' => 1,
534 'Non ASCII Location Type' => [
535 'location_type' => $locationTypeID,
540 CRM_Core_Action
::NONE
,
546 $sql = $selector->getQueryObject()->query();
549 0 => "SELECT contact_a.id as contact_id, contact_a.contact_type as `contact_type`, contact_a.contact_sub_type as `contact_sub_type`, contact_a.sort_name as `sort_name`, `Non_ASCII_Location_Type-location_type`.id as `Non_ASCII_Location_Type-location_type_id`, `Non_ASCII_Location_Type-location_type`.name as `Non_ASCII_Location_Type-location_type`, `Non_ASCII_Location_Type-address`.id as `Non_ASCII_Location_Type-address_id`, `Non_ASCII_Location_Type-email`.id as `Non_ASCII_Location_Type-email_id`, `Non_ASCII_Location_Type-email`.email as `Non_ASCII_Location_Type-email`",
550 // @TODO these FROM clause doesn't matches due to extra spaces or special character
551 2 => "WHERE ( ( `Non_ASCII_Location_Type-email`.email IS NOT NULL ) ) AND ( 1 ) AND (contact_a.is_deleted = 0)",
553 foreach ($expectedQuery as $index => $queryString) {
554 $this->assertEquals($this->strWrangle($queryString), $this->strWrangle($sql[$index]));
557 $rows = $selector->getRows(CRM_Core_Action
::VIEW
, 0, 1, NULL);
558 $this->assertEquals(1, count($rows));
559 $this->assertEquals($contactID, key($rows));
560 $this->assertEquals('test@test.com', $rows[$contactID]['Non_ASCII_Location_Type-email']);
564 * Test the value use in where clause if it's case sensitive or not against each MySQL operators
566 public function testWhereClauseByOperator() {
567 $contactID = $this->individualCreate(['first_name' => 'Adam']);
573 'RLIKE' => '^A[a-z]{3}$',
574 'IN' => ['IN' => ['Adam']],
576 $filtersByWhereClause = [
578 'IS NOT NULL' => '( contact_a.first_name IS NOT NULL )',
579 // case sensitive check
580 '=' => "( contact_a.first_name = 'Adam' )",
581 // case insensitive check
582 'LIKE' => "( contact_a.first_name LIKE '%Ad%' )",
583 // case sensitive check
584 'RLIKE' => "( CAST(contact_a.first_name AS BINARY) RLIKE BINARY '^A[a-z]{3}$' )",
585 // case sensitive check
586 'IN' => '( contact_a.first_name IN ("Adam") )',
588 foreach ($filters as $op => $filter) {
589 $selector = new CRM_Contact_Selector(
590 'CRM_Contact_Selector',
591 ['first_name' => [$op => $filter]],
602 CRM_Core_Action
::NONE
,
608 $sql = $selector->getQueryObject()->query();
609 $this->assertEquals(TRUE, strpos($sql[2], $filtersByWhereClause[$op]));
611 $rows = $selector->getRows(CRM_Core_Action
::VIEW
, 0, 1, NULL);
612 $this->assertEquals(1, count($rows));
613 $this->assertEquals($contactID, key($rows));
618 * Test if custom table is added in from clause when
619 * search results are ordered by a custom field.
621 public function testSelectorQueryOrderByCustomField() {
622 //Search for any params.
633 //Create a test custom group and field.
634 $customGroup = $this->callAPISuccess('CustomGroup', 'create', [
635 'title' => "test custom group",
636 'extends' => "Individual",
638 $cgTableName = $customGroup['values'][$customGroup['id']]['table_name'];
639 $customField = $this->callAPISuccess('CustomField', 'create', [
640 'custom_group_id' => $customGroup['id'],
641 'label' => "test field",
642 'html_type' => "Text",
644 $customFieldId = $customField['id'];
646 //Sort by the custom field created above.
649 'name' => 'test field',
650 'sort' => "custom_{$customFieldId}",
653 $sort = new CRM_Utils_Sort($sortParams, '1_d');
655 //Form a query to order by a custom field.
656 $query = new CRM_Contact_BAO_Query($params,
657 CRM_Contact_BAO_Query
::NO_RETURN_PROPERTIES
,
658 NULL, FALSE, FALSE, 1,
659 FALSE, TRUE, TRUE, NULL,
662 $query->searchQuery(0, 0, $sort,
666 //Check if custom table is included in $query->_tables.
667 $this->assertTrue(array_key_exists($cgTableName, $query->_tables
));
668 //Assert if from clause joins the custom table.
669 $this->assertTrue(strpos($query->_fromClause
, $cgTableName) !== FALSE);
670 $this->callAPISuccess('CustomField', 'delete', ['id' => $customField['id']]);
671 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $customGroup['id']]);
675 * Check where clause of a date custom field when 'IS NOT EMPTY' operator is used
677 public function testCustomDateField() {
678 $contactID = $this->individualCreate();
679 //Create a test custom group and field.
680 $customGroup = $this->callAPISuccess('CustomGroup', 'create', [
681 'title' => "test custom group",
682 'extends' => "Individual",
684 $customTableName = $this->callAPISuccess('CustomGroup', 'getValue', ['id' => $customGroup['id'], 'return' => 'table_name']);
685 $customGroupTableName = $customGroup['values'][$customGroup['id']]['table_name'];
687 $createdField = $this->callAPISuccess('customField', 'create', [
688 'data_type' => 'Date',
689 'html_type' => 'Select Date',
690 'date_format' => 'd M yy',
692 'label' => 'test field',
693 'custom_group_id' => $customGroup['id'],
695 $customFieldColumnName = $createdField['values'][$createdField['id']]['column_name'];
697 $this->callAPISuccess('Contact', 'create', [
699 'custom_' . $createdField['id'] => date('YmdHis'),
702 $selector = new CRM_Contact_Selector(
703 'CRM_Contact_Selector',
704 ['custom_' . $createdField['id'] => ['IS NOT EMPTY' => 1]],
707 0 => 'custom_' . $createdField['id'],
715 CRM_Core_Action
::NONE
,
721 $whereClause = $selector->getQueryObject()->query()[2];
722 $expectedClause = sprintf("( %s.%s IS NOT NULL )", $customGroupTableName, $customFieldColumnName);
723 // test the presence of expected date clause
724 $this->assertEquals(TRUE, strpos($whereClause, $expectedClause));
726 $rows = $selector->getRows(CRM_Core_Action
::VIEW
, 0, 1, NULL);
727 $this->assertEquals(1, count($rows));
731 * Get the default select string since this is generally consistent.
733 public function getDefaultSelectString() {
734 return 'SELECT contact_a.id as contact_id, contact_a.contact_type as `contact_type`, contact_a.contact_sub_type as `contact_sub_type`, contact_a.sort_name as `sort_name`,'
735 . ' contact_a.display_name as `display_name`, contact_a.do_not_email as `do_not_email`, contact_a.do_not_phone as `do_not_phone`, contact_a.do_not_mail as `do_not_mail`,'
736 . ' contact_a.do_not_sms as `do_not_sms`, contact_a.do_not_trade as `do_not_trade`, contact_a.is_opt_out as `is_opt_out`, contact_a.legal_identifier as `legal_identifier`,'
737 . ' contact_a.external_identifier as `external_identifier`, contact_a.nick_name as `nick_name`, contact_a.legal_name as `legal_name`, contact_a.image_URL as `image_URL`,'
738 . ' contact_a.preferred_communication_method as `preferred_communication_method`, contact_a.preferred_language as `preferred_language`,'
739 . ' contact_a.preferred_mail_format as `preferred_mail_format`, contact_a.first_name as `first_name`, contact_a.middle_name as `middle_name`, contact_a.last_name as `last_name`,'
740 . ' contact_a.prefix_id as `prefix_id`, contact_a.suffix_id as `suffix_id`, contact_a.formal_title as `formal_title`, contact_a.communication_style_id as `communication_style_id`,'
741 . ' contact_a.job_title as `job_title`, contact_a.gender_id as `gender_id`, contact_a.birth_date as `birth_date`, contact_a.is_deceased as `is_deceased`,'
742 . ' contact_a.deceased_date as `deceased_date`, contact_a.household_name as `household_name`,'
743 . ' IF ( contact_a.contact_type = \'Individual\', NULL, contact_a.organization_name ) as organization_name, contact_a.sic_code as `sic_code`, contact_a.is_deleted as `contact_is_deleted`,'
744 . ' IF ( contact_a.contact_type = \'Individual\', contact_a.organization_name, NULL ) as current_employer, civicrm_address.id as address_id,'
745 . ' civicrm_address.street_address as `street_address`, civicrm_address.supplemental_address_1 as `supplemental_address_1`, '
746 . 'civicrm_address.supplemental_address_2 as `supplemental_address_2`, civicrm_address.supplemental_address_3 as `supplemental_address_3`, civicrm_address.city as `city`, civicrm_address.postal_code_suffix as `postal_code_suffix`, '
747 . 'civicrm_address.postal_code as `postal_code`, civicrm_address.geo_code_1 as `geo_code_1`, civicrm_address.geo_code_2 as `geo_code_2`, '
748 . 'civicrm_address.state_province_id as state_province_id, civicrm_address.country_id as country_id, civicrm_phone.id as phone_id, civicrm_phone.phone_type_id as phone_type_id, '
749 . 'civicrm_phone.phone as `phone`, civicrm_email.id as email_id, civicrm_email.email as `email`, civicrm_email.on_hold as `on_hold`, civicrm_im.id as im_id, '
750 . 'civicrm_im.provider_id as provider_id, civicrm_im.name as `im`, civicrm_worldregion.id as worldregion_id, civicrm_worldregion.name as `world_region`';
754 * Get the default from string since this is generally consistent.
756 public function getDefaultFromString() {
757 return ' FROM civicrm_contact contact_a LEFT JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )'
758 . ' LEFT JOIN civicrm_country ON ( civicrm_address.country_id = civicrm_country.id ) '
759 . ' LEFT JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1)'
760 . ' LEFT JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1)'
761 . ' LEFT JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) '
762 . 'LEFT JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ';
766 * Strangle strings into a more matchable format.
768 * @param string $string
772 public function strWrangle($string) {
773 return trim(str_replace(' ', ' ', $string));
777 * Swap out default parts of the query for the actual string.
779 * Note that it seems to make more sense to resolve this earlier & pass it in from a clean code point of
780 * view, but the output on fail includes long sql statements that are of low relevance then.
782 * @param array $expectedQuery
784 public function wrangleDefaultClauses(&$expectedQuery) {
785 if (CRM_Utils_Array
::value(0, $expectedQuery) == 'default') {
786 $expectedQuery[0] = $this->getDefaultSelectString();
788 if (CRM_Utils_Array
::value(1, $expectedQuery) == 'default') {
789 $expectedQuery[1] = $this->getDefaultFromString();