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