Merge pull request #17779 from seamuslee001/nfc_php74_flexmailer
[civicrm-core.git] / tests / phpunit / CRM / Contact / SelectorTest.php
CommitLineData
836eb043 1<?php
2/*
3 +--------------------------------------------------------------------+
7d61e75f 4 | Copyright CiviCRM LLC. All rights reserved. |
836eb043 5 | |
7d61e75f
TO
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 |
836eb043 9 +--------------------------------------------------------------------+
10 */
11
12/**
13 * Include parent class definition
14 */
836eb043 15
16/**
17 * Test contact custom search functions
18 *
19 * @package CiviCRM
acb109b7 20 * @group headless
836eb043 21 */
1d17e4fc 22class CRM_Contact_SelectorTest extends CiviUnitTestCase {
836eb043 23
836eb043 24 /**
25 * Test the query from the selector class is consistent with the dataset expectation.
26 *
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.
30 *
31 * @dataProvider querySets
e2b506f7 32 * @throws \Exception
836eb043 33 */
34 public function testSelectorQuery($dataSet) {
fb1ee468 35 $params = CRM_Contact_BAO_Query::convertFormValues($dataSet['form_values'], 0, FALSE, NULL, []);
836eb043 36 foreach ($dataSet['settings'] as $setting) {
fb1ee468 37 $this->callAPISuccess('Setting', 'create', [$setting['name'] => $setting['value']]);
836eb043 38 }
39 $selector = new CRM_Contact_Selector(
40 $dataSet['class'],
41 $dataSet['form_values'],
42 $params,
43 $dataSet['return_properties'],
44 $dataSet['action'],
45 $dataSet['includeContactIds'],
46 $dataSet['searchDescendentGroups'],
47 $dataSet['context']
48 );
49 $queryObject = $selector->getQueryObject();
def88c52 50 // Make sure there is no fail on alphabet query.
51 $selector->alphabetQuery()->fetchAll();
836eb043 52 $sql = $queryObject->query();
53 $this->wrangleDefaultClauses($dataSet['expected_query']);
54 foreach ($dataSet['expected_query'] as $index => $queryString) {
299c1530 55 $this->assertLike($this->strWrangle($queryString), $this->strWrangle($sql[$index]));
836eb043 56 }
7ccccc32 57 // Ensure that search builder return individual contact as per criteria
d1d108ee 58 if ($dataSet['context'] === 'builder') {
d567ed10 59 $contactID = $this->individualCreate(['first_name' => 'James', 'last_name' => 'Bond']);
d1d108ee 60 if ('Search builder behaviour for Activity' === $dataSet['description']) {
fd95406d 61 $this->callAPISuccess('Activity', 'create', [
62 'activity_type_id' => 'Meeting',
d1d108ee 63 'subject' => 'Test',
fd95406d 64 'source_contact_id' => $contactID,
65 ]);
66 $rows = CRM_Core_DAO::executeQuery(implode(' ', $sql))->fetchAll();
d1d108ee 67 $this->assertCount(1, $rows);
fd95406d 68 $this->assertEquals($contactID, $rows[0]['source_contact_id']);
69 }
70 else {
71 $this->callAPISuccess('Address', 'create', [
72 'contact_id' => $contactID,
d1d108ee 73 'location_type_id' => 'Home',
fd95406d 74 'is_primary' => 1,
d1d108ee 75 'country_id' => 'IN',
fd95406d 76 ]);
77 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 50, '');
78 $this->assertEquals(1, count($rows));
2365bc96 79
80 CRM_Core_DAO::reenableFullGroupByMode();
81 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 50, '');
82
fd95406d 83 $sortChar = $selector->alphabetQuery()->fetchAll();
84 // sort name is stored in '<last_name>, <first_name>' format, as per which the first character would be B of Bond
85 $this->assertEquals('B', $sortChar[0]['sort_name']);
86 $this->assertEquals($contactID, key($rows));
2365bc96 87
88 CRM_Core_DAO::reenableFullGroupByMode();
89 $selector->getQueryObject()->getCachedContacts([$contactID], FALSE);
fd95406d 90 }
7ccccc32 91 }
836eb043 92 }
93
7906396a
JP
94 /**
95 * Test advanced search results by uf_group_id.
96 */
97 public function testSearchByProfile() {
98 //Create search profile for contacts.
99 $ufGroup = $this->callAPISuccess('uf_group', 'create', [
100 'group_type' => 'Contact',
101 'name' => 'test_search_profile',
102 'title' => 'Test Search Profile',
103 'api.uf_field.create' => [
104 [
105 'field_name' => 'email',
106 'visibility' => 'Public Pages and Listings',
107 'field_type' => 'Contact',
108 'label' => 'Email',
109 'in_selector' => 1,
110 ],
111 ],
112 ]);
113 $contactID = $this->individualCreate(['email' => 'mickey@mouseville.com']);
114 //Put the email on hold.
115 $email = $this->callAPISuccess('Email', 'get', [
116 'sequential' => 1,
117 'contact_id' => $contactID,
118 ]);
119 $this->callAPISuccess('Email', 'create', [
120 'id' => $email['id'],
121 'on_hold' => 1,
122 ]);
123
124 $dataSet = [
125 'description' => 'Normal default behaviour',
126 'class' => 'CRM_Contact_Selector',
127 'settings' => [],
128 'form_values' => ['email' => 'mickey@mouseville.com', 'uf_group_id' => $ufGroup['id']],
129 'params' => [],
130 'return_properties' => NULL,
131 'context' => 'advanced',
132 'action' => CRM_Core_Action::ADVANCED,
133 'includeContactIds' => NULL,
134 'searchDescendentGroups' => FALSE,
135 ];
136 $params = CRM_Contact_BAO_Query::convertFormValues($dataSet['form_values'], 0, FALSE, NULL, []);
137 // create CRM_Contact_Selector instance and set desired query params
138 $selector = new CRM_Contact_Selector(
139 $dataSet['class'],
140 $dataSet['form_values'],
141 $params,
142 $dataSet['return_properties'],
143 $dataSet['action'],
144 $dataSet['includeContactIds'],
145 $dataSet['searchDescendentGroups'],
146 $dataSet['context']
147 );
148 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 50, '');
149 $this->assertEquals(1, count($rows));
150 $this->assertEquals($contactID, key($rows));
151
152 //Check if email column contains (On Hold) string.
153 foreach ($rows[$contactID] as $key => $value) {
154 if (strpos($key, 'email') !== FALSE) {
155 $this->assertContains("(On Hold)", (string) $value);
156 }
157 }
158 }
159
2eb3ff3e 160 /**
161 * Test the civicrm_prevnext_cache entry if it correctly stores the search query result
162 */
163 public function testPrevNextCache() {
164 $contactID = $this->individualCreate(['email' => 'mickey@mouseville.com']);
fb1ee468 165 $dataSet = [
2eb3ff3e 166 'description' => 'Normal default behaviour',
167 'class' => 'CRM_Contact_Selector',
fb1ee468 168 'settings' => [],
169 'form_values' => ['email' => 'mickey@mouseville.com'],
170 'params' => [],
2eb3ff3e 171 'return_properties' => NULL,
172 'context' => 'advanced',
173 'action' => CRM_Core_Action::ADVANCED,
174 'includeContactIds' => NULL,
175 'searchDescendentGroups' => FALSE,
fb1ee468 176 'expected_query' => [
2eb3ff3e 177 0 => 'default',
178 1 => 'default',
b3df61d8 179 2 => "WHERE ( civicrm_email.email LIKE '%mickey@mouseville.com%' ) AND ( 1 )",
fb1ee468 180 ],
181 ];
182 $params = CRM_Contact_BAO_Query::convertFormValues($dataSet['form_values'], 0, FALSE, NULL, []);
2eb3ff3e 183
184 // create CRM_Contact_Selector instance and set desired query params
185 $selector = new CRM_Contact_Selector(
186 $dataSet['class'],
187 $dataSet['form_values'],
188 $params,
189 $dataSet['return_properties'],
190 $dataSet['action'],
191 $dataSet['includeContactIds'],
192 $dataSet['searchDescendentGroups'],
193 $dataSet['context']
194 );
195 // set cache key
196 $key = substr(sha1(rand()), 0, 7);
197 $selector->setKey($key);
198
199 // fetch row and check the result
1d17e4fc 200 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 1, NULL);
2eb3ff3e 201 $this->assertEquals(1, count($rows));
202 $this->assertEquals($contactID, key($rows));
203
204 // build cache key and use to it to fetch prev-next cache record
205 $cacheKey = 'civicrm search ' . $key;
206 $contacts = CRM_Utils_SQL_Select::from('civicrm_prevnext_cache')
783b4b21
SL
207 ->select(['entity_id1', 'cachekey'])
208 ->where("cachekey = @key")
39b959db
SL
209 ->param('key', $cacheKey)
210 ->execute()
211 ->fetchAll();
2eb3ff3e 212 $this->assertEquals(1, count($contacts));
213 // check the prevNext record matches
214 $expectedEntry = [
2eb3ff3e 215 'entity_id1' => $contactID,
783b4b21 216 'cachekey' => $cacheKey,
2eb3ff3e 217 ];
218 $this->checkArrayEquals($contacts[0], $expectedEntry);
219 }
220
836eb043 221 /**
222 * Data sets for testing.
223 */
224 public function querySets() {
fb1ee468 225 return [
226 [
227 [
e2b506f7 228 'description' => 'Empty group test',
229 'class' => 'CRM_Contact_Selector',
230 'settings' => [],
231 'form_values' => [['contact_type', '=', 'Individual', 1, 0], ['group', 'IS NULL', '', 1, 0]],
232 'params' => [],
233 'return_properties' => NULL,
234 'context' => 'builder',
235 'action' => CRM_Core_Action::NONE,
236 'includeContactIds' => NULL,
237 'searchDescendentGroups' => FALSE,
673fae6c 238 'expected_query' => [],
fb1ee468 239 ],
240 ],
241 [
242 [
836eb043 243 'description' => 'Normal default behaviour',
244 'class' => 'CRM_Contact_Selector',
fb1ee468 245 'settings' => [],
246 'form_values' => ['email' => 'mickey@mouseville.com'],
247 'params' => [],
836eb043 248 'return_properties' => NULL,
249 'context' => 'advanced',
250 'action' => CRM_Core_Action::ADVANCED,
251 'includeContactIds' => NULL,
252 'searchDescendentGroups' => FALSE,
fb1ee468 253 'expected_query' => [
836eb043 254 0 => 'default',
255 1 => 'default',
b3df61d8 256 2 => "WHERE ( civicrm_email.email LIKE '%mickey@mouseville.com%' ) AND ( 1 )",
fb1ee468 257 ],
258 ],
259 ],
260 [
261 [
836eb043 262 'description' => 'Normal default + user added wildcard',
263 'class' => 'CRM_Contact_Selector',
fb1ee468 264 'settings' => [],
265 'form_values' => ['email' => '%mickey@mouseville.com', 'sort_name' => 'Mouse'],
266 'params' => [],
836eb043 267 'return_properties' => NULL,
268 'context' => 'advanced',
269 'action' => CRM_Core_Action::ADVANCED,
270 'includeContactIds' => NULL,
271 'searchDescendentGroups' => FALSE,
fb1ee468 272 'expected_query' => [
836eb043 273 0 => 'default',
274 1 => 'default',
b3df61d8 275 2 => "WHERE ( civicrm_email.email LIKE '%mickey@mouseville.com%' AND ( ( ( contact_a.sort_name LIKE '%Mouse%' ) OR ( civicrm_email.email LIKE '%Mouse%' ) ) ) ) AND ( 1 )",
fb1ee468 276 ],
277 ],
278 ],
279 [
280 [
836eb043 281 'description' => 'Site set to not pre-pend wildcard',
282 'class' => 'CRM_Contact_Selector',
fb1ee468 283 'settings' => [['name' => 'includeWildCardInName', 'value' => FALSE]],
284 'form_values' => ['email' => 'mickey@mouseville.com', 'sort_name' => 'Mouse'],
285 'params' => [],
836eb043 286 'return_properties' => NULL,
287 'context' => 'advanced',
288 'action' => CRM_Core_Action::ADVANCED,
289 'includeContactIds' => NULL,
290 'searchDescendentGroups' => FALSE,
fb1ee468 291 'expected_query' => [
836eb043 292 0 => 'default',
293 1 => 'default',
b3df61d8 294 2 => "WHERE ( civicrm_email.email LIKE 'mickey@mouseville.com%' AND ( ( ( contact_a.sort_name LIKE 'Mouse%' ) OR ( civicrm_email.email LIKE 'Mouse%' ) ) ) ) AND ( 1 )",
fb1ee468 295 ],
296 ],
297 ],
298 [
299 [
836eb043 300 'description' => 'Use of quotes for exact string',
301 'use_case_comments' => 'This is something that was in the code but seemingly not working. No UI info on it though!',
302 'class' => 'CRM_Contact_Selector',
fb1ee468 303 'settings' => [['name' => 'includeWildCardInName', 'value' => FALSE]],
304 'form_values' => ['email' => '"mickey@mouseville.com"', 'sort_name' => 'Mouse'],
305 'params' => [],
836eb043 306 'return_properties' => NULL,
307 'context' => 'advanced',
308 'action' => CRM_Core_Action::ADVANCED,
309 'includeContactIds' => NULL,
310 'searchDescendentGroups' => FALSE,
fb1ee468 311 'expected_query' => [
836eb043 312 0 => 'default',
313 1 => 'default',
b3df61d8 314 2 => "WHERE ( civicrm_email.email = 'mickey@mouseville.com' AND ( ( ( contact_a.sort_name LIKE 'Mouse%' ) OR ( civicrm_email.email LIKE 'Mouse%' ) ) ) ) AND ( 1 )",
fb1ee468 315 ],
316 ],
317 ],
318 [
319 [
7ccccc32 320 'description' => 'Normal search builder behaviour',
321 'class' => 'CRM_Contact_Selector',
fb1ee468 322 'settings' => [],
323 'form_values' => ['contact_type' => 'Individual', 'country' => ['IS NOT NULL' => 1]],
324 'params' => [],
325 'return_properties' => [
7ccccc32 326 'contact_type' => 1,
327 'contact_sub_type' => 1,
328 'sort_name' => 1,
fb1ee468 329 ],
7ccccc32 330 'context' => 'builder',
331 'action' => CRM_Core_Action::NONE,
332 'includeContactIds' => NULL,
333 'searchDescendentGroups' => FALSE,
fb1ee468 334 'expected_query' => [
a220b357 335 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',
336 1 => ' FROM civicrm_contact contact_a LEFT JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )',
b3df61d8 337 2 => 'WHERE ( contact_a.contact_type IN ("Individual") AND civicrm_address.country_id IS NOT NULL ) AND ( 1 )',
fb1ee468 338 ],
339 ],
340 ],
341 [
342 [
fd95406d 343 'description' => 'Search builder behaviour for Activity',
344 'class' => 'CRM_Contact_Selector',
fb1ee468 345 'settings' => [],
346 'form_values' => ['source_contact_id' => ['IS NOT NULL' => 1]],
347 'params' => [],
348 'return_properties' => [
fd95406d 349 'source_contact_id' => 1,
fb1ee468 350 ],
fd95406d 351 'context' => 'builder',
352 'action' => CRM_Core_Action::NONE,
353 'includeContactIds' => NULL,
354 'searchDescendentGroups' => FALSE,
fb1ee468 355 'expected_query' => [
fd95406d 356 0 => 'SELECT contact_a.id as contact_id, source_contact.id as source_contact_id',
b3df61d8 357 2 => 'WHERE ( source_contact.id IS NOT NULL ) AND ( 1 )',
fb1ee468 358 ],
359 ],
360 ],
361 [
362 [
def88c52 363 'description' => 'Test display relationships',
364 'class' => 'CRM_Contact_Selector',
365 'settings' => [],
366 'form_values' => ['display_relationship_type' => '1_b_a'],
367 'return_properties' => NULL,
368 'params' => [],
369 'context' => 'advanced',
370 'action' => CRM_Core_Action::NONE,
371 'includeContactIds' => NULL,
372 'searchDescendentGroups' => FALSE,
fb1ee468 373 'expected_query' => [
def88c52 374 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`',
375 2 => 'WHERE displayRelType.relationship_type_id = 1
376AND displayRelType.is_active = 1
b3df61d8 377AND ( 1 )',
fb1ee468 378 ],
379 ],
380 ],
381 ];
836eb043 382 }
383
ae066a2b 384 /**
385 * Test the contact ID query does not fail on country search.
386 */
387 public function testContactIDQuery() {
39b959db
SL
388 $params = [
389 [
390 0 => 'country-1',
391 1 => '=',
392 2 => '1228',
393 3 => 1,
394 4 => 0,
395 ],
396 ];
ae066a2b 397
398 $searchOBJ = new CRM_Contact_Selector(NULL);
399 $searchOBJ->contactIDQuery($params, '1_u');
400 }
401
f9ba4d01 402 /**
403 * Test the Search Builder using Non ASCII location type for email filter
404 */
405 public function testSelectorQueryOnNonASCIIlocationType() {
406 $contactID = $this->individualCreate();
407 $locationType = $this->locationTypeCreate([
408 'name' => 'Non ASCII Location Type',
409 'display_name' => 'Дом Location type',
410 'vcard_name' => 'Non ASCII Location Type',
411 'is_active' => 1,
412 ]);
413 $this->callAPISuccess('Email', 'create', [
414 'contact_id' => $contactID,
415 'location_type_id' => $locationType->id,
416 'email' => 'test@test.com',
417 ]);
418
419 $selector = new CRM_Contact_Selector(
420 'CRM_Contact_Selector',
421 ['email' => ['IS NOT NULL' => 1]],
39b959db
SL
422 [
423 [
424 0 => 'email-' . $locationType->id,
425 1 => 'IS NOT NULL',
426 2 => NULL,
fb1ee468 427 3 => 1,
39b959db
SL
428 4 => 0,
429 ],
430 ],
f9ba4d01 431 [
432 'contact_type' => 1,
433 'contact_sub_type' => 1,
434 'sort_name' => 1,
435 'location' => [
436 'Non ASCII Location Type' => [
437 'location_type' => $locationType->id,
438 'email' => 1,
439 ],
440 ],
441 ],
442 CRM_Core_Action::NONE,
443 NULL,
444 FALSE,
445 'builder'
446 );
447
448 $sql = $selector->getQueryObject()->query();
449
450 $expectedQuery = [
451 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-email`.id as `Non_ASCII_Location_Type-email_id`, `Non_ASCII_Location_Type-email`.email as `Non_ASCII_Location_Type-email`",
452 // @TODO these FROM clause doesn't matches due to extra spaces or special character
b3df61d8 453 2 => "WHERE ( ( `Non_ASCII_Location_Type-email`.email IS NOT NULL ) ) AND ( 1 )",
f9ba4d01 454 ];
455 foreach ($expectedQuery as $index => $queryString) {
456 $this->assertEquals($this->strWrangle($queryString), $this->strWrangle($sql[$index]));
457 }
458
1d17e4fc 459 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 1, NULL);
f9ba4d01 460 $this->assertEquals(1, count($rows));
461 $this->assertEquals($contactID, key($rows));
462 $this->assertEquals('test@test.com', $rows[$contactID]['Non_ASCII_Location_Type-email']);
463 }
464
a0475688 465 /**
466 * Test the value use in where clause if it's case sensitive or not against each MySQL operators
467 */
468 public function testWhereClauseByOperator() {
469 $contactID = $this->individualCreate(['first_name' => 'Adam']);
470
471 $filters = [
472 'IS NOT NULL' => 1,
473 '=' => 'Adam',
474 'LIKE' => '%Ad%',
475 'RLIKE' => '^A[a-z]{3}$',
476 'IN' => ['IN' => ['Adam']],
477 ];
478 $filtersByWhereClause = [
39b959db
SL
479 // doesn't matter
480 'IS NOT NULL' => '( contact_a.first_name IS NOT NULL )',
481 // case sensitive check
482 '=' => "( contact_a.first_name = 'Adam' )",
483 // case insensitive check
484 'LIKE' => "( contact_a.first_name LIKE '%Ad%' )",
485 // case sensitive check
486 'RLIKE' => "( contact_a.first_name RLIKE BINARY '^A[a-z]{3}$' )",
487 // case sensitive check
488 'IN' => '( contact_a.first_name IN ("Adam") )',
a0475688 489 ];
490 foreach ($filters as $op => $filter) {
491 $selector = new CRM_Contact_Selector(
492 'CRM_Contact_Selector',
493 ['first_name' => [$op => $filter]],
39b959db
SL
494 [
495 [
496 0 => 'first_name',
497 1 => $op,
498 2 => $filter,
499 3 => 1,
500 4 => 0,
501 ],
502 ],
a0475688 503 [],
504 CRM_Core_Action::NONE,
505 NULL,
506 FALSE,
507 'builder'
508 );
509
510 $sql = $selector->getQueryObject()->query();
511 $this->assertEquals(TRUE, strpos($sql[2], $filtersByWhereClause[$op]));
512
1d17e4fc 513 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 1, NULL);
a0475688 514 $this->assertEquals(1, count($rows));
515 $this->assertEquals($contactID, key($rows));
516 }
517 }
518
744050b0
JP
519 /**
520 * Test if custom table is added in from clause when
521 * search results are ordered by a custom field.
522 */
523 public function testSelectorQueryOrderByCustomField() {
524 //Search for any params.
39b959db
SL
525 $params = [
526 [
527 0 => 'country-1',
528 1 => '=',
529 2 => '1228',
530 3 => 1,
531 4 => 0,
532 ],
533 ];
744050b0
JP
534
535 //Create a test custom group and field.
fb1ee468 536 $customGroup = $this->callAPISuccess('CustomGroup', 'create', [
744050b0
JP
537 'title' => "test custom group",
538 'extends' => "Individual",
fb1ee468 539 ]);
744050b0 540 $cgTableName = $customGroup['values'][$customGroup['id']]['table_name'];
fb1ee468 541 $customField = $this->callAPISuccess('CustomField', 'create', [
744050b0
JP
542 'custom_group_id' => $customGroup['id'],
543 'label' => "test field",
544 'html_type' => "Text",
fb1ee468 545 ]);
744050b0
JP
546 $customFieldId = $customField['id'];
547
548 //Sort by the custom field created above.
fb1ee468 549 $sortParams = [
550 1 => [
744050b0
JP
551 'name' => 'test field',
552 'sort' => "custom_{$customFieldId}",
fb1ee468 553 ],
554 ];
744050b0
JP
555 $sort = new CRM_Utils_Sort($sortParams, '1_d');
556
557 //Form a query to order by a custom field.
558 $query = new CRM_Contact_BAO_Query($params,
559 CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES,
560 NULL, FALSE, FALSE, 1,
561 FALSE, TRUE, TRUE, NULL,
562 'AND'
563 );
564 $query->searchQuery(0, 0, $sort,
565 FALSE, FALSE, FALSE,
566 FALSE, FALSE
567 );
568 //Check if custom table is included in $query->_tables.
569 $this->assertTrue(in_array($cgTableName, array_keys($query->_tables)));
570 //Assert if from clause joins the custom table.
571 $this->assertTrue(strpos($query->_fromClause, $cgTableName) !== FALSE);
1d17e4fc
SL
572 $this->callAPISuccess('CustomField', 'delete', ['id' => $customField['id']]);
573 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $customGroup['id']]);
744050b0
JP
574 }
575
8ad22b15 576 /**
577 * Check where clause of a date custom field when 'IS NOT EMPTY' operator is used
578 */
579 public function testCustomDateField() {
580 $contactID = $this->individualCreate();
581 //Create a test custom group and field.
fb1ee468 582 $customGroup = $this->callAPISuccess('CustomGroup', 'create', [
8ad22b15 583 'title' => "test custom group",
584 'extends' => "Individual",
fb1ee468 585 ]);
1d17e4fc 586 $customTableName = $this->callAPISuccess('CustomGroup', 'getValue', ['id' => $customGroup['id'], 'return' => 'table_name']);
8ad22b15 587 $customGroupTableName = $customGroup['values'][$customGroup['id']]['table_name'];
588
589 $createdField = $this->callAPISuccess('customField', 'create', [
590 'data_type' => 'Date',
591 'html_type' => 'Select Date',
592 'date_format' => 'd M yy',
593 'time_format' => 1,
594 'label' => 'test field',
595 'custom_group_id' => $customGroup['id'],
596 ]);
597 $customFieldColumnName = $createdField['values'][$createdField['id']]['column_name'];
598
599 $this->callAPISuccess('Contact', 'create', [
600 'id' => $contactID,
601 'custom_' . $createdField['id'] => date('YmdHis'),
602 ]);
603
604 $selector = new CRM_Contact_Selector(
605 'CRM_Contact_Selector',
606 ['custom_' . $createdField['id'] => ['IS NOT EMPTY' => 1]],
39b9dbb3
TO
607 [
608 [
609 0 => 'custom_' . $createdField['id'],
610 1 => 'IS NOT NULL',
611 2 => 1,
612 3 => 1,
613 4 => 0,
614 ],
39b959db 615 ],
8ad22b15 616 [],
617 CRM_Core_Action::NONE,
618 NULL,
619 FALSE,
620 'builder'
621 );
622
623 $whereClause = $selector->getQueryObject()->query()[2];
624 $expectedClause = sprintf("( %s.%s IS NOT NULL )", $customGroupTableName, $customFieldColumnName);
625 // test the presence of expected date clause
626 $this->assertEquals(TRUE, strpos($whereClause, $expectedClause));
627
1d17e4fc 628 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 1, NULL);
8ad22b15 629 $this->assertEquals(1, count($rows));
630 }
631
836eb043 632 /**
633 * Get the default select string since this is generally consistent.
634 */
635 public function getDefaultSelectString() {
636 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`,'
fb1ee468 637 . ' 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`,'
638 . ' 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`,'
639 . ' 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`,'
640 . ' contact_a.preferred_communication_method as `preferred_communication_method`, contact_a.preferred_language as `preferred_language`,'
641 . ' 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`,'
642 . ' 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`,'
643 . ' 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`,'
644 . ' contact_a.deceased_date as `deceased_date`, contact_a.household_name as `household_name`,'
645 . ' 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`,'
646 . ' IF ( contact_a.contact_type = \'Individual\', contact_a.organization_name, NULL ) as current_employer, civicrm_address.id as address_id,'
647 . ' civicrm_address.street_address as `street_address`, civicrm_address.supplemental_address_1 as `supplemental_address_1`, '
648 . '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`, '
649 . '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`, '
650 . '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, '
651 . '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, '
652 . 'civicrm_im.provider_id as provider_id, civicrm_im.name as `im`, civicrm_worldregion.id as worldregion_id, civicrm_worldregion.name as `world_region`';
836eb043 653 }
654
655 /**
656 * Get the default from string since this is generally consistent.
657 */
658 public function getDefaultFromString() {
659 return ' FROM civicrm_contact contact_a LEFT JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )'
fb1ee468 660 . ' LEFT JOIN civicrm_country ON ( civicrm_address.country_id = civicrm_country.id ) '
661 . ' LEFT JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1)'
662 . ' LEFT JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1)'
663 . ' LEFT JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) '
664 . 'LEFT JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ';
836eb043 665 }
666
667 /**
668 * Strangle strings into a more matchable format.
669 *
670 * @param string $string
fb1ee468 671 *
836eb043 672 * @return string
673 */
674 public function strWrangle($string) {
def88c52 675 return trim(str_replace(' ', ' ', $string));
836eb043 676 }
677
678 /**
679 * Swap out default parts of the query for the actual string.
680 *
681 * Note that it seems to make more sense to resolve this earlier & pass it in from a clean code point of
682 * view, but the output on fail includes long sql statements that are of low relevance then.
683 *
684 * @param array $expectedQuery
685 */
686 public function wrangleDefaultClauses(&$expectedQuery) {
fd95406d 687 if (CRM_Utils_Array::value(0, $expectedQuery) == 'default') {
836eb043 688 $expectedQuery[0] = $this->getDefaultSelectString();
689 }
fd95406d 690 if (CRM_Utils_Array::value(1, $expectedQuery) == 'default') {
836eb043 691 $expectedQuery[1] = $this->getDefaultFromString();
692 }
693 }
694
695}