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
54 public function testSearch($fv, $count, $ids, $full) {
55 $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";}']);
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";}']);
58 $tag7 = $this->ids
['Tag'][7] = $this->tagCreate(['name' => 'Test Tag 7', 'description' => 'Test Tag 7'])['id'];
59 $tag9 = $this->ids
['Tag'][9] = $this->tagCreate(['name' => 'Test Tag 9', 'description' => 'Test Tag 9'])['id'];
60 $this->tagCreate(['name' => 'Test Tag 10']);
62 3 => ['name' => 'Test Group 3'],
63 4 => ['name' => 'Test Smart Group 4', 'saved_search_id' => 1],
64 5 => ['name' => 'Test Group 5'],
65 6 => ['name' => 'Test Smart Group 6', 'saved_search_id' => 2],
68 foreach ($groups as $id => $group) {
69 $this->ids
['Group'][$id] = $this->groupCreate(array_merge($group, ['title' => $group['name']]));
72 ['first_name' => 'Test', 'last_name' => 'Test Contact 9', 'gender_id' => 1, 'prefix_id' => 1, 'suffix_id' => 1],
73 ['first_name' => 'Test', 'last_name' => 'Test Contact 10', 'gender_id' => 2, 'prefix_id' => 2, 'suffix_id' => 2, 'api.entity_tag.create' => ['tag_id' => $tag9]],
74 ['first_name' => 'Test', 'last_name' => 'Test Contact 11', 'gender_id' => 3, 'prefix_id' => 3, 'suffix_id' => 3, 'api.entity_tag.create' => ['tag_id' => $tag7]],
76 'first_name' => 'Test',
77 'last_name' => 'Test Contact 12',
81 'api.entity_tag.create' => ['tag_id' => $tag9],
82 'api.entity_tag.create.2' => ['tag_id' => $tag7],
84 ['first_name' => 'Test', 'last_name' => 'Test Contact 13', 'gender_id' => 2, 'prefix_id' => 2, 'suffix_id' => 2],
85 ['first_name' => 'Test', 'last_name' => 'Test Contact 14', 'gender_id' => 3, 'prefix_id' => 4, 'suffix_id' => 4, 'api.entity_tag.create' => ['tag_id' => $tag9]],
86 ['first_name' => 'Test', 'last_name' => 'Test Contact 15', 'gender_id' => 3, 'prefix_id' => 4, 'suffix_id' => 5, 'api.entity_tag.create' => ['tag_id' => $tag7]],
88 'first_name' => 'Test',
89 'last_name' => 'Test Contact 16',
93 'api.entity_tag.create' => ['tag_id' => $tag9],
94 'api.entity_tag.create.2' => ['tag_id' => $tag7],
96 ['first_name' => 'Test', 'last_name' => 'Test Contact 17', 'gender_id' => 2, 'prefix_id' => 4, 'suffix_id' => 7],
97 ['first_name' => 'Test', 'last_name' => 'Test Contact 18', 'gender_id' => 2, 'prefix_id' => 4, 'suffix_id' => 4, 'api.entity_tag.create' => ['tag_id' => $tag9]],
98 ['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]],
100 'first_name' => 'Test',
101 'last_name' => 'Test Contact 20',
105 'api.entity_tag.create' => ['tag_id' => $tag9],
106 'api.entity_tag.create.2' => ['tag_id' => $tag7],
108 ['first_name' => 'Test', 'last_name' => 'Test Contact 21', 'gender_id' => 3, 'prefix_id' => 1, 'suffix_id' => 6],
109 ['first_name' => 'Test', 'last_name' => 'Test Contact 22', 'gender_id' => 1, 'prefix_id' => 1, 'suffix_id' => 1, 'api.entity_tag.create' => ['tag_id' => $tag9]],
110 ['first_name' => 'Test', 'last_name' => 'Test Contact 23', 'gender_id' => 3, 'prefix_id' => 1, 'suffix_id' => 1, 'api.entity_tag.create' => ['tag_id' => $tag7]],
112 'first_name' => 'Test',
113 'last_name' => 'Test Contact 24',
117 'api.entity_tag.create' => ['tag_id' => $tag9],
118 'api.entity_tag.create.2' => ['tag_id' => $tag7],
121 foreach ($individuals as $individual) {
122 $this->ids
['Contact'][$individual['last_name']] = $this->individualCreate($individual);
142 foreach ($groupContacts as $group) {
143 $groupID = $this->ids
['Group'][key($group)];
144 $contactID = $this->ids
['Contact']['Test Contact ' . reset($group)];
145 $this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $contactID, 'status' => 'Added']);
148 // We have migrated from a hard-coded dataset to a dynamic one but are still working with the same
149 // dataprovider at this stage -> wrangle.
150 foreach ($fv as $key => $value) {
151 $entity = ucfirst($key);
152 if (!array_key_exists($entity, $this->ids
)) {
155 if (is_numeric($value)) {
156 $fv[$key] = $this->ids
[$entity][$value];
158 elseif (!empty($value[0])) {
159 foreach ($value as $index => $oldGroup) {
160 $fv[$key][$index] = $this->ids
[$entity][$oldGroup];
164 foreach (array_keys($value) as $index) {
165 unset($fv[$key][$index]);
166 $fv[$key][$this->ids
[$entity][$index]] = 1;
171 $params = CRM_Contact_BAO_Query
::convertFormValues($fv);
172 $obj = new CRM_Contact_BAO_Query($params);
174 // let's set useGroupBy=true since we are listing contacts here who might belong to
175 // more than one group / tag / notes etc.
176 $obj->_useGroupBy
= TRUE;
178 $dao = $obj->searchQuery();
181 while ($dao->fetch()) {
182 $contacts[] = $dao->contact_id
;
185 sort($contacts, SORT_NUMERIC
);
188 foreach ($ids as $id) {
189 $expectedIDs[] = $this->ids
['Contact']['Test Contact ' . $id];
191 $this->assertEquals($expectedIDs, $contacts);
195 * Check that we get a successful result querying for home address.
196 * CRM-14263 search builder failure with search profile & address in criteria
198 public function testSearchProfileHomeCityCRM14263() {
199 $contactID = $this->individualCreate();
200 CRM_Core_Config
::singleton()->defaultSearchProfileID
= 1;
201 $this->callAPISuccess('address', 'create', [
202 'contact_id' => $contactID,
203 'city' => 'Cool City',
204 'location_type_id' => 1,
215 $returnProperties = [
217 'contact_sub_type' => 1,
221 $queryObj = new CRM_Contact_BAO_Query($params, $returnProperties);
223 $resultDAO = $queryObj->searchQuery();
224 $this->assertTrue($resultDAO->fetch());
226 catch (PEAR_Exception
$e) {
227 $err = $e->getCause();
228 $this->fail('invalid SQL created' . $e->getMessage() . " " . $err->userinfo
);
234 * Check that we get a successful result querying for home address.
235 * CRM-14263 search builder failure with search profile & address in criteria
237 public function testSearchProfileHomeCityNoResultsCRM14263() {
238 $contactID = $this->individualCreate();
239 CRM_Core_Config
::singleton()->defaultSearchProfileID
= 1;
240 $this->callAPISuccess('address', 'create', [
241 'contact_id' => $contactID,
242 'city' => 'Cool City',
243 'location_type_id' => 1,
254 $returnProperties = [
256 'contact_sub_type' => 1,
260 $queryObj = new CRM_Contact_BAO_Query($params, $returnProperties);
262 $resultDAO = $queryObj->searchQuery();
263 $this->assertFalse($resultDAO->fetch());
265 catch (PEAR_Exception
$e) {
266 $err = $e->getCause();
267 $this->fail('invalid SQL created' . $e->getMessage() . " " . $err->userinfo
);
273 * Test searchPrimaryDetailsOnly setting.
275 public function testSearchPrimaryLocTypes() {
276 $contactID = $this->individualCreate();
278 'contact_id' => $contactID,
279 'email' => 'primary@example.com',
282 $this->callAPISuccess('email', 'create', $params);
284 unset($params['is_primary']);
285 $params['email'] = 'secondary@team.com';
286 $this->callAPISuccess('email', 'create', $params);
288 foreach ([0, 1] as $searchPrimary) {
289 Civi
::settings()->set('searchPrimaryDetailsOnly', $searchPrimary);
295 2 => 'sEcondary@example.com',
300 $returnProperties = [
302 'contact_sub_type' => 1,
306 $queryObj = new CRM_Contact_BAO_Query($params, $returnProperties);
307 $resultDAO = $queryObj->searchQuery();
309 if ($searchPrimary) {
310 $this->assertEquals($resultDAO->N
, 0);
313 //Assert secondary email gets included in search results.
314 while ($resultDAO->fetch()) {
315 $this->assertEquals('secondary@example.com', $resultDAO->email
);
319 // API should always return primary email.
320 $result = $this->callAPISuccess('Contact', 'get', ['contact_id' => $contactID]);
321 $this->assertEquals('primary@example.com', $result['values'][$contactID]['email']);
326 * Test created to prove failure of search on state when location
327 * display name is different form location name (issue 607)
329 public function testSearchOtherLocationUpperLower() {
333 0 => 'state_province-4',
340 $returnProperties = [
342 'contact_sub_type' => 1,
346 'location_type' => 4,
347 'state_province' => 1,
352 // update with the api does not work because it updates both the name and the
353 // the display_name. Plain SQL however does the job
354 CRM_Core_DAO
::executeQuery('update civicrm_location_type set name=%2 where id=%1',
357 2 => ['other', 'String'],
360 $queryObj = new CRM_Contact_BAO_Query($params, $returnProperties);
362 $resultDAO = $queryObj->searchQuery();
367 * CRM-14263 search builder failure with search profile & address in criteria.
369 * We are retrieving primary here - checking the actual sql seems super prescriptive - but since the massive query object has
370 * so few tests detecting any change seems good here :-)
372 * @dataProvider getSearchProfileData
374 * @param array $params
375 * @param string $selectClause
376 * @param string $whereClause
378 * @throws \CRM_Core_Exception
380 public function testSearchProfilePrimaryCityCRM14263($params, $selectClause, $whereClause) {
381 $contactID = $this->individualCreate();
382 CRM_Core_Config
::singleton()->defaultSearchProfileID
= 1;
383 $this->callAPISuccess('address', 'create', [
384 'contact_id' => $contactID,
385 'city' => 'Cool CITY',
386 'street_address' => 'Long STREET',
387 'location_type_id' => 1,
389 $returnProperties = [
391 'contact_sub_type' => 1,
394 $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` ";
395 $queryObj = new CRM_Contact_BAO_Query($params, $returnProperties);
397 $this->assertLike($expectedSQL, $queryObj->getSearchSQL());
398 list($select, $from, $where, $having) = $queryObj->query();
399 $dao = CRM_Core_DAO
::executeQuery("$select $from $where $having");
401 $this->assertEquals('Anderson, Anthony', $dao->sort_name
);
403 catch (PEAR_Exception
$e) {
404 $err = $e->getCause();
405 $this->fail('invalid SQL created' . $e->getMessage() . " " . $err->userinfo
);
411 * Get data sets to test for search.
413 public function getSearchProfileData() {
416 [['city', '=', 'Cool City', 1, 0]],
417 "civicrm_address.city as `city`",
418 "civicrm_address.city = 'Cool City'",
421 // Note that in the query 'long street' is lower cased. We eventually want to change that & not mess with the vars - it turns out
422 // it doesn't work on some charsets. However, the the lcasing affects more vars & we are looking to stagger removal of lcasing 'in case'
423 // (although we have been removing without blowback since 2017)
424 [['street_address', '=', 'Long Street', 1, 0]],
425 "civicrm_address.street_address as `street_address`",
426 "civicrm_address.street_address LIKE '%Long Street%'",
432 * Test set up to test calling the query object per GroupContactCache BAO usage.
434 * CRM-17254 ensure that if only the contact_id is required other fields should
437 public function testGroupContactCacheAddSearch() {
438 $returnProperties = ['contact_id'];
439 $params = [['group', 'IN', [1], 0, 0]];
441 $query = new CRM_Contact_BAO_Query(
442 $params, $returnProperties,
443 NULL, TRUE, FALSE, 1,
448 list($select) = $query->query(FALSE);
449 $this->assertEquals('SELECT contact_a.id as contact_id', $select);
453 * Test smart groups with non-numeric don't fail on range queries.
457 public function testNumericPostal() {
458 // Precaution as hitting some inconsistent set up running in isolation vs in the suite.
459 CRM_Core_DAO
::executeQuery('UPDATE civicrm_address SET postal_code = NULL');
461 $this->individualCreate(['api.address.create' => ['postal_code' => 5, 'location_type_id' => 'Main']]);
462 $this->individualCreate(['api.address.create' => ['postal_code' => 'EH10 4RB-889', 'location_type_id' => 'Main']]);
463 $this->individualCreate(['api.address.create' => ['postal_code' => '4', 'location_type_id' => 'Main']]);
464 $this->individualCreate(['api.address.create' => ['postal_code' => '6', 'location_type_id' => 'Main']]);
465 $this->individualCreate(['api.address.create' => ['street_address' => 'just a street', 'location_type_id' => 'Main']]);
466 $this->individualCreate(['api.address.create' => ['postal_code' => '12345678444455555555555555555555555555555555551314151617181920', 'location_type_id' => 'Main']]);
468 $params = [['postal_code_low', '=', 5, 0, 0]];
469 CRM_Contact_BAO_Query
::convertFormValues($params);
471 $query = new CRM_Contact_BAO_Query(
472 $params, ['contact_id'],
473 NULL, TRUE, FALSE, 1,
478 $sql = $query->query(FALSE);
479 $result = CRM_Core_DAO
::executeQuery(implode(' ', $sql));
480 $this->assertEquals(2, $result->N
);
482 // We save this as a smart group and then load it. With mysql warnings on & CRM-14720 this
483 // results in mysql warnings & hence fatal errors.
484 /// I was unable to get mysql warnings to activate in the context of the unit tests - but
485 // felt this code still provided a useful bit of coverage as it runs the various queries to load
486 // the group & could generate invalid sql if a bug were introduced.
487 $groupParams = ['title' => 'postal codes', 'formValues' => $params, 'is_active' => 1];
488 $group = CRM_Contact_BAO_Group
::createSmartGroup($groupParams);
489 CRM_Contact_BAO_GroupContactCache
::load($group, TRUE);
493 * Test searches are case insensitive.
495 public function testCaseInsensitive() {
496 $orgID = $this->organizationCreate(['organization_name' => 'BOb']);
498 'display_name' => 'Minnie Mouse',
499 'first_name' => 'Minnie',
500 'last_name' => 'Mouse',
501 'employer_id' => $orgID,
502 'contact_type' => 'Individual',
503 'nick_name' => 'Mins',
505 $this->callAPISuccess('Contact', 'create', $params);
506 unset($params['contact_type']);
507 foreach ($params as $key => $value) {
508 if ($key == 'employer_id') {
509 $searchParams = [['current_employer', '=', 'bob', 0, 1]];
512 $searchParams = [[$key, '=', strtolower($value), 0, 1]];
514 $query = new CRM_Contact_BAO_Query($searchParams);
515 $result = $query->apiQuery($searchParams);
516 $this->assertEquals(1, count($result[0]), 'search for ' . $key);
517 $contact = reset($result[0]);
518 $this->assertEquals('Minnie Mouse', $contact['display_name']);
519 $this->assertEquals('BOb', $contact['current_employer']);
524 * Test smart groups with non-numeric don't fail on equal queries.
528 public function testNonNumericEqualsPostal() {
529 $this->individualCreate(['api.address.create' => ['postal_code' => 5, 'location_type_id' => 'Main']]);
530 $this->individualCreate(['api.address.create' => ['postal_code' => 'EH10 4RB-889', 'location_type_id' => 'Main']]);
531 $this->individualCreate(['api.address.create' => ['postal_code' => '4', 'location_type_id' => 'Main']]);
532 $this->individualCreate(['api.address.create' => ['postal_code' => '6', 'location_type_id' => 'Main']]);
534 $params = [['postal_code', '=', 'EH10 4RB-889', 0, 0]];
535 CRM_Contact_BAO_Query
::convertFormValues($params);
537 $query = new CRM_Contact_BAO_Query(
538 $params, ['contact_id'],
539 NULL, TRUE, FALSE, 1,
544 $sql = $query->query(FALSE);
545 $this->assertEquals("WHERE ( civicrm_address.postal_code = 'EH10 4RB-889' ) AND (contact_a.is_deleted = 0)", $sql[2]);
546 $result = CRM_Core_DAO
::executeQuery(implode(' ', $sql));
547 $this->assertEquals(1, $result->N
);
551 public function testRelationshipDescription() {
552 $relType = $this->callAPISuccess('RelationshipType', 'create', [
553 'name_a_b' => uniqid('a'),
554 'name_b_a' => uniqid('b'),
556 $contactID_a = $this->individualCreate([], 1);
557 $contactID_b = $this->individualCreate([], 2);
558 $contactID_c = $this->individualCreate([], 3);
559 $contactID_d = $this->individualCreate([], 4);
560 $desc = uniqid('rel', TRUE);
561 $this->callAPISuccess('Relationship', 'create', [
562 'contact_id_a' => $contactID_a,
563 'contact_id_b' => $contactID_b,
564 'relationship_type_id' => $relType['id'],
566 'description' => $desc,
568 $this->callAPISuccess('Relationship', 'create', [
569 'contact_id_a' => $contactID_c,
570 'contact_id_b' => $contactID_d,
571 'relationship_type_id' => $relType['id'],
573 'description' => 'nothing of interest',
576 ['relation_description', '=', substr($desc, 3, 18), 0, 0],
579 $query = new CRM_Contact_BAO_Query($params);
580 $dao = $query->searchQuery();
581 // This is a little weird but seems consistent with the behavior of the search form in general.
582 // Technically there are 2 contacts who share a relationship with the description searched for,
583 // so one might expect the search form to return both of them instead of just Contact A... but it doesn't.
584 $this->assertEquals('1', $dao->N
, "Search query returns exactly 1 result?");
585 $this->assertTrue($dao->fetch(), "Search query returns success?");
586 $this->assertEquals($contactID_a, $dao->contact_id
, "Search query returns contact A?");
589 public function testNonReciprocalRelationshipTargetGroupIsCorrectResults() {
590 $contactID_a = $this->individualCreate();
591 $contactID_b = $this->individualCreate();
592 $this->callAPISuccess('Relationship', 'create', [
593 'contact_id_a' => $contactID_a,
594 'contact_id_b' => $contactID_b,
595 'relationship_type_id' => 1,
598 // Create a group and add contact A to it.
599 $groupID = $this->groupCreate();
600 $this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $contactID_a, 'status' => 'Added']);
602 // Add another (sans-relationship) contact to the group,
603 $contactID_c = $this->individualCreate();
604 $this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $contactID_c, 'status' => 'Added']);
608 0 => 'relation_type_id',
618 0 => 'relation_target_group',
629 $query = new CRM_Contact_BAO_Query($params);
630 $dao = $query->searchQuery();
631 $this->assertEquals('1', $dao->N
, "Search query returns exactly 1 result?");
632 $this->assertTrue($dao->fetch(), "Search query returns success?");
633 $this->assertEquals($contactID_b, $dao->contact_id
, "Search query returns parent of contact A?");
637 * @throws \CRM_Core_Exception
639 public function testReciprocalRelationshipTargetGroupIsCorrectResults() {
640 $contactID_a = $this->individualCreate();
641 $contactID_b = $this->individualCreate();
642 $this->callAPISuccess('Relationship', 'create', [
643 'contact_id_a' => $contactID_a,
644 'contact_id_b' => $contactID_b,
645 'relationship_type_id' => 2,
648 // Create a group and add contact A to it.
649 $groupID = $this->groupCreate();
650 $this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $contactID_a, 'status' => 'Added']);
652 // Add another (sans-relationship) contact to the group,
653 $contactID_c = $this->individualCreate();
654 $this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $contactID_c, 'status' => 'Added']);
658 0 => 'relation_type_id',
668 0 => 'relation_target_group',
679 $query = new CRM_Contact_BAO_Query($params);
680 $dao = $query->searchQuery();
681 $this->assertEquals('1', $dao->N
, "Search query returns exactly 1 result?");
682 $this->assertTrue($dao->fetch(), "Search query returns success?");
683 $this->assertEquals($contactID_b, $dao->contact_id
, "Search query returns spouse of contact A?");
686 public function testReciprocalRelationshipTargetGroupUsesTempTable() {
687 $groupID = $this->groupCreate();
690 0 => 'relation_type_id',
700 0 => 'relation_target_group',
710 $sql = CRM_Contact_BAO_Query
::getQuery($params);
711 $this->assertContains('INNER JOIN civicrm_tmp_e', $sql, "Query appears to use temporary table of compiled relationships?", TRUE);
714 public function testRelationshipPermissionClause() {
715 $params = [['relation_type_id', 'IN', ['1_b_a'], 0, 0], ['relation_permission', 'IN', [2], 0, 0]];
716 $sql = CRM_Contact_BAO_Query
::getQuery($params);
717 $this->assertContains('(civicrm_relationship.is_permission_a_b IN (2))', $sql);
721 * Test Relationship Clause
723 * @throws \CRM_Core_Exception
725 public function testRelationshipClause() {
726 $today = date('Ymd');
727 $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 )";
728 $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 )";
730 civicrm_relationship.is_active = 1 AND
731 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
732 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
733 ) AND (contact_b.is_deleted = 0) AND civicrm_relationship.relationship_type_id IN (8) ) AND (contact_a.is_deleted = 0)";
735 civicrm_relationship.is_active = 1 AND
736 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
737 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
738 ) AND (contact_b.is_deleted = 0) AND civicrm_relationship.relationship_type_id IN (8,10) ) AND (contact_a.is_deleted = 0)";
739 // Test Traditional single select format
740 $params1 = [['relation_type_id', '=', '8_a_b', 0, 0]];
741 $query1 = new CRM_Contact_BAO_Query(
742 $params1, ['contact_id'],
743 NULL, TRUE, FALSE, 1,
747 $sql1 = $query1->query(FALSE);
748 $this->assertLike($from1, $sql1[1]);
749 $this->assertLike($where1, $sql1[2]);
750 // Test single relationship type selected in multiple select.
751 $params2 = [['relation_type_id', 'IN', ['8_a_b'], 0, 0]];
752 $query2 = new CRM_Contact_BAO_Query(
753 $params2, ['contact_id'],
754 NULL, TRUE, FALSE, 1,
758 $sql2 = $query2->query(FALSE);
759 $this->assertLike($from1, $sql2[1]);
760 $this->assertLike($where1, $sql2[2]);
761 // Test multiple relationship types selected.
762 $params3 = [['relation_type_id', 'IN', ['8_a_b', '10_a_b'], 0, 0]];
763 $query3 = new CRM_Contact_BAO_Query(
764 $params3, ['contact_id'],
765 NULL, TRUE, FALSE, 1,
769 $sql3 = $query3->query(FALSE);
770 $this->assertLike($from1, $sql3[1]);
771 $this->assertLike($where2, $sql3[2]);
772 // Test Multiple Relationship type selected where one doesn't actually exist.
773 $params4 = [['relation_type_id', 'IN', ['8_a_b', '10_a_b', '14_a_b'], 0, 0]];
774 $query4 = new CRM_Contact_BAO_Query(
775 $params4, ['contact_id'],
776 NULL, TRUE, FALSE, 1,
780 $sql4 = $query4->query(FALSE);
781 $this->assertLike($from1, $sql4[1]);
782 $this->assertLike($where2, $sql4[2]);
784 // Test Multiple b to a Relationship type .
785 $params5 = [['relation_type_id', 'IN', ['8_b_a', '10_b_a', '14_b_a'], 0, 0]];
786 $query5 = new CRM_Contact_BAO_Query(
787 $params5, ['contact_id'],
788 NULL, TRUE, FALSE, 1,
792 $sql5 = $query5->query(FALSE);
793 $this->assertLike($from2, $sql5[1]);
794 $this->assertLike($where2, $sql5[2]);
798 * Test we can narrow a group get by status.
800 * @throws \CRM_Core_Exception
802 public function testGetByGroupWithStatus() {
803 $groupID = $this->groupCreate();
804 $this->groupContactCreate($groupID, 3);
805 $groupContactID = $this->callAPISuccessGetSingle('GroupContact', ['group_id' => $groupID, 'options' => ['limit' => 1]])['id'];
806 $this->callAPISuccess('GroupContact', 'create', ['id' => $groupContactID, 'status' => 'Removed']);
807 $queryObj = new CRM_Contact_BAO_Query([['group', '=', $groupID, 0, 0], ['group_contact_status', 'IN', ['Removed' => 1], 0, 0]]);
808 $resultDAO = $queryObj->searchQuery();
809 $this->assertEquals(1, $resultDAO->N
);
811 $queryObj = new CRM_Contact_BAO_Query([['group', '=', $groupID, 0, 0], ['group_contact_status', 'IN', ['Added' => 1], 0, 0]]);
812 $resultDAO = $queryObj->searchQuery();
813 $this->assertEquals(2, $resultDAO->N
);
815 $queryObj = new CRM_Contact_BAO_Query([['group', '=', $groupID, 0, 0]]);
816 $resultDAO = $queryObj->searchQuery();
817 $this->assertEquals(2, $resultDAO->N
);
821 * Test we can narrow a group get by status.
825 public function testGetByGroupWithStatusSmartGroup() {
826 $groupID = $this->smartGroupCreate();
827 // This means they are actually all hard-added, which is fine for this purpose.
828 $this->groupContactCreate($groupID, 3);
829 $groupContactID = $this->callAPISuccessGetSingle('GroupContact', ['group_id' => $groupID, 'options' => ['limit' => 1]])['id'];
830 $this->callAPISuccess('GroupContact', 'create', ['id' => $groupContactID, 'status' => 'Removed']);
832 $queryObj = new CRM_Contact_BAO_Query([['group', '=', $groupID, 0, 0], ['group_contact_status', 'IN', ['Removed' => 1], 0, 0]]);
833 $resultDAO = $queryObj->searchQuery();
834 $this->assertEquals(1, $resultDAO->N
);
838 * Test the group contact clause does not contain an OR.
840 * The search should return 3 contacts - 2 households in the smart group of
841 * Contact Type = Household and one Individual hard-added to it. The
842 * Household that meets both criteria should be returned once.
846 public function testGroupClause() {
847 $this->householdCreate();
848 $householdID = $this->householdCreate();
849 $individualID = $this->individualCreate();
850 $groupID = $this->smartGroupCreate();
851 $this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $individualID, 'status' => 'Added']);
852 $this->callAPISuccess('GroupContact', 'create', ['group_id' => $groupID, 'contact_id' => $householdID, 'status' => 'Added']);
854 // Refresh the cache for test purposes. It would be better to alter to alter the GroupContact add function to add contacts to the cache.
855 CRM_Contact_BAO_GroupContactCache
::clearGroupContactCache($groupID);
857 $sql = CRM_Contact_BAO_Query
::getQuery(
858 [['group', 'IN', [$groupID], 0, 0]],
862 $dao = CRM_Core_DAO
::executeQuery($sql);
863 $this->assertEquals(3, $dao->N
);
864 $this->assertFalse(strstr($sql, ' OR '));
866 $sql = CRM_Contact_BAO_Query
::getQuery(
867 [['group', 'IN', [$groupID], 0, 0]],
868 ['contact_id' => 1, 'group' => 1]
871 $dao = CRM_Core_DAO
::executeQuery($sql);
872 $this->assertEquals(3, $dao->N
);
873 $this->assertFalse(strstr($sql, ' OR '), 'Query does not include or');
874 while ($dao->fetch()) {
875 $this->assertTrue(($dao->groups
== $groupID ||
$dao->groups
== ',' . $groupID), $dao->groups
. ' includes ' . $groupID);
880 * CRM-19562 ensure that only ids are used for contact_id searching.
882 public function testContactIDClause() {
884 ["mark_x_2", "=", 1, 0, 0],
885 ["mark_x_foo@example.com", "=", 1, 0, 0],
887 $returnProperties = [
894 "preferred_mail_format" => 1,
896 $numberOfContacts = 2;
897 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
899 $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberOfContacts);
901 catch (Exception
$e) {
903 "One of parameters (value: foo@example.com) is not of the type Positive",
906 $this->assertTrue(TRUE);
909 $this->fail('Test failed for some reason which is not good');
913 * Test the sorting on the contact ID query works.
915 * Checking for lack of fatal.
917 * @param string $sortOrder
918 * Param reflecting how sort is passed in.
919 * - 1_d is column 1 descending.
921 * @dataProvider getSortOptions
923 public function testContactIDQuery($sortOrder) {
924 $selector = new CRM_Contact_Selector(NULL, ['radio_ts' => 'ts_all'], NULL, ['sort_name' => 1]);
925 $selector->contactIDQuery([], $sortOrder);
929 * Test the sorting on the contact ID query works with a profile search.
931 * Checking for lack of fatal.
933 public function testContactIDQueryProfileSearchResults() {
934 $profile = $this->callAPISuccess('UFGroup', 'create', ['group_type' => 'Contact', 'name' => 'search', 'title' => 'search']);
935 $this->callAPISuccess('UFField', 'create', [
936 'uf_group_id' => $profile['id'],
937 'field_name' => 'postal_code',
938 'field_type' => 'Contact',
939 'in_selector' => TRUE,
940 'is_searchable' => TRUE,
941 'label' => 'postal code',
942 'visibility' => 'Public Pages and Listings',
944 $selector = new CRM_Contact_Selector(NULL, ['radio_ts' => 'ts_all', 'uf_group_id' => $profile['id']], NULL, ['sort_name' => 1]);
945 $selector->contactIDQuery([], '2_d');
949 * Get search options to reflect how a UI search would look.
953 public function getSortOptions() {
965 * Test the summary query does not add an acl clause when acls not enabled..
967 public function testGetSummaryQueryWithFinancialACLDisabled() {
968 $this->createContributionsForSummaryQueryTests();
970 // Test the function directly
971 $where = $from = NULL;
972 $queryObject = new CRM_Contact_BAO_Query();
973 $queryObject->appendFinancialTypeWhereAndFromToQueryStrings($where,
975 $this->assertEquals(NULL, $where);
976 $this->assertEquals(NULL, $from);
978 // Test the function in action
979 $queryObject = new CRM_Contact_BAO_Query([['contribution_source', '=', 'SSF', '', '']]);
980 $summary = $queryObject->summaryContribution();
981 $this->assertEquals([
984 'amount' => '$ 1,400.00',
989 'amount' => '$ 100.00',
996 * Test the summary query accurately adds financial acl filters.
998 public function testGetSummaryQueryWithFinancialACLEnabled() {
999 $where = $from = NULL;
1000 $this->createContributionsForSummaryQueryTests();
1001 $this->enableFinancialACLs();
1002 $this->createLoggedInUserWithFinancialACL();
1004 // Test the function directly
1005 $queryObject = new CRM_Contact_BAO_Query();
1006 $queryObject->appendFinancialTypeWhereAndFromToQueryStrings($where,
1008 $donationTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Donation');
1009 $this->assertEquals(
1010 " LEFT JOIN civicrm_line_item li
1011 ON civicrm_contribution.id = li.contribution_id AND
1012 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN ({$donationTypeID}) ", $from);
1014 // Test the function in action
1015 $queryObject = new CRM_Contact_BAO_Query([['contribution_source', '=', 'SSF', '', '']]);
1016 $summary = $queryObject->summaryContribution();
1017 $this->assertEquals([
1019 'avg' => '$ 200.00',
1020 'amount' => '$ 400.00',
1025 'amount' => '$ 50.00',
1029 $this->disableFinancialACLs();
1033 * Create contributions to test summary calculations.
1035 * financial type | cancel_date |total_amount| source | line_item_financial_types |number_line_items| line_amounts
1036 * Donation |NULL | 100.00 |SSF | Donation | 1 | 100.00
1037 * Member Dues |NULL | 100.00 |SSF | Member Dues | 1 | 100.00
1038 * Donation |NULL | 300.00 |SSF | Event Fee,Event Fee | 2 | 200.00,100.00
1039 * Donation |NULL | 300.00 |SSF | Event Fee,Donation | 2 | 200.00,100.00
1040 * Donation |NULL | 300.00 |SSF | Donation,Donation | 2 | 200.00,100.00
1041 * Donation |2019-02-13 00:00:00 | 50.00 |SSF | Donation | 1 | 50.00
1042 * Member Dues |2019-02-13 00:00:00 | 50.00 |SSF | Member Dues | 1 | 50.00
1044 * @throws \CRM_Core_Exception
1046 protected function createContributionsForSummaryQueryTests() {
1047 $contactID = $this->individualCreate();
1048 $this->contributionCreate(['contact_id' => $contactID]);
1049 $this->contributionCreate([
1050 'contact_id' => $contactID,
1051 'total_amount' => 100,
1052 'financial_type_id' => 'Member Dues',
1054 $eventFeeType = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Event Fee');
1055 $this->createContributionWithTwoLineItemsAgainstPriceSet(['contact_id' => $contactID, 'source' => 'SSF']);
1056 $this->createContributionWithTwoLineItemsAgainstPriceSet(['contact_id' => $contactID, 'source' => 'SSF'], [
1057 CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Donation'),
1060 $this->createContributionWithTwoLineItemsAgainstPriceSet(['contact_id' => $contactID, 'source' => 'SSF'], [
1061 CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Donation'),
1062 CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Donation'),
1064 $this->createContributionWithTwoLineItemsAgainstPriceSet(['contact_id' => $contactID, 'source' => 'SSF', 'financial_type_id' => $eventFeeType], [
1065 CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Donation'),
1066 CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Donation'),
1068 $this->contributionCreate([
1069 'contact_id' => $contactID,
1070 'total_amount' => 50,
1071 'contribution_status_id' => 'Cancelled',
1072 'cancel_date' => 'yesterday',
1074 $this->contributionCreate([
1075 'contact_id' => $contactID,
1076 'total_amount' => 50,
1077 'contribution_status_id' => 'Cancelled',
1078 'cancel_date' => 'yesterday',
1079 'financial_type_id' => 'Member Dues',