REF - Cleanup array key checking to use array_key_exists
[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) {
32704862
SL
35 $tag = $this->callAPISuccess('Tag', 'create', [
36 'name' => 'Test Tag Name' . uniqid(),
37 'parent_id' => 1,
38 ]);
21b8bcb5
SL
39 if (!empty($dataSet['limitedPermissions'])) {
40 CRM_Core_Config::singleton()->userPermissionClass->permissions = [
41 'access CiviCRM',
42 'access deleted contacts',
43 ];
44 }
fb1ee468 45 $params = CRM_Contact_BAO_Query::convertFormValues($dataSet['form_values'], 0, FALSE, NULL, []);
54b8719b 46 $isDeleted = in_array(['deleted_contacts', '=', 1, 0, 0], $params);
836eb043 47 foreach ($dataSet['settings'] as $setting) {
fb1ee468 48 $this->callAPISuccess('Setting', 'create', [$setting['name'] => $setting['value']]);
836eb043 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();
def88c52 61 // Make sure there is no fail on alphabet query.
62 $selector->alphabetQuery()->fetchAll();
54b8719b 63 $sql = $queryObject->query(FALSE, FALSE, FALSE, $isDeleted);
836eb043 64 $this->wrangleDefaultClauses($dataSet['expected_query']);
65 foreach ($dataSet['expected_query'] as $index => $queryString) {
299c1530 66 $this->assertLike($this->strWrangle($queryString), $this->strWrangle($sql[$index]));
836eb043 67 }
32704862 68 if (!empty($dataSet['where_contains'])) {
275686a3 69 $this->assertStringContainsString($this->strWrangle(str_replace('@tagid', $tag['id'], $dataSet['where_contains'])), $this->strWrangle($sql[2]));
32704862 70 }
7ccccc32 71 // Ensure that search builder return individual contact as per criteria
d1d108ee 72 if ($dataSet['context'] === 'builder') {
d567ed10 73 $contactID = $this->individualCreate(['first_name' => 'James', 'last_name' => 'Bond']);
d1d108ee 74 if ('Search builder behaviour for Activity' === $dataSet['description']) {
fd95406d 75 $this->callAPISuccess('Activity', 'create', [
76 'activity_type_id' => 'Meeting',
d1d108ee 77 'subject' => 'Test',
fd95406d 78 'source_contact_id' => $contactID,
79 ]);
80 $rows = CRM_Core_DAO::executeQuery(implode(' ', $sql))->fetchAll();
d1d108ee 81 $this->assertCount(1, $rows);
fd95406d 82 $this->assertEquals($contactID, $rows[0]['source_contact_id']);
83 }
84 else {
32704862
SL
85 $this->callAPISuccess('EntityTag', 'create', [
86 'entity_id' => $contactID,
87 'tag_id' => $tag['id'],
88 'entity_table' => 'civicrm_contact',
89 ]);
fd95406d 90 $this->callAPISuccess('Address', 'create', [
91 'contact_id' => $contactID,
d1d108ee 92 'location_type_id' => 'Home',
fd95406d 93 'is_primary' => 1,
d1d108ee 94 'country_id' => 'IN',
fd95406d 95 ]);
96 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 50, '');
97 $this->assertEquals(1, count($rows));
2365bc96 98
99 CRM_Core_DAO::reenableFullGroupByMode();
100 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 50, '');
101
fd95406d 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));
2365bc96 106
107 CRM_Core_DAO::reenableFullGroupByMode();
108 $selector->getQueryObject()->getCachedContacts([$contactID], FALSE);
fd95406d 109 }
7ccccc32 110 }
21b8bcb5
SL
111 if (!empty($dataSet['limitedPermissions'])) {
112 $this->cleanUpAfterACLs();
113 }
32704862 114 $this->callAPISuccess('Tag', 'delete', ['id' => $tag['id']]);
836eb043 115 }
116
7906396a
JP
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) {
275686a3 178 $this->assertStringContainsString("(On Hold)", (string) $value);
7906396a
JP
179 }
180 }
181 }
182
2eb3ff3e 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']);
fb1ee468 188 $dataSet = [
2eb3ff3e 189 'description' => 'Normal default behaviour',
190 'class' => 'CRM_Contact_Selector',
fb1ee468 191 'settings' => [],
192 'form_values' => ['email' => 'mickey@mouseville.com'],
193 'params' => [],
2eb3ff3e 194 'return_properties' => NULL,
195 'context' => 'advanced',
196 'action' => CRM_Core_Action::ADVANCED,
197 'includeContactIds' => NULL,
198 'searchDescendentGroups' => FALSE,
fb1ee468 199 'expected_query' => [
2eb3ff3e 200 0 => 'default',
201 1 => 'default',
54b8719b 202 2 => "WHERE ( civicrm_email.email LIKE '%mickey@mouseville.com%' ) AND (contact_a.is_deleted = 0)",
fb1ee468 203 ],
204 ];
205 $params = CRM_Contact_BAO_Query::convertFormValues($dataSet['form_values'], 0, FALSE, NULL, []);
2eb3ff3e 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
1d17e4fc 223 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 1, NULL);
2eb3ff3e 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')
783b4b21
SL
230 ->select(['entity_id1', 'cachekey'])
231 ->where("cachekey = @key")
39b959db
SL
232 ->param('key', $cacheKey)
233 ->execute()
234 ->fetchAll();
2eb3ff3e 235 $this->assertEquals(1, count($contacts));
236 // check the prevNext record matches
237 $expectedEntry = [
2eb3ff3e 238 'entity_id1' => $contactID,
783b4b21 239 'cachekey' => $cacheKey,
2eb3ff3e 240 ];
241 $this->checkArrayEquals($contacts[0], $expectedEntry);
242 }
243
836eb043 244 /**
245 * Data sets for testing.
246 */
247 public function querySets() {
fb1ee468 248 return [
249 [
250 [
e2b506f7 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,
673fae6c 261 'expected_query' => [],
fb1ee468 262 ],
263 ],
32704862
SL
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 ],
fb1ee468 280 [
281 [
836eb043 282 'description' => 'Normal default behaviour',
283 'class' => 'CRM_Contact_Selector',
fb1ee468 284 'settings' => [],
285 'form_values' => ['email' => 'mickey@mouseville.com'],
286 'params' => [],
836eb043 287 'return_properties' => NULL,
288 'context' => 'advanced',
289 'action' => CRM_Core_Action::ADVANCED,
290 'includeContactIds' => NULL,
291 'searchDescendentGroups' => FALSE,
fb1ee468 292 'expected_query' => [
836eb043 293 0 => 'default',
294 1 => 'default',
99827266 295 2 => "WHERE ( civicrm_email.email LIKE '%mickey@mouseville.com%' ) AND ( 1 ) AND (contact_a.is_deleted = 0)",
fb1ee468 296 ],
297 ],
298 ],
299 [
300 [
836eb043 301 'description' => 'Normal default + user added wildcard',
302 'class' => 'CRM_Contact_Selector',
fb1ee468 303 'settings' => [],
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',
99827266 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)",
fb1ee468 315 ],
316 ],
317 ],
318 [
319 [
836eb043 320 'description' => 'Site set to not pre-pend wildcard',
321 'class' => 'CRM_Contact_Selector',
fb1ee468 322 'settings' => [['name' => 'includeWildCardInName', 'value' => FALSE]],
323 'form_values' => ['email' => 'mickey@mouseville.com', 'sort_name' => 'Mouse'],
324 'params' => [],
836eb043 325 'return_properties' => NULL,
326 'context' => 'advanced',
327 'action' => CRM_Core_Action::ADVANCED,
328 'includeContactIds' => NULL,
329 'searchDescendentGroups' => FALSE,
fb1ee468 330 'expected_query' => [
836eb043 331 0 => 'default',
332 1 => 'default',
99827266 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)",
fb1ee468 334 ],
335 ],
336 ],
337 [
54b8719b
SL
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',
99827266 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)",
54b8719b
SL
353 ],
354 ],
21b8bcb5
SL
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 ],
99827266
SL
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 ],
21b8bcb5 396 [
fb1ee468 397 [
836eb043 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',
fb1ee468 401 'settings' => [['name' => 'includeWildCardInName', 'value' => FALSE]],
402 'form_values' => ['email' => '"mickey@mouseville.com"', 'sort_name' => 'Mouse'],
403 'params' => [],
836eb043 404 'return_properties' => NULL,
405 'context' => 'advanced',
406 'action' => CRM_Core_Action::ADVANCED,
407 'includeContactIds' => NULL,
408 'searchDescendentGroups' => FALSE,
fb1ee468 409 'expected_query' => [
836eb043 410 0 => 'default',
411 1 => 'default',
99827266 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)",
fb1ee468 413 ],
414 ],
415 ],
416 [
417 [
7ccccc32 418 'description' => 'Normal search builder behaviour',
419 'class' => 'CRM_Contact_Selector',
fb1ee468 420 'settings' => [],
421 'form_values' => ['contact_type' => 'Individual', 'country' => ['IS NOT NULL' => 1]],
422 'params' => [],
423 'return_properties' => [
7ccccc32 424 'contact_type' => 1,
425 'contact_sub_type' => 1,
426 'sort_name' => 1,
fb1ee468 427 ],
7ccccc32 428 'context' => 'builder',
429 'action' => CRM_Core_Action::NONE,
430 'includeContactIds' => NULL,
431 'searchDescendentGroups' => FALSE,
fb1ee468 432 'expected_query' => [
a220b357 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 )',
99827266 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)',
fb1ee468 436 ],
437 ],
438 ],
439 [
440 [
fd95406d 441 'description' => 'Search builder behaviour for Activity',
442 'class' => 'CRM_Contact_Selector',
fb1ee468 443 'settings' => [],
444 'form_values' => ['source_contact_id' => ['IS NOT NULL' => 1]],
445 'params' => [],
446 'return_properties' => [
fd95406d 447 'source_contact_id' => 1,
fb1ee468 448 ],
fd95406d 449 'context' => 'builder',
450 'action' => CRM_Core_Action::NONE,
451 'includeContactIds' => NULL,
452 'searchDescendentGroups' => FALSE,
fb1ee468 453 'expected_query' => [
fd95406d 454 0 => 'SELECT contact_a.id as contact_id, source_contact.id as source_contact_id',
99827266 455 2 => 'WHERE ( source_contact.id IS NOT NULL ) AND ( 1 ) AND (contact_a.is_deleted = 0)',
fb1ee468 456 ],
457 ],
458 ],
459 [
460 [
def88c52 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,
fb1ee468 471 'expected_query' => [
def88c52 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`',
7ebe0c1e 473 2 => 'WHERE 1 AND displayRelType.relationship_type_id = 1
def88c52 474AND displayRelType.is_active = 1
99827266 475AND ( 1 ) AND (contact_a.is_deleted = 0)',
fb1ee468 476 ],
477 ],
478 ],
479 ];
836eb043 480 }
481
ae066a2b 482 /**
483 * Test the contact ID query does not fail on country search.
484 */
485 public function testContactIDQuery() {
39b959db
SL
486 $params = [
487 [
488 0 => 'country-1',
489 1 => '=',
490 2 => '1228',
491 3 => 1,
492 4 => 0,
493 ],
494 ];
ae066a2b 495
496 $searchOBJ = new CRM_Contact_Selector(NULL);
497 $searchOBJ->contactIDQuery($params, '1_u');
498 }
499
f9ba4d01 500 /**
501 * Test the Search Builder using Non ASCII location type for email filter
502 */
503 public function testSelectorQueryOnNonASCIIlocationType() {
504 $contactID = $this->individualCreate();
d4d66593 505 $locationTypeID = $this->locationTypeCreate([
f9ba4d01 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,
d4d66593 513 'location_type_id' => $locationTypeID,
f9ba4d01 514 'email' => 'test@test.com',
515 ]);
516
517 $selector = new CRM_Contact_Selector(
518 'CRM_Contact_Selector',
519 ['email' => ['IS NOT NULL' => 1]],
39b959db
SL
520 [
521 [
d4d66593 522 0 => 'email-' . $locationTypeID,
39b959db
SL
523 1 => 'IS NOT NULL',
524 2 => NULL,
fb1ee468 525 3 => 1,
39b959db
SL
526 4 => 0,
527 ],
528 ],
f9ba4d01 529 [
530 'contact_type' => 1,
531 'contact_sub_type' => 1,
532 'sort_name' => 1,
533 'location' => [
534 'Non ASCII Location Type' => [
d4d66593 535 'location_type' => $locationTypeID,
f9ba4d01 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 = [
48c48a4b 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`",
f9ba4d01 550 // @TODO these FROM clause doesn't matches due to extra spaces or special character
99827266 551 2 => "WHERE ( ( `Non_ASCII_Location_Type-email`.email IS NOT NULL ) ) AND ( 1 ) AND (contact_a.is_deleted = 0)",
f9ba4d01 552 ];
553 foreach ($expectedQuery as $index => $queryString) {
554 $this->assertEquals($this->strWrangle($queryString), $this->strWrangle($sql[$index]));
555 }
556
1d17e4fc 557 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 1, NULL);
f9ba4d01 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
a0475688 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 = [
39b959db
SL
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
0800bc59 584 'RLIKE' => "( CAST(contact_a.first_name AS BINARY) RLIKE BINARY '^A[a-z]{3}$' )",
39b959db
SL
585 // case sensitive check
586 'IN' => '( contact_a.first_name IN ("Adam") )',
a0475688 587 ];
588 foreach ($filters as $op => $filter) {
589 $selector = new CRM_Contact_Selector(
590 'CRM_Contact_Selector',
591 ['first_name' => [$op => $filter]],
39b959db
SL
592 [
593 [
594 0 => 'first_name',
595 1 => $op,
596 2 => $filter,
597 3 => 1,
598 4 => 0,
599 ],
600 ],
a0475688 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
1d17e4fc 611 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 1, NULL);
a0475688 612 $this->assertEquals(1, count($rows));
613 $this->assertEquals($contactID, key($rows));
614 }
615 }
616
744050b0
JP
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.
39b959db
SL
623 $params = [
624 [
625 0 => 'country-1',
626 1 => '=',
627 2 => '1228',
628 3 => 1,
629 4 => 0,
630 ],
631 ];
744050b0
JP
632
633 //Create a test custom group and field.
fb1ee468 634 $customGroup = $this->callAPISuccess('CustomGroup', 'create', [
744050b0
JP
635 'title' => "test custom group",
636 'extends' => "Individual",
fb1ee468 637 ]);
744050b0 638 $cgTableName = $customGroup['values'][$customGroup['id']]['table_name'];
fb1ee468 639 $customField = $this->callAPISuccess('CustomField', 'create', [
744050b0
JP
640 'custom_group_id' => $customGroup['id'],
641 'label' => "test field",
642 'html_type' => "Text",
fb1ee468 643 ]);
744050b0
JP
644 $customFieldId = $customField['id'];
645
646 //Sort by the custom field created above.
fb1ee468 647 $sortParams = [
648 1 => [
744050b0
JP
649 'name' => 'test field',
650 'sort' => "custom_{$customFieldId}",
fb1ee468 651 ],
652 ];
744050b0
JP
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.
c3f7ab62 667 $this->assertTrue(array_key_exists($cgTableName, $query->_tables));
744050b0
JP
668 //Assert if from clause joins the custom table.
669 $this->assertTrue(strpos($query->_fromClause, $cgTableName) !== FALSE);
1d17e4fc
SL
670 $this->callAPISuccess('CustomField', 'delete', ['id' => $customField['id']]);
671 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $customGroup['id']]);
744050b0
JP
672 }
673
8ad22b15 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.
fb1ee468 680 $customGroup = $this->callAPISuccess('CustomGroup', 'create', [
8ad22b15 681 'title' => "test custom group",
682 'extends' => "Individual",
fb1ee468 683 ]);
1d17e4fc 684 $customTableName = $this->callAPISuccess('CustomGroup', 'getValue', ['id' => $customGroup['id'], 'return' => 'table_name']);
8ad22b15 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]],
39b9dbb3
TO
705 [
706 [
707 0 => 'custom_' . $createdField['id'],
708 1 => 'IS NOT NULL',
709 2 => 1,
710 3 => 1,
711 4 => 0,
712 ],
39b959db 713 ],
8ad22b15 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
1d17e4fc 726 $rows = $selector->getRows(CRM_Core_Action::VIEW, 0, 1, NULL);
8ad22b15 727 $this->assertEquals(1, count($rows));
728 }
729
836eb043 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`,'
fb1ee468 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`';
836eb043 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 )'
fb1ee468 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 ';
836eb043 763 }
764
765 /**
766 * Strangle strings into a more matchable format.
767 *
768 * @param string $string
fb1ee468 769 *
836eb043 770 * @return string
771 */
772 public function strWrangle($string) {
def88c52 773 return trim(str_replace(' ', ' ', $string));
836eb043 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) {
fd95406d 785 if (CRM_Utils_Array::value(0, $expectedQuery) == 'default') {
836eb043 786 $expectedQuery[0] = $this->getDefaultSelectString();
787 }
fd95406d 788 if (CRM_Utils_Array::value(1, $expectedQuery) == 'default') {
836eb043 789 $expectedQuery[1] = $this->getDefaultFromString();
790 }
791 }
792
793}