4 * Include dataProvider for tests
8 class CRM_Contact_BAO_QueryTest
extends CiviUnitTestCase
{
10 use CRMTraits_Financial_FinancialACLTrait
;
11 use CRMTraits_Financial_PriceSetTrait
;
14 * @return CRM_Contact_BAO_QueryTestDataProvider
16 public function dataProvider() {
17 return new CRM_Contact_BAO_QueryTestDataProvider();
20 public function setUp() {
25 * Clean up after test.
29 public function tearDown() {
30 $this->quickCleanUpFinancialEntities();
32 'civicrm_group_contact',
34 'civicrm_saved_search',
40 $this->quickCleanup($tablesToTruncate);
45 * Test CRM_Contact_BAO_Query::searchQuery().
47 * @dataProvider dataProvider
53 * @throws \CRM_Core_Exception
55 public function testSearch($fv, $count, $ids) {
56 $this->callAPISuccess('SavedSearch', 'create', ['form_values' => 'a:9:{s:5:"qfKey";s:32:"0123456789abcdef0123456789abcdef";s:13:"includeGroups";a:1:{i:0;s:1:"3";}s:13:"excludeGroups";a:0:{}s:11:"includeTags";a:0:{}s:11:"excludeTags";a:0:{}s:4:"task";s:2:"14";s:8:"radio_ts";s:6:"ts_all";s:14:"customSearchID";s:1:"4";s:17:"customSearchClass";s:36:"CRM_Contact_Form_Search_Custom_Group";}']);
57 $this->callAPISuccess('SavedSearch', 'create', ['form_values' => 'a:9:{s:5:"qfKey";s:32:"0123456789abcdef0123456789abcdef";s:13:"includeGroups";a:1:{i:0;s:1:"3";}s:13:"excludeGroups";a:0:{}s:11:"includeTags";a:0:{}s:11:"excludeTags";a:0:{}s:4:"task";s:2:"14";s:8:"radio_ts";s:6:"ts_all";s:14:"customSearchID";s:1:"4";s:17:"customSearchClass";s:36:"CRM_Contact_Form_Search_Custom_Group";}']);
59 $tag7 = $this->ids
['Tag'][7] = $this->tagCreate(['name' => 'Test Tag 7', 'description' => 'Test Tag 7'])['id'];
60 $tag9 = $this->ids
['Tag'][9] = $this->tagCreate(['name' => 'Test Tag 9', 'description' => 'Test Tag 9'])['id'];
61 $this->tagCreate(['name' => 'Test Tag 10']);
63 3 => ['name' => 'Test Group 3'],
64 4 => ['name' => 'Test Smart Group 4', 'saved_search_id' => 1],
65 5 => ['name' => 'Test Group 5'],
66 6 => ['name' => 'Test Smart Group 6', 'saved_search_id' => 2],
69 foreach ($groups as $id => $group) {
70 $this->ids
['Group'][$id] = $this->groupCreate(array_merge($group, ['title' => $group['name']]));
73 ['first_name' => 'Test', 'last_name' => 'Test Contact 9', 'gender_id' => 1, 'prefix_id' => 1, 'suffix_id' => 1],
74 ['first_name' => 'Test', 'last_name' => 'Test Contact 10', 'gender_id' => 2, 'prefix_id' => 2, 'suffix_id' => 2, 'api.entity_tag.create' => ['tag_id' => $tag9]],
75 ['first_name' => 'Test', 'last_name' => 'Test Contact 11', 'gender_id' => 3, 'prefix_id' => 3, 'suffix_id' => 3, 'api.entity_tag.create' => ['tag_id' => $tag7]],
77 'first_name' => 'Test',
78 'last_name' => 'Test Contact 12',
82 'api.entity_tag.create' => ['tag_id' => $tag9],
83 'api.entity_tag.create.2' => ['tag_id' => $tag7],
85 ['first_name' => 'Test', 'last_name' => 'Test Contact 13', 'gender_id' => 2, 'prefix_id' => 2, 'suffix_id' => 2],
86 ['first_name' => 'Test', 'last_name' => 'Test Contact 14', 'gender_id' => 3, 'prefix_id' => 4, 'suffix_id' => 4, 'api.entity_tag.create' => ['tag_id' => $tag9]],
87 ['first_name' => 'Test', 'last_name' => 'Test Contact 15', 'gender_id' => 3, 'prefix_id' => 4, 'suffix_id' => 5, 'api.entity_tag.create' => ['tag_id' => $tag7]],
89 'first_name' => 'Test',
90 'last_name' => 'Test Contact 16',
94 'api.entity_tag.create' => ['tag_id' => $tag9],
95 'api.entity_tag.create.2' => ['tag_id' => $tag7],
97 ['first_name' => 'Test', 'last_name' => 'Test Contact 17', 'gender_id' => 2, 'prefix_id' => 4, 'suffix_id' => 7],
98 ['first_name' => 'Test', 'last_name' => 'Test Contact 18', 'gender_id' => 2, 'prefix_id' => 4, 'suffix_id' => 4, 'api.entity_tag.create' => ['tag_id' => $tag9]],
99 ['first_name' => 'Test', 'last_name' => 'Test Contact 19', 'gender_id' => 2, 'prefix_id' => 4, 'suffix_id' => 6, 'api.entity_tag.create.2' => ['tag_id' => $tag7]],
101 'first_name' => 'Test',
102 'last_name' => 'Test Contact 20',
106 'api.entity_tag.create' => ['tag_id' => $tag9],
107 'api.entity_tag.create.2' => ['tag_id' => $tag7],
109 ['first_name' => 'Test', 'last_name' => 'Test Contact 21', 'gender_id' => 3, 'prefix_id' => 1, 'suffix_id' => 6],
110 ['first_name' => 'Test', 'last_name' => 'Test Contact 22', 'gender_id' => 1, 'prefix_id' => 1, 'suffix_id' => 1, 'api.entity_tag.create' => ['tag_id' => $tag9]],
111 ['first_name' => 'Test', 'last_name' => 'Test Contact 23', 'gender_id' => 3, 'prefix_id' => 1, 'suffix_id' => 1, 'api.entity_tag.create' => ['tag_id' => $tag7]],
113 'first_name' => 'Test',
114 'last_name' => 'Test Contact 24',
118 'api.entity_tag.create' => ['tag_id' => $tag9],
119 'api.entity_tag.create.2' => ['tag_id' => $tag7],
122 foreach ($individuals as $individual) {
123 $this->ids
['Contact'][$individual['last_name']] = $this->individualCreate($individual);
143 foreach ($groupContacts as $group) {
144 $groupID = $this->ids
['Group'][key($group)];
145 $contactID = $this->ids
['Contact']['Test Contact ' . reset($group)];
146 $this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $contactID, 'status' => 'Added']);
149 // We have migrated from a hard-coded dataset to a dynamic one but are still working with the same
150 // dataprovider at this stage -> wrangle.
151 foreach ($fv as $key => $value) {
152 $entity = ucfirst($key);
153 if (!array_key_exists($entity, $this->ids
)) {
156 if (is_numeric($value)) {
157 $fv[$key] = $this->ids
[$entity][$value];
159 elseif (!empty($value[0])) {
160 foreach ($value as $index => $oldGroup) {
161 $fv[$key][$index] = $this->ids
[$entity][$oldGroup];
165 foreach (array_keys($value) as $index) {
166 unset($fv[$key][$index]);
167 $fv[$key][$this->ids
[$entity][$index]] = 1;
172 $params = CRM_Contact_BAO_Query
::convertFormValues($fv);
173 $obj = new CRM_Contact_BAO_Query($params);
175 // let's set useGroupBy=true since we are listing contacts here who might belong to
176 // more than one group / tag / notes etc.
177 $obj->_useGroupBy
= TRUE;
179 $dao = $obj->searchQuery();
182 while ($dao->fetch()) {
183 $contacts[] = $dao->contact_id
;
186 sort($contacts, SORT_NUMERIC
);
189 foreach ($ids as $id) {
190 $expectedIDs[] = $this->ids
['Contact']['Test Contact ' . $id];
192 $this->assertEquals($expectedIDs, $contacts);
196 * Check that we get a successful result querying for home address.
197 * CRM-14263 search builder failure with search profile & address in criteria
199 * @throws \CRM_Core_Exception
201 public function testSearchProfileHomeCityCRM14263() {
202 $contactID = $this->individualCreate();
203 CRM_Core_Config
::singleton()->defaultSearchProfileID
= 1;
204 $this->callAPISuccess('address', 'create', [
205 'contact_id' => $contactID,
206 'city' => 'Cool City',
207 'location_type_id' => 1,
218 $returnProperties = [
220 'contact_sub_type' => 1,
224 $queryObj = new CRM_Contact_BAO_Query($params, $returnProperties);
226 $resultDAO = $queryObj->searchQuery();
227 $this->assertTrue($resultDAO->fetch());
229 catch (PEAR_Exception
$e) {
230 $err = $e->getCause();
231 $this->fail('invalid SQL created' . $e->getMessage() . " " . $err->userinfo
);
237 * Check that we get a successful result querying for home address.
238 * CRM-14263 search builder failure with search profile & address in criteria
240 * @throws \CRM_Core_Exception
242 public function testSearchProfileHomeCityNoResultsCRM14263() {
243 $contactID = $this->individualCreate();
244 CRM_Core_Config
::singleton()->defaultSearchProfileID
= 1;
245 $this->callAPISuccess('address', 'create', [
246 'contact_id' => $contactID,
247 'city' => 'Cool City',
248 'location_type_id' => 1,
259 $returnProperties = [
261 'contact_sub_type' => 1,
265 $queryObj = new CRM_Contact_BAO_Query($params, $returnProperties);
267 $resultDAO = $queryObj->searchQuery();
268 $this->assertFalse($resultDAO->fetch());
270 catch (PEAR_Exception
$e) {
271 $err = $e->getCause();
272 $this->fail('invalid SQL created' . $e->getMessage() . " " . $err->userinfo
);
278 * Test searchPrimaryDetailsOnly setting.
280 * @throws \CRM_Core_Exception
282 public function testSearchPrimaryLocTypes() {
283 $contactID = $this->individualCreate();
285 'contact_id' => $contactID,
286 'email' => 'primary@example.com',
289 $this->callAPISuccess('email', 'create', $params);
291 unset($params['is_primary']);
292 $params['email'] = 'secondary@team.com';
293 $this->callAPISuccess('email', 'create', $params);
295 foreach ([0, 1] as $searchPrimary) {
296 Civi
::settings()->set('searchPrimaryDetailsOnly', $searchPrimary);
302 2 => 'sEcondary@example.com',
307 $returnProperties = [
309 'contact_sub_type' => 1,
313 $queryObj = new CRM_Contact_BAO_Query($params, $returnProperties);
314 $resultDAO = $queryObj->searchQuery();
316 if ($searchPrimary) {
317 $this->assertEquals($resultDAO->N
, 0);
320 //Assert secondary email gets included in search results.
321 while ($resultDAO->fetch()) {
322 $this->assertEquals('secondary@example.com', $resultDAO->email
);
326 // API should always return primary email.
327 $result = $this->callAPISuccess('Contact', 'get', ['contact_id' => $contactID]);
328 $this->assertEquals('primary@example.com', $result['values'][$contactID]['email']);
333 * Test created to prove failure of search on state when location
334 * display name is different form location name (issue 607)
336 * @throws \CRM_Core_Exception
338 public function testSearchOtherLocationUpperLower() {
342 0 => 'state_province-4',
349 $returnProperties = [
351 'contact_sub_type' => 1,
355 'location_type' => 4,
356 'state_province' => 1,
361 // update with the api does not work because it updates both the name and the
362 // the display_name. Plain SQL however does the job
363 CRM_Core_DAO
::executeQuery('update civicrm_location_type set name=%2 where id=%1',
366 2 => ['other', 'String'],
369 $queryObj = new CRM_Contact_BAO_Query($params, $returnProperties);
371 $resultDAO = $queryObj->searchQuery();
376 * CRM-14263 search builder failure with search profile & address in criteria.
378 * We are retrieving primary here - checking the actual sql seems super prescriptive - but since the massive query object has
379 * so few tests detecting any change seems good here :-)
381 * @dataProvider getSearchProfileData
383 * @param array $params
384 * @param string $selectClause
385 * @param string $whereClause
387 * @throws \CRM_Core_Exception
389 public function testSearchProfilePrimaryCityCRM14263($params, $selectClause, $whereClause) {
390 $contactID = $this->individualCreate();
391 CRM_Core_Config
::singleton()->defaultSearchProfileID
= 1;
392 $this->callAPISuccess('address', 'create', [
393 'contact_id' => $contactID,
394 'city' => 'Cool CITY',
395 'street_address' => 'Long STREET',
396 'location_type_id' => 1,
398 $returnProperties = [
400 'contact_sub_type' => 1,
403 $expectedSQL = "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, " . $selectClause . " FROM civicrm_contact contact_a LEFT JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 ) WHERE ( ( " . $whereClause . " ) ) AND (contact_a.is_deleted = 0) ORDER BY `contact_a`.`sort_name` ASC, `contact_a`.`id` ";
404 $queryObj = new CRM_Contact_BAO_Query($params, $returnProperties);
406 $this->assertLike($expectedSQL, $queryObj->getSearchSQL());
407 list($select, $from, $where, $having) = $queryObj->query();
408 $dao = CRM_Core_DAO
::executeQuery("$select $from $where $having");
410 $this->assertEquals('Anderson, Anthony', $dao->sort_name
);
412 catch (PEAR_Exception
$e) {
413 $err = $e->getCause();
414 $this->fail('invalid SQL created' . $e->getMessage() . " " . $err->userinfo
);
420 * Get data sets to test for search.
422 public function getSearchProfileData() {
425 [['city', '=', 'Cool City', 1, 0]],
426 "civicrm_address.city as `city`",
427 "civicrm_address.city = 'Cool City'",
430 // Note that in the query 'long street' is lower cased. We eventually want to change that & not mess with the vars - it turns out
431 // it doesn't work on some charsets. However, the the lcasing affects more vars & we are looking to stagger removal of lcasing 'in case'
432 // (although we have been removing without blowback since 2017)
433 [['street_address', '=', 'Long Street', 1, 0]],
434 "civicrm_address.street_address as `street_address`",
435 "civicrm_address.street_address LIKE '%Long Street%'",
441 * Test set up to test calling the query object per GroupContactCache BAO usage.
443 * CRM-17254 ensure that if only the contact_id is required other fields should
446 public function testGroupContactCacheAddSearch() {
447 $returnProperties = ['contact_id'];
448 $params = [['group', 'IN', [1], 0, 0]];
450 $query = new CRM_Contact_BAO_Query(
451 $params, $returnProperties,
452 NULL, TRUE, FALSE, 1,
457 list($select) = $query->query(FALSE);
458 $this->assertEquals('SELECT contact_a.id as contact_id', $select);
462 * Test smart groups with non-numeric don't fail on range queries.
466 * @throws \CRM_Core_Exception
468 public function testNumericPostal() {
469 // Precaution as hitting some inconsistent set up running in isolation vs in the suite.
470 CRM_Core_DAO
::executeQuery('UPDATE civicrm_address SET postal_code = NULL');
472 $this->individualCreate(['api.address.create' => ['postal_code' => 5, 'location_type_id' => 'Main']]);
473 $this->individualCreate(['api.address.create' => ['postal_code' => 'EH10 4RB-889', 'location_type_id' => 'Main']]);
474 $this->individualCreate(['api.address.create' => ['postal_code' => '4', 'location_type_id' => 'Main']]);
475 $this->individualCreate(['api.address.create' => ['postal_code' => '6', 'location_type_id' => 'Main']]);
476 $this->individualCreate(['api.address.create' => ['street_address' => 'just a street', 'location_type_id' => 'Main']]);
477 $this->individualCreate(['api.address.create' => ['postal_code' => '12345678444455555555555555555555555555555555551314151617181920', 'location_type_id' => 'Main']]);
479 $params = [['postal_code_low', '=', 5, 0, 0]];
480 CRM_Contact_BAO_Query
::convertFormValues($params);
482 $query = new CRM_Contact_BAO_Query(
483 $params, ['contact_id'],
484 NULL, TRUE, FALSE, 1,
489 $sql = $query->query(FALSE);
490 $result = CRM_Core_DAO
::executeQuery(implode(' ', $sql));
491 $this->assertEquals(2, $result->N
);
493 // We save this as a smart group and then load it. With mysql warnings on & CRM-14720 this
494 // results in mysql warnings & hence fatal errors.
495 /// I was unable to get mysql warnings to activate in the context of the unit tests - but
496 // felt this code still provided a useful bit of coverage as it runs the various queries to load
497 // the group & could generate invalid sql if a bug were introduced.
498 $groupParams = ['title' => 'postal codes', 'formValues' => $params, 'is_active' => 1];
499 $group = CRM_Contact_BAO_Group
::createSmartGroup($groupParams);
500 CRM_Contact_BAO_GroupContactCache
::load($group, TRUE);
504 * Test searches are case insensitive.
506 * @throws \CRM_Core_Exception
508 public function testCaseInsensitive() {
509 $orgID = $this->organizationCreate(['organization_name' => 'BOb']);
511 'display_name' => 'Minnie Mouse',
512 'first_name' => 'Minnie',
513 'last_name' => 'Mouse',
514 'employer_id' => $orgID,
515 'contact_type' => 'Individual',
516 'nick_name' => 'Mins',
518 $this->callAPISuccess('Contact', 'create', $params);
519 unset($params['contact_type']);
520 foreach ($params as $key => $value) {
521 if ($key === 'employer_id') {
522 $searchParams = [['current_employer', '=', 'bob', 0, 1]];
525 $searchParams = [[$key, '=', strtolower($value), 0, 1]];
528 $result = CRM_Contact_BAO_Query
::apiQuery($searchParams);
529 $this->assertCount(1, $result[0], 'search for ' . $key);
530 $contact = reset($result[0]);
531 $this->assertEquals('Minnie Mouse', $contact['display_name']);
532 $this->assertEquals('BOb', $contact['current_employer']);
537 * Test smart groups with non-numeric don't fail on equal queries.
541 * @throws \CRM_Core_Exception
543 public function testNonNumericEqualsPostal() {
544 $this->individualCreate(['api.address.create' => ['postal_code' => 5, 'location_type_id' => 'Main']]);
545 $this->individualCreate(['api.address.create' => ['postal_code' => 'EH10 4RB-889', 'location_type_id' => 'Main']]);
546 $this->individualCreate(['api.address.create' => ['postal_code' => '4', 'location_type_id' => 'Main']]);
547 $this->individualCreate(['api.address.create' => ['postal_code' => '6', 'location_type_id' => 'Main']]);
549 $params = [['postal_code', '=', 'EH10 4RB-889', 0, 0]];
550 CRM_Contact_BAO_Query
::convertFormValues($params);
552 $query = new CRM_Contact_BAO_Query(
553 $params, ['contact_id'],
554 NULL, TRUE, FALSE, 1,
559 $sql = $query->query(FALSE);
560 $this->assertEquals("WHERE ( civicrm_address.postal_code = 'EH10 4RB-889' ) AND (contact_a.is_deleted = 0)", $sql[2]);
561 $result = CRM_Core_DAO
::executeQuery(implode(' ', $sql));
562 $this->assertEquals(1, $result->N
);
567 * Test relationship description.
569 * @throws \CRM_Core_Exception
571 public function testRelationshipDescription() {
572 $relType = $this->callAPISuccess('RelationshipType', 'create', [
573 'name_a_b' => 'blah',
574 'name_b_a' => 'other blah',
576 $contactID_a = $this->individualCreate([], 1);
577 $contactID_b = $this->individualCreate([], 2);
578 $contactID_c = $this->individualCreate([], 3);
579 $contactID_d = $this->individualCreate([], 4);
580 $desc = uniqid('rel', TRUE);
581 $this->callAPISuccess('Relationship', 'create', [
582 'contact_id_a' => $contactID_a,
583 'contact_id_b' => $contactID_b,
584 'relationship_type_id' => $relType['id'],
586 'description' => $desc,
588 $this->callAPISuccess('Relationship', 'create', [
589 'contact_id_a' => $contactID_c,
590 'contact_id_b' => $contactID_d,
591 'relationship_type_id' => $relType['id'],
593 'description' => 'nothing of interest',
596 ['relation_description', '=', substr($desc, 3, 18), 0, 0],
599 $query = new CRM_Contact_BAO_Query($params);
600 $dao = $query->searchQuery();
601 // This is a little weird but seems consistent with the behavior of the search form in general.
602 // Technically there are 2 contacts who share a relationship with the description searched for,
603 // so one might expect the search form to return both of them instead of just Contact A... but it doesn't.
604 $this->assertEquals('1', $dao->N
, 'Search query returns exactly 1 result?');
605 $this->assertTrue($dao->fetch(), 'Search query returns success?');
606 $this->assertEquals($contactID_a, $dao->contact_id
, 'Search query returns contact A?');
610 * Test non-reciprocal relationship.
612 * @throws \CRM_Core_Exception
614 public function testNonReciprocalRelationshipTargetGroupIsCorrectResults() {
615 $contactID_a = $this->individualCreate();
616 $contactID_b = $this->individualCreate();
617 $this->callAPISuccess('Relationship', 'create', [
618 'contact_id_a' => $contactID_a,
619 'contact_id_b' => $contactID_b,
620 'relationship_type_id' => 1,
623 // Create a group and add contact A to it.
624 $groupID = $this->groupCreate();
625 $this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $contactID_a, 'status' => 'Added']);
627 // Add another (sans-relationship) contact to the group,
628 $contactID_c = $this->individualCreate();
629 $this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $contactID_c, 'status' => 'Added']);
633 0 => 'relation_type_id',
643 0 => 'relation_target_group',
654 $query = new CRM_Contact_BAO_Query($params);
655 $dao = $query->searchQuery();
656 $this->assertEquals('1', $dao->N
, "Search query returns exactly 1 result?");
657 $this->assertTrue($dao->fetch(), "Search query returns success?");
658 $this->assertEquals($contactID_b, $dao->contact_id
, "Search query returns parent of contact A?");
662 * Relationship search with custom fields.
664 public function testReciprocalRelationshipWithCustomFields() {
666 'extends' => 'Relationship',
668 $customGroup = $this->customGroupCreate($params);
669 $customFieldId = $this->customFieldCreate(['custom_group_id' => $customGroup['id']])['id'];
670 $contactID_a = $this->individualCreate();
671 $contactID_b = $this->individualCreate();
672 $relationship = $this->callAPISuccess('Relationship', 'create', [
673 'contact_id_a' => $contactID_a,
674 'contact_id_b' => $contactID_b,
675 'relationship_type_id' => 2,
677 "custom_{$customFieldId}" => 'testvalue',
681 0 => 'relation_type_id',
691 0 => "custom_{$customFieldId}",
699 $query = new CRM_Contact_BAO_Query($params);
700 $dao = $query->searchQuery();
701 $this->assertEquals('2', $dao->N
);
702 $this->callAPISuccess('Relationship', 'delete', ['id' => $relationship['id']]);
703 $this->callAPISuccess('Contact', 'delete', ['id' => $contactID_a, 'skip_undelete' => 1]);
704 $this->callAPISuccess('Contact', 'delete', ['id' => $contactID_b, 'skip_undelete' => 1]);
705 $this->callAPISuccess('CustomField', 'delete', ['id' => $customFieldId, 'skip_undelete' => 1]);
706 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $customGroup]);
710 * @throws \CRM_Core_Exception
712 public function testReciprocalRelationshipTargetGroupIsCorrectResults() {
713 $contactID_a = $this->individualCreate();
714 $contactID_b = $this->individualCreate();
715 $this->callAPISuccess('Relationship', 'create', [
716 'contact_id_a' => $contactID_a,
717 'contact_id_b' => $contactID_b,
718 'relationship_type_id' => 2,
721 // Create a group and add contact A to it.
722 $groupID = $this->groupCreate();
723 $this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $contactID_a, 'status' => 'Added']);
725 // Add another (sans-relationship) contact to the group,
726 $contactID_c = $this->individualCreate();
727 $this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $contactID_c, 'status' => 'Added']);
731 0 => 'relation_type_id',
741 0 => 'relation_target_group',
752 $query = new CRM_Contact_BAO_Query($params);
753 $dao = $query->searchQuery();
754 $this->assertEquals('1', $dao->N
, "Search query returns exactly 1 result?");
755 $this->assertTrue($dao->fetch(), "Search query returns success?");
756 $this->assertEquals($contactID_b, $dao->contact_id
, "Search query returns spouse of contact A?");
759 public function testReciprocalRelationshipTargetGroupUsesTempTable() {
760 $groupID = $this->groupCreate();
763 0 => 'relation_type_id',
773 0 => 'relation_target_group',
783 $sql = CRM_Contact_BAO_Query
::getQuery($params);
784 $this->assertContains('INNER JOIN civicrm_tmp_e', $sql, "Query appears to use temporary table of compiled relationships?", TRUE);
788 * Test relationship permission clause.
790 * @throws \CRM_Core_Exception
792 public function testRelationshipPermissionClause() {
793 $params = [['relation_type_id', 'IN', ['1_b_a'], 0, 0], ['relation_permission', 'IN', [2], 0, 0]];
794 $sql = CRM_Contact_BAO_Query
::getQuery($params);
795 $this->assertContains('(civicrm_relationship.is_permission_a_b IN (2))', $sql);
799 * Test Relationship Clause
801 * @throws \CRM_Core_Exception
803 public function testRelationshipClause() {
804 $today = date('Ymd');
805 $from1 = " FROM civicrm_contact contact_a LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id ) LEFT JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
806 $from2 = " FROM civicrm_contact contact_a LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id ) LEFT JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
808 civicrm_relationship.is_active = 1 AND
809 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
810 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
811 ) AND (contact_b.is_deleted = 0) AND civicrm_relationship.relationship_type_id IN (8) ) AND (contact_a.is_deleted = 0)";
813 civicrm_relationship.is_active = 1 AND
814 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
815 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
816 ) AND (contact_b.is_deleted = 0) AND civicrm_relationship.relationship_type_id IN (8,10) ) AND (contact_a.is_deleted = 0)";
817 // Test Traditional single select format
818 $params1 = [['relation_type_id', '=', '8_a_b', 0, 0]];
819 $query1 = new CRM_Contact_BAO_Query(
820 $params1, ['contact_id'],
821 NULL, TRUE, FALSE, 1,
825 $sql1 = $query1->query(FALSE);
826 $this->assertLike($from1, $sql1[1]);
827 $this->assertLike($where1, $sql1[2]);
828 // Test single relationship type selected in multiple select.
829 $params2 = [['relation_type_id', 'IN', ['8_a_b'], 0, 0]];
830 $query2 = new CRM_Contact_BAO_Query(
831 $params2, ['contact_id'],
832 NULL, TRUE, FALSE, 1,
836 $sql2 = $query2->query(FALSE);
837 $this->assertLike($from1, $sql2[1]);
838 $this->assertLike($where1, $sql2[2]);
839 // Test multiple relationship types selected.
840 $params3 = [['relation_type_id', 'IN', ['8_a_b', '10_a_b'], 0, 0]];
841 $query3 = new CRM_Contact_BAO_Query(
842 $params3, ['contact_id'],
843 NULL, TRUE, FALSE, 1,
847 $sql3 = $query3->query(FALSE);
848 $this->assertLike($from1, $sql3[1]);
849 $this->assertLike($where2, $sql3[2]);
850 // Test Multiple Relationship type selected where one doesn't actually exist.
851 $params4 = [['relation_type_id', 'IN', ['8_a_b', '10_a_b', '14_a_b'], 0, 0]];
852 $query4 = new CRM_Contact_BAO_Query(
853 $params4, ['contact_id'],
854 NULL, TRUE, FALSE, 1,
858 $sql4 = $query4->query(FALSE);
859 $this->assertLike($from1, $sql4[1]);
860 $this->assertLike($where2, $sql4[2]);
862 // Test Multiple b to a Relationship type .
863 $params5 = [['relation_type_id', 'IN', ['8_b_a', '10_b_a', '14_b_a'], 0, 0]];
864 $query5 = new CRM_Contact_BAO_Query(
865 $params5, ['contact_id'],
866 NULL, TRUE, FALSE, 1,
870 $sql5 = $query5->query(FALSE);
871 $this->assertLike($from2, $sql5[1]);
872 $this->assertLike($where2, $sql5[2]);
876 * Test we can narrow a group get by status.
878 * @throws \CRM_Core_Exception
880 public function testGetByGroupWithStatus() {
881 $groupID = $this->groupCreate();
882 $this->groupContactCreate($groupID, 3);
883 $groupContactID = $this->callAPISuccessGetSingle('GroupContact', ['group_id' => $groupID, 'options' => ['limit' => 1]])['id'];
884 $this->callAPISuccess('GroupContact', 'create', ['id' => $groupContactID, 'status' => 'Removed']);
885 $queryObj = new CRM_Contact_BAO_Query([['group', '=', $groupID, 0, 0], ['group_contact_status', 'IN', ['Removed' => 1], 0, 0]]);
886 $resultDAO = $queryObj->searchQuery();
887 $this->assertEquals(1, $resultDAO->N
);
889 $queryObj = new CRM_Contact_BAO_Query([['group', '=', $groupID, 0, 0], ['group_contact_status', 'IN', ['Added' => 1], 0, 0]]);
890 $resultDAO = $queryObj->searchQuery();
891 $this->assertEquals(2, $resultDAO->N
);
893 $queryObj = new CRM_Contact_BAO_Query([['group', '=', $groupID, 0, 0]]);
894 $resultDAO = $queryObj->searchQuery();
895 $this->assertEquals(2, $resultDAO->N
);
899 * Test we can narrow a group get by status.
903 public function testGetByGroupWithStatusSmartGroup() {
904 $groupID = $this->smartGroupCreate();
905 // This means they are actually all hard-added, which is fine for this purpose.
906 $this->groupContactCreate($groupID, 3);
907 $groupContactID = $this->callAPISuccessGetSingle('GroupContact', ['group_id' => $groupID, 'options' => ['limit' => 1]])['id'];
908 $this->callAPISuccess('GroupContact', 'create', ['id' => $groupContactID, 'status' => 'Removed']);
910 $queryObj = new CRM_Contact_BAO_Query([['group', '=', $groupID, 0, 0], ['group_contact_status', 'IN', ['Removed' => 1], 0, 0]]);
911 $resultDAO = $queryObj->searchQuery();
912 $this->assertEquals(1, $resultDAO->N
);
914 $queryObj = new CRM_Contact_BAO_Query([['group', 'IS NOT EMPTY', '', 0, 0], ['group_contact_status', 'IN', ['Removed' => 1], 0, 0]]);
915 $resultDAO = $queryObj->searchQuery();
916 $this->assertEquals(1, $resultDAO->N
);
920 * Test the group contact clause does not contain an OR.
922 * The search should return 3 contacts - 2 households in the smart group of
923 * Contact Type = Household and one Individual hard-added to it. The
924 * Household that meets both criteria should be returned once.
928 public function testGroupClause() {
929 $this->householdCreate();
930 $householdID = $this->householdCreate();
931 $individualID = $this->individualCreate();
932 $groupID = $this->smartGroupCreate();
933 $this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $individualID, 'status' => 'Added']);
934 $this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $householdID, 'status' => 'Added']);
936 // Refresh the cache for test purposes. It would be better to alter to alter the GroupContact add function to add contacts to the cache.
937 CRM_Contact_BAO_GroupContactCache
::clearGroupContactCache($groupID);
939 $sql = CRM_Contact_BAO_Query
::getQuery(
940 [['group', 'IN', [$groupID], 0, 0]],
944 $dao = CRM_Core_DAO
::executeQuery($sql);
945 $this->assertEquals(3, $dao->N
);
946 $this->assertFalse(strstr($sql, ' OR '));
948 $sql = CRM_Contact_BAO_Query
::getQuery(
949 [['group', 'IN', [$groupID], 0, 0]],
950 ['contact_id' => 1, 'group' => 1]
953 $dao = CRM_Core_DAO
::executeQuery($sql);
954 $this->assertEquals(3, $dao->N
);
955 $this->assertFalse(strstr($sql, ' OR '), 'Query does not include or');
956 while ($dao->fetch()) {
957 $this->assertTrue(($dao->groups
== $groupID ||
$dao->groups
== ',' . $groupID), $dao->groups
. ' includes ' . $groupID);
962 * CRM-19562 ensure that only ids are used for contact_id searching.
964 * @throws \CRM_Core_Exception
966 public function testContactIDClause() {
968 ['mark_x_2', '=', 1, 0, 0],
969 ['mark_x_foo@example.com', '=', 1, 0, 0],
971 $returnProperties = [
978 'preferred_mail_format' => 1,
980 $numberOfContacts = 2;
983 CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, $numberOfContacts);
985 catch (Exception
$e) {
987 'One of parameters (value: foo@example.com) is not of the type Positive',
990 $this->assertTrue(TRUE);
993 $this->fail('Test failed for some reason which is not good');
997 * Test the sorting on the contact ID query works.
999 * Checking for lack of fatal.
1001 * @param string $sortOrder
1002 * Param reflecting how sort is passed in.
1003 * - 1_d is column 1 descending.
1005 * @dataProvider getSortOptions
1007 public function testContactIDQuery($sortOrder) {
1008 $selector = new CRM_Contact_Selector(NULL, ['radio_ts' => 'ts_all'], NULL, ['sort_name' => 1]);
1009 $selector->contactIDQuery([], $sortOrder);
1013 * Test the sorting on the contact ID query works with a profile search.
1015 * Checking for lack of fatal.
1017 * @throws \CRM_Core_Exception
1019 public function testContactIDQueryProfileSearchResults() {
1020 $profile = $this->callAPISuccess('UFGroup', 'create', ['group_type' => 'Contact', 'name' => 'search', 'title' => 'search']);
1021 $this->callAPISuccess('UFField', 'create', [
1022 'uf_group_id' => $profile['id'],
1023 'field_name' => 'postal_code',
1024 'field_type' => 'Contact',
1025 'in_selector' => TRUE,
1026 'is_searchable' => TRUE,
1027 'label' => 'postal code',
1028 'visibility' => 'Public Pages and Listings',
1030 $selector = new CRM_Contact_Selector(NULL, ['radio_ts' => 'ts_all', 'uf_group_id' => $profile['id']], NULL, ['sort_name' => 1]);
1031 $selector->contactIDQuery([], '2_d');
1035 * Get search options to reflect how a UI search would look.
1039 public function getSortOptions() {
1051 * Test the summary query does not add an acl clause when acls not enabled..
1053 * @throws \CRM_Core_Exception
1055 public function testGetSummaryQueryWithFinancialACLDisabled() {
1056 $this->createContributionsForSummaryQueryTests();
1058 // Test the function directly
1059 $where = $from = NULL;
1060 $queryObject = new CRM_Contact_BAO_Query();
1061 $queryObject->appendFinancialTypeWhereAndFromToQueryStrings($where,
1063 $this->assertEquals(NULL, $where);
1064 $this->assertEquals(NULL, $from);
1066 // Test the function in action
1067 $queryObject = new CRM_Contact_BAO_Query([['contribution_source', '=', 'SSF', '', '']]);
1068 $summary = $queryObject->summaryContribution();
1069 $this->assertEquals([
1071 'avg' => '$ 233.33',
1072 'amount' => '$ 1,400.00',
1077 'amount' => '$ 100.00',
1084 * Test the summary query accurately adds financial acl filters.
1086 * @throws \CRM_Core_Exception
1088 public function testGetSummaryQueryWithFinancialACLEnabled() {
1089 $where = $from = NULL;
1090 $this->createContributionsForSummaryQueryTests();
1091 $this->enableFinancialACLs();
1092 $this->createLoggedInUserWithFinancialACL();
1094 // Test the function directly
1095 $queryObject = new CRM_Contact_BAO_Query();
1096 $queryObject->appendFinancialTypeWhereAndFromToQueryStrings($where,
1098 $donationTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Donation');
1099 $this->assertEquals(
1100 " LEFT JOIN civicrm_line_item li
1101 ON civicrm_contribution.id = li.contribution_id AND
1102 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN ({$donationTypeID}) ", $from);
1104 // Test the function in action
1105 $queryObject = new CRM_Contact_BAO_Query([['contribution_source', '=', 'SSF', '', '']]);
1106 $summary = $queryObject->summaryContribution();
1107 $this->assertEquals([
1109 'avg' => '$ 200.00',
1110 'amount' => '$ 400.00',
1115 'amount' => '$ 50.00',
1119 $this->disableFinancialACLs();
1123 * Test relative date filters to ensure they generate correct SQL.
1125 * @dataProvider relativeDateFilters
1127 public function testRelativeDateFilters($filter, $expectedWhere) {
1128 $params = [['created_date_relative', '=', $filter, 0, 0]];
1130 $dates = CRM_Utils_Date
::getFromTo($filter, NULL, NULL);
1131 $expectedWhere = str_replace(['date0', 'date1'], [$dates[0], $dates[1]], $expectedWhere);
1133 $query = new CRM_Contact_BAO_Query(
1135 NULL, TRUE, FALSE, 1,
1140 list($select, $from, $where, $having) = $query->query();
1141 $this->assertEquals($expectedWhere, $where);
1144 public function relativeDateFilters() {
1145 $dataProvider[] = ['this.year', "WHERE ( contact_a.created_date BETWEEN 'date0' AND 'date1' ) AND (contact_a.is_deleted = 0)"];
1146 $dataProvider[] = ['greater.day', "WHERE ( contact_a.created_date >= 'date0' ) AND (contact_a.is_deleted = 0)"];
1147 $dataProvider[] = ['earlier.week', "WHERE ( contact_a.created_date <= 'date1' ) AND (contact_a.is_deleted = 0)"];
1148 return $dataProvider;
1152 * Create contributions to test summary calculations.
1154 * financial type | cancel_date |total_amount| source | line_item_financial_types |number_line_items| line_amounts
1155 * Donation |NULL | 100.00 |SSF | Donation | 1 | 100.00
1156 * Member Dues |NULL | 100.00 |SSF | Member Dues | 1 | 100.00
1157 * Donation |NULL | 300.00 |SSF | Event Fee,Event Fee | 2 | 200.00,100.00
1158 * Donation |NULL | 300.00 |SSF | Event Fee,Donation | 2 | 200.00,100.00
1159 * Donation |NULL | 300.00 |SSF | Donation,Donation | 2 | 200.00,100.00
1160 * Donation |2019-02-13 00:00:00 | 50.00 |SSF | Donation | 1 | 50.00
1161 * Member Dues |2019-02-13 00:00:00 | 50.00 |SSF | Member Dues | 1 | 50.00
1163 * @throws \CRM_Core_Exception
1165 protected function createContributionsForSummaryQueryTests() {
1166 $contactID = $this->individualCreate();
1167 $this->contributionCreate(['contact_id' => $contactID]);
1168 $this->contributionCreate([
1169 'contact_id' => $contactID,
1170 'total_amount' => 100,
1171 'financial_type_id' => 'Member Dues',
1173 $eventFeeType = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Event Fee');
1174 $this->createContributionWithTwoLineItemsAgainstPriceSet(['contact_id' => $contactID, 'source' => 'SSF']);
1175 $this->createContributionWithTwoLineItemsAgainstPriceSet(['contact_id' => $contactID, 'source' => 'SSF'], [
1176 CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Donation'),
1179 $this->createContributionWithTwoLineItemsAgainstPriceSet(['contact_id' => $contactID, 'source' => 'SSF'], [
1180 CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Donation'),
1181 CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Donation'),
1183 $this->createContributionWithTwoLineItemsAgainstPriceSet(['contact_id' => $contactID, 'source' => 'SSF', 'financial_type_id' => $eventFeeType], [
1184 CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Donation'),
1185 CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Donation'),
1187 $this->contributionCreate([
1188 'contact_id' => $contactID,
1189 'total_amount' => 50,
1190 'contribution_status_id' => 'Cancelled',
1191 'cancel_date' => 'yesterday',
1193 $this->contributionCreate([
1194 'contact_id' => $contactID,
1195 'total_amount' => 50,
1196 'contribution_status_id' => 'Cancelled',
1197 'cancel_date' => 'yesterday',
1198 'financial_type_id' => 'Member Dues',
1203 * Test the options are handled for the qill.
1205 public function testQillOptions() {
1206 $qill = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Activity_BAO_Activity', 'activity_type_id', 2, '=');
1207 $this->assertEquals(['=', 'Phone Call'], $qill);
1209 $qill = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Activity_BAO_Activity', 'priority_id', 2, '=');
1210 $this->assertEquals(['=', 'Normal'], $qill);
1214 * Test tests that a value on 'any entity' with the right metadata will be handled.
1216 * @throws \CRM_Core_Exception
1218 public function testGenericWhereHandling() {
1219 $query = new CRM_Contact_BAO_Query([['suffix_id', '=', 2, 0]]);
1220 $this->assertEquals("contact_a.suffix_id = 2", $query->_where
[0][0]);
1221 $this->assertEquals('Individual Suffix = Sr.', $query->_qill
[0][0]);
1222 $this->assertNotTrue(isset($query->_tables
['civicrm_activity']));
1224 $query = new CRM_Contact_BAO_Query([['prefix_id', '=', 2, 0]]);
1225 $this->assertEquals('contact_a.prefix_id = 2', $query->_where
[0][0]);
1226 $this->assertEquals('Individual Prefix = Ms.', $query->_qill
[0][0]);
1227 $this->assertNotTrue(isset($query->_tables
['civicrm_activity']));
1229 $query = new CRM_Contact_BAO_Query([['gender_id', '=', 2, 0]]);
1230 $this->assertEquals('contact_a.gender_id = 2', $query->_where
[0][0]);
1231 $this->assertEquals('Gender = Male', $query->_qill
[0][0]);
1232 $this->assertNotTrue(isset($query->_tables
['civicrm_activity']));
1234 $query = new CRM_Contact_BAO_Query([['communication_style_id', '=', 2, 0]]);
1235 $this->assertEquals('contact_a.communication_style_id = 2', $query->_where
[0][0]);
1236 $this->assertEquals('Communication Style = Familiar', $query->_qill
[0][0]);
1238 $query = new CRM_Contact_BAO_Query([['communication_style_id', '=', 2, 0]]);
1239 $this->assertEquals('contact_a.communication_style_id = 2', $query->_where
[0][0]);
1240 $this->assertEquals('Communication Style = Familiar', $query->_qill
[0][0]);
1242 $query = new CRM_Contact_BAO_Query([['contact_type', '=', 'Household', 0]]);
1243 $this->assertEquals("contact_a.contact_type = 'Household'", $query->_where
[0][0]);
1244 $this->assertEquals('Contact Type = Household', $query->_qill
[0][0]);
1246 $query = new CRM_Contact_BAO_Query([['on_hold', '=', 0, 0]]);
1247 $this->assertEquals('civicrm_email.on_hold = 0', $query->_where
[0][0]);
1248 $this->assertEquals('On Hold = 0', $query->_qill
[0][0]);
1250 $query = new CRM_Contact_BAO_Query([['on_hold', '=', 1, 0]]);
1251 $this->assertEquals('civicrm_email.on_hold = 1', $query->_where
[0][0]);
1252 $this->assertEquals('On Hold = 1', $query->_qill
[0][0]);
1254 $query = new CRM_Contact_BAO_Query([['world_region', '=', 3, 0]]);
1255 $this->assertEquals('civicrm_worldregion.id = 3', $query->_where
[0][0]);
1256 $this->assertEquals('World Region = Middle East and North Africa', $query->_qill
[0][0]);