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