REF - Cleanup array key checking to use array_key_exists
[civicrm-core.git] / tests / phpunit / CRM / Contact / SelectorTest.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * Include parent class definition
14 */
15
16 /**
17 * Test contact custom search functions
18 *
19 * @package CiviCRM
20 * @group headless
21 */
22 class CRM_Contact_SelectorTest extends CiviUnitTestCase {
23
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
32 * @throws \Exception
33 */
34 public function testSelectorQuery($dataSet) {
35 $tag = $this->callAPISuccess('Tag', 'create', [
36 'name' => 'Test Tag Name' . uniqid(),
37 'parent_id' => 1,
38 ]);
39 if (!empty($dataSet['limitedPermissions'])) {
40 CRM_Core_Config::singleton()->userPermissionClass->permissions = [
41 'access CiviCRM',
42 'access deleted contacts',
43 ];
44 }
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']]);
49 }
50 $selector = new CRM_Contact_Selector(
51 $dataSet['class'],
52 $dataSet['form_values'],
53 $params,
54 $dataSet['return_properties'],
55 $dataSet['action'],
56 $dataSet['includeContactIds'],
57 $dataSet['searchDescendentGroups'],
58 $dataSet['context']
59 );
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]));
67 }
68 if (!empty($dataSet['where_contains'])) {
69 $this->assertStringContainsString($this->strWrangle(str_replace('@tagid', $tag['id'], $dataSet['where_contains'])), $this->strWrangle($sql[2]));
70 }
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',
77 'subject' => 'Test',
78 'source_contact_id' => $contactID,
79 ]);
80 $rows = CRM_Core_DAO::executeQuery(implode(' ', $sql))->fetchAll();
81 $this->assertCount(1, $rows);
82 $this->assertEquals($contactID, $rows[0]['source_contact_id']);
83 }
84 else {
85 $this->callAPISuccess('EntityTag', 'create', [
86 'entity_id' => $contactID,
87 'tag_id' => $tag['id'],
88 'entity_table' => 'civicrm_contact',
89 ]);
90 $this->callAPISuccess('Address', 'create', [
91 'contact_id' => $contactID,
92 'location_type_id' => 'Home',
93 'is_primary' => 1,
94 'country_id' => 'IN',
95 ]);
96 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 50, '');
97 $this->assertEquals(1, count($rows));
98
99 CRM_Core_DAO::reenableFullGroupByMode();
100 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 50, '');
101
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));
106
107 CRM_Core_DAO::reenableFullGroupByMode();
108 $selector->getQueryObject()->getCachedContacts([$contactID], FALSE);
109 }
110 }
111 if (!empty($dataSet['limitedPermissions'])) {
112 $this->cleanUpAfterACLs();
113 }
114 $this->callAPISuccess('Tag', 'delete', ['id' => $tag['id']]);
115 }
116
117 /**
118 * Test advanced search results by uf_group_id.
119 */
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' => [
127 [
128 'field_name' => 'email',
129 'visibility' => 'Public Pages and Listings',
130 'field_type' => 'Contact',
131 'label' => 'Email',
132 'in_selector' => 1,
133 ],
134 ],
135 ]);
136 $contactID = $this->individualCreate(['email' => 'mickey@mouseville.com']);
137 //Put the email on hold.
138 $email = $this->callAPISuccess('Email', 'get', [
139 'sequential' => 1,
140 'contact_id' => $contactID,
141 ]);
142 $this->callAPISuccess('Email', 'create', [
143 'id' => $email['id'],
144 'on_hold' => 1,
145 ]);
146
147 $dataSet = [
148 'description' => 'Normal default behaviour',
149 'class' => 'CRM_Contact_Selector',
150 'settings' => [],
151 'form_values' => ['email' => 'mickey@mouseville.com', 'uf_group_id' => $ufGroup['id']],
152 'params' => [],
153 'return_properties' => NULL,
154 'context' => 'advanced',
155 'action' => CRM_Core_Action::ADVANCED,
156 'includeContactIds' => NULL,
157 'searchDescendentGroups' => FALSE,
158 ];
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(
162 $dataSet['class'],
163 $dataSet['form_values'],
164 $params,
165 $dataSet['return_properties'],
166 $dataSet['action'],
167 $dataSet['includeContactIds'],
168 $dataSet['searchDescendentGroups'],
169 $dataSet['context']
170 );
171 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 50, '');
172 $this->assertEquals(1, count($rows));
173 $this->assertEquals($contactID, key($rows));
174
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);
179 }
180 }
181 }
182
183 /**
184 * Test the civicrm_prevnext_cache entry if it correctly stores the search query result
185 */
186 public function testPrevNextCache() {
187 $contactID = $this->individualCreate(['email' => 'mickey@mouseville.com']);
188 $dataSet = [
189 'description' => 'Normal default behaviour',
190 'class' => 'CRM_Contact_Selector',
191 'settings' => [],
192 'form_values' => ['email' => 'mickey@mouseville.com'],
193 'params' => [],
194 'return_properties' => NULL,
195 'context' => 'advanced',
196 'action' => CRM_Core_Action::ADVANCED,
197 'includeContactIds' => NULL,
198 'searchDescendentGroups' => FALSE,
199 'expected_query' => [
200 0 => 'default',
201 1 => 'default',
202 2 => "WHERE ( civicrm_email.email LIKE '%mickey@mouseville.com%' ) AND (contact_a.is_deleted = 0)",
203 ],
204 ];
205 $params = CRM_Contact_BAO_Query::convertFormValues($dataSet['form_values'], 0, FALSE, NULL, []);
206
207 // create CRM_Contact_Selector instance and set desired query params
208 $selector = new CRM_Contact_Selector(
209 $dataSet['class'],
210 $dataSet['form_values'],
211 $params,
212 $dataSet['return_properties'],
213 $dataSet['action'],
214 $dataSet['includeContactIds'],
215 $dataSet['searchDescendentGroups'],
216 $dataSet['context']
217 );
218 // set cache key
219 $key = substr(sha1(rand()), 0, 7);
220 $selector->setKey($key);
221
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));
226
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)
233 ->execute()
234 ->fetchAll();
235 $this->assertEquals(1, count($contacts));
236 // check the prevNext record matches
237 $expectedEntry = [
238 'entity_id1' => $contactID,
239 'cachekey' => $cacheKey,
240 ];
241 $this->checkArrayEquals($contacts[0], $expectedEntry);
242 }
243
244 /**
245 * Data sets for testing.
246 */
247 public function querySets() {
248 return [
249 [
250 [
251 'description' => 'Empty group test',
252 'class' => 'CRM_Contact_Selector',
253 'settings' => [],
254 'form_values' => [['contact_type', '=', 'Individual', 1, 0], ['group', 'IS NULL', '', 1, 0]],
255 'params' => [],
256 'return_properties' => NULL,
257 'context' => 'builder',
258 'action' => CRM_Core_Action::NONE,
259 'includeContactIds' => NULL,
260 'searchDescendentGroups' => FALSE,
261 'expected_query' => [],
262 ],
263 ],
264 [
265 [
266 'description' => 'Tag Equals Test',
267 'class' => 'CRM_Contact_Selector',
268 'settings' => [],
269 'form_values' => [['contact_type', '=', 'Individual', 1, 0], ['tag', '=', '1', 1, 0]],
270 'params' => [],
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 )',
278 ],
279 ],
280 [
281 [
282 'description' => 'Normal default behaviour',
283 'class' => 'CRM_Contact_Selector',
284 'settings' => [],
285 'form_values' => ['email' => 'mickey@mouseville.com'],
286 'params' => [],
287 'return_properties' => NULL,
288 'context' => 'advanced',
289 'action' => CRM_Core_Action::ADVANCED,
290 'includeContactIds' => NULL,
291 'searchDescendentGroups' => FALSE,
292 'expected_query' => [
293 0 => 'default',
294 1 => 'default',
295 2 => "WHERE ( civicrm_email.email LIKE '%mickey@mouseville.com%' ) AND ( 1 ) AND (contact_a.is_deleted = 0)",
296 ],
297 ],
298 ],
299 [
300 [
301 'description' => 'Normal default + user added wildcard',
302 'class' => 'CRM_Contact_Selector',
303 'settings' => [],
304 'form_values' => ['email' => '%mickey@mouseville.com', 'sort_name' => 'Mouse'],
305 'params' => [],
306 'return_properties' => NULL,
307 'context' => 'advanced',
308 'action' => CRM_Core_Action::ADVANCED,
309 'includeContactIds' => NULL,
310 'searchDescendentGroups' => FALSE,
311 'expected_query' => [
312 0 => 'default',
313 1 => 'default',
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)",
315 ],
316 ],
317 ],
318 [
319 [
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'],
324 'params' => [],
325 'return_properties' => NULL,
326 'context' => 'advanced',
327 'action' => CRM_Core_Action::ADVANCED,
328 'includeContactIds' => NULL,
329 'searchDescendentGroups' => FALSE,
330 'expected_query' => [
331 0 => 'default',
332 1 => 'default',
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)",
334 ],
335 ],
336 ],
337 [
338 [
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],
343 'params' => [],
344 'return_properties' => NULL,
345 'context' => 'advanced',
346 'action' => CRM_Core_Action::ADVANCED,
347 'includeContactIds' => NULL,
348 'searchDescendentGroups' => FALSE,
349 'expected_query' => [
350 0 => 'default',
351 1 => 'default',
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)",
353 ],
354 ],
355 ],
356 [
357 [
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],
362 'params' => [],
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' => [
370 0 => 'default',
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)",
373 ],
374 ],
375 ],
376 [
377 [
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'],
382 'params' => [],
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' => [
390 0 => 'default',
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)",
393 ],
394 ],
395 ],
396 [
397 [
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'],
403 'params' => [],
404 'return_properties' => NULL,
405 'context' => 'advanced',
406 'action' => CRM_Core_Action::ADVANCED,
407 'includeContactIds' => NULL,
408 'searchDescendentGroups' => FALSE,
409 'expected_query' => [
410 0 => 'default',
411 1 => 'default',
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)",
413 ],
414 ],
415 ],
416 [
417 [
418 'description' => 'Normal search builder behaviour',
419 'class' => 'CRM_Contact_Selector',
420 'settings' => [],
421 'form_values' => ['contact_type' => 'Individual', 'country' => ['IS NOT NULL' => 1]],
422 'params' => [],
423 'return_properties' => [
424 'contact_type' => 1,
425 'contact_sub_type' => 1,
426 'sort_name' => 1,
427 ],
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)',
436 ],
437 ],
438 ],
439 [
440 [
441 'description' => 'Search builder behaviour for Activity',
442 'class' => 'CRM_Contact_Selector',
443 'settings' => [],
444 'form_values' => ['source_contact_id' => ['IS NOT NULL' => 1]],
445 'params' => [],
446 'return_properties' => [
447 'source_contact_id' => 1,
448 ],
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)',
456 ],
457 ],
458 ],
459 [
460 [
461 'description' => 'Test display relationships',
462 'class' => 'CRM_Contact_Selector',
463 'settings' => [],
464 'form_values' => ['display_relationship_type' => '1_b_a'],
465 'return_properties' => NULL,
466 'params' => [],
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)',
476 ],
477 ],
478 ],
479 ];
480 }
481
482 /**
483 * Test the contact ID query does not fail on country search.
484 */
485 public function testContactIDQuery() {
486 $params = [
487 [
488 0 => 'country-1',
489 1 => '=',
490 2 => '1228',
491 3 => 1,
492 4 => 0,
493 ],
494 ];
495
496 $searchOBJ = new CRM_Contact_Selector(NULL);
497 $searchOBJ->contactIDQuery($params, '1_u');
498 }
499
500 /**
501 * Test the Search Builder using Non ASCII location type for email filter
502 */
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',
509 'is_active' => 1,
510 ]);
511 $this->callAPISuccess('Email', 'create', [
512 'contact_id' => $contactID,
513 'location_type_id' => $locationTypeID,
514 'email' => 'test@test.com',
515 ]);
516
517 $selector = new CRM_Contact_Selector(
518 'CRM_Contact_Selector',
519 ['email' => ['IS NOT NULL' => 1]],
520 [
521 [
522 0 => 'email-' . $locationTypeID,
523 1 => 'IS NOT NULL',
524 2 => NULL,
525 3 => 1,
526 4 => 0,
527 ],
528 ],
529 [
530 'contact_type' => 1,
531 'contact_sub_type' => 1,
532 'sort_name' => 1,
533 'location' => [
534 'Non ASCII Location Type' => [
535 'location_type' => $locationTypeID,
536 'email' => 1,
537 ],
538 ],
539 ],
540 CRM_Core_Action::NONE,
541 NULL,
542 FALSE,
543 'builder'
544 );
545
546 $sql = $selector->getQueryObject()->query();
547
548 $expectedQuery = [
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)",
552 ];
553 foreach ($expectedQuery as $index => $queryString) {
554 $this->assertEquals($this->strWrangle($queryString), $this->strWrangle($sql[$index]));
555 }
556
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']);
561 }
562
563 /**
564 * Test the value use in where clause if it's case sensitive or not against each MySQL operators
565 */
566 public function testWhereClauseByOperator() {
567 $contactID = $this->individualCreate(['first_name' => 'Adam']);
568
569 $filters = [
570 'IS NOT NULL' => 1,
571 '=' => 'Adam',
572 'LIKE' => '%Ad%',
573 'RLIKE' => '^A[a-z]{3}$',
574 'IN' => ['IN' => ['Adam']],
575 ];
576 $filtersByWhereClause = [
577 // doesn't matter
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") )',
587 ];
588 foreach ($filters as $op => $filter) {
589 $selector = new CRM_Contact_Selector(
590 'CRM_Contact_Selector',
591 ['first_name' => [$op => $filter]],
592 [
593 [
594 0 => 'first_name',
595 1 => $op,
596 2 => $filter,
597 3 => 1,
598 4 => 0,
599 ],
600 ],
601 [],
602 CRM_Core_Action::NONE,
603 NULL,
604 FALSE,
605 'builder'
606 );
607
608 $sql = $selector->getQueryObject()->query();
609 $this->assertEquals(TRUE, strpos($sql[2], $filtersByWhereClause[$op]));
610
611 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 1, NULL);
612 $this->assertEquals(1, count($rows));
613 $this->assertEquals($contactID, key($rows));
614 }
615 }
616
617 /**
618 * Test if custom table is added in from clause when
619 * search results are ordered by a custom field.
620 */
621 public function testSelectorQueryOrderByCustomField() {
622 //Search for any params.
623 $params = [
624 [
625 0 => 'country-1',
626 1 => '=',
627 2 => '1228',
628 3 => 1,
629 4 => 0,
630 ],
631 ];
632
633 //Create a test custom group and field.
634 $customGroup = $this->callAPISuccess('CustomGroup', 'create', [
635 'title' => "test custom group",
636 'extends' => "Individual",
637 ]);
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",
643 ]);
644 $customFieldId = $customField['id'];
645
646 //Sort by the custom field created above.
647 $sortParams = [
648 1 => [
649 'name' => 'test field',
650 'sort' => "custom_{$customFieldId}",
651 ],
652 ];
653 $sort = new CRM_Utils_Sort($sortParams, '1_d');
654
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,
660 'AND'
661 );
662 $query->searchQuery(0, 0, $sort,
663 FALSE, FALSE, FALSE,
664 FALSE, FALSE
665 );
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']]);
672 }
673
674 /**
675 * Check where clause of a date custom field when 'IS NOT EMPTY' operator is used
676 */
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",
683 ]);
684 $customTableName = $this->callAPISuccess('CustomGroup', 'getValue', ['id' => $customGroup['id'], 'return' => 'table_name']);
685 $customGroupTableName = $customGroup['values'][$customGroup['id']]['table_name'];
686
687 $createdField = $this->callAPISuccess('customField', 'create', [
688 'data_type' => 'Date',
689 'html_type' => 'Select Date',
690 'date_format' => 'd M yy',
691 'time_format' => 1,
692 'label' => 'test field',
693 'custom_group_id' => $customGroup['id'],
694 ]);
695 $customFieldColumnName = $createdField['values'][$createdField['id']]['column_name'];
696
697 $this->callAPISuccess('Contact', 'create', [
698 'id' => $contactID,
699 'custom_' . $createdField['id'] => date('YmdHis'),
700 ]);
701
702 $selector = new CRM_Contact_Selector(
703 'CRM_Contact_Selector',
704 ['custom_' . $createdField['id'] => ['IS NOT EMPTY' => 1]],
705 [
706 [
707 0 => 'custom_' . $createdField['id'],
708 1 => 'IS NOT NULL',
709 2 => 1,
710 3 => 1,
711 4 => 0,
712 ],
713 ],
714 [],
715 CRM_Core_Action::NONE,
716 NULL,
717 FALSE,
718 'builder'
719 );
720
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));
725
726 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 1, NULL);
727 $this->assertEquals(1, count($rows));
728 }
729
730 /**
731 * Get the default select string since this is generally consistent.
732 */
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`';
751 }
752
753 /**
754 * Get the default from string since this is generally consistent.
755 */
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 ';
763 }
764
765 /**
766 * Strangle strings into a more matchable format.
767 *
768 * @param string $string
769 *
770 * @return string
771 */
772 public function strWrangle($string) {
773 return trim(str_replace(' ', ' ', $string));
774 }
775
776 /**
777 * Swap out default parts of the query for the actual string.
778 *
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.
781 *
782 * @param array $expectedQuery
783 */
784 public function wrangleDefaultClauses(&$expectedQuery) {
785 if (CRM_Utils_Array::value(0, $expectedQuery) == 'default') {
786 $expectedQuery[0] = $this->getDefaultSelectString();
787 }
788 if (CRM_Utils_Array::value(1, $expectedQuery) == 'default') {
789 $expectedQuery[1] = $this->getDefaultFromString();
790 }
791 }
792
793 }