3 * File for the CiviUnitTestCase class
7 * @copyright Copyright CiviCRM LLC (C) 2009
8 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html
9 * GNU Affero General Public License version 3
12 * This file is part of CiviCRM
14 * CiviCRM is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Affero General Public License
16 * as published by the Free Software Foundation; either version 3 of
17 * the License, or (at your option) any later version.
19 * CiviCRM is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Affero General Public License for more details.
24 * You should have received a copy of the GNU Affero General Public
25 * License along with this program. If not, see
26 * <http://www.gnu.org/licenses/>.
29 use Civi\Payment\System
;
32 * Include class definitions
34 require_once 'api/api.php';
35 define('API_LATEST_VERSION', 3);
38 * Base class for CiviCRM unit tests
40 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
41 * may opt for one or neither:
43 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
44 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
45 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
46 * 2. useTransaction() executes the test inside a transaction. It's easier to use
47 * (because you don't need to identify specific tables), but it doesn't work for tests
48 * which manipulate schema or truncate data -- and could behave inconsistently
49 * for tests which specifically examine DB transactions.
51 * Common functions for unit tests
54 class CiviUnitTestCase
extends PHPUnit_Extensions_Database_TestCase
{
56 use \Civi\Test\Api3DocTrait
;
59 * Database has been initialized.
63 private static $dbInit = FALSE;
66 * Database connection.
68 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
77 static protected $_dbName;
80 * Track tables we have modified during a test.
82 protected $_tablesToTruncate = array();
85 * @var array of temporary directory names
90 * @var boolean populateOnce allows to skip db resets in setUp
92 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
93 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
96 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
98 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
100 public static $populateOnce = FALSE;
103 * @var boolean DBResetRequired allows skipping DB reset
104 * in specific test case. If you still need
105 * to reset single test (method) of such case, call
106 * $this->cleanDB() in the first line of this
109 public $DBResetRequired = TRUE;
112 * @var CRM_Core_Transaction|NULL
117 * @var CRM_Utils_Hook_UnitTests hookClass
118 * example of setting a method for a hook
119 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
121 public $hookClass = NULL;
124 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
126 protected $_params = array();
129 * @var CRM_Extension_System
131 protected $origExtensionSystem;
134 * Array of IDs created during test setup routine.
136 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
140 public $setupIDs = array();
143 * PHPUnit Mock Mecthod to use.
147 public $mockMethod = 'getMock';
152 * Because we are overriding the parent class constructor, we
153 * need to show the same arguments as exist in the constructor of
154 * PHPUnit_Framework_TestCase, since
155 * PHPUnit_Framework_TestSuite::createTest() creates a
156 * ReflectionClass of the Test class and checks the constructor
157 * of that class to decide how to set up the test.
159 * @param string $name
161 * @param string $dataName
163 public function __construct($name = NULL, array$data = array(), $dataName = '') {
164 parent
::__construct($name, $data, $dataName);
166 // we need full error reporting
167 error_reporting(E_ALL
& ~E_NOTICE
);
169 self
::$_dbName = self
::getDBName();
171 // also load the class loader
172 require_once 'CRM/Core/ClassLoader.php';
173 CRM_Core_ClassLoader
::singleton()->register();
174 if (function_exists('_civix_phpunit_setUp')) {
175 // FIXME: loosen coupling
176 _civix_phpunit_setUp();
178 if (version_compare(PHPUnit_Runner_Version
::id(), '5', '>=')) {
179 $this->mockMethod
= 'createMock';
184 * Override to run the test and assert its state.
187 * @throws \PHPUnit_Framework_IncompleteTest
188 * @throws \PHPUnit_Framework_SkippedTest
190 protected function runTest() {
192 return parent
::runTest();
194 catch (PEAR_Exception
$e) {
195 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
196 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
203 public function requireDBReset() {
204 return $this->DBResetRequired
;
210 public static function getDBName() {
211 static $dbName = NULL;
212 if ($dbName === NULL) {
213 require_once "DB.php";
214 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
215 $dbName = $dsninfo['database'];
221 * Create database connection for this instance.
223 * Initialize the test database if it hasn't been initialized
225 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
227 protected function getConnection() {
228 $dbName = self
::$_dbName;
229 if (!self
::$dbInit) {
230 $dbName = self
::getDBName();
232 // install test database
233 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
235 static::_populateDB(FALSE, $this);
237 self
::$dbInit = TRUE;
240 return $this->createDefaultDBConnection(Civi\Test
::pdo(), $dbName);
244 * Required implementation of abstract method.
246 protected function getDataSet() {
250 * @param bool $perClass
251 * @param null $object
253 * TRUE if the populate logic runs; FALSE if it is skipped
255 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
256 if (CIVICRM_UF
!== 'UnitTests') {
257 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
260 if ($perClass ||
$object == NULL) {
264 $dbreset = $object->requireDBReset();
267 if (self
::$populateOnce ||
!$dbreset) {
270 self
::$populateOnce = NULL;
272 Civi\Test
::data()->populate();
277 public static function setUpBeforeClass() {
278 static::_populateDB(TRUE);
280 // also set this global hack
281 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
285 * Common setup functions for all unit tests.
287 protected function setUp() {
288 $session = CRM_Core_Session
::singleton();
289 $session->set('userID', NULL);
291 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
292 // Use a temporary file for STDIN
293 $GLOBALS['stdin'] = tmpfile();
294 if ($GLOBALS['stdin'] === FALSE) {
295 echo "Couldn't open temporary file\n";
299 // Get and save a connection to the database
300 $this->_dbconn
= $this->getConnection();
302 // reload database before each test
303 // $this->_populateDB();
305 // "initialize" CiviCRM to avoid problems when running single tests
306 // FIXME: look at it closer in second stage
308 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
309 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
311 // disable any left-over test extensions
312 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
314 // reset all the caches
315 CRM_Utils_System
::flushCache();
317 // initialize the object once db is loaded
319 $config = CRM_Core_Config
::singleton(TRUE, TRUE); // ugh, performance
321 // when running unit tests, use mockup user framework
322 $this->hookClass
= CRM_Utils_Hook
::singleton();
324 // Make sure the DB connection is setup properly
325 $config->userSystem
->setMySQLTimeZone();
326 $env = new CRM_Utils_Check_Component_Env();
327 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
329 // clear permissions stub to not check permissions
330 $config->userPermissionClass
->permissions
= NULL;
332 //flush component settings
333 CRM_Core_Component
::getEnabledComponents(TRUE);
335 error_reporting(E_ALL
);
337 $this->_sethtmlGlobals();
341 * Read everything from the datasets directory and insert into the db.
343 public function loadAllFixtures() {
344 $fixturesDir = __DIR__
. '/../../fixtures';
346 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
348 $xmlFiles = glob($fixturesDir . '/*.xml');
349 foreach ($xmlFiles as $xmlFixture) {
350 $op = new PHPUnit_Extensions_Database_Operation_Insert();
351 $dataset = $this->createXMLDataSet($xmlFixture);
352 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
353 $op->execute($this->_dbconn
, $dataset);
356 $yamlFiles = glob($fixturesDir . '/*.yaml');
357 foreach ($yamlFiles as $yamlFixture) {
358 $op = new PHPUnit_Extensions_Database_Operation_Insert();
359 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
360 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
361 $op->execute($this->_dbconn
, $dataset);
364 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
368 * Emulate a logged in user since certain functions use that.
369 * value to store a record in the DB (like activity)
373 * Contact ID of the created user.
375 public function createLoggedInUser() {
377 'first_name' => 'Logged In',
378 'last_name' => 'User ' . rand(),
379 'contact_type' => 'Individual',
381 $contactID = $this->individualCreate($params);
382 $this->callAPISuccess('UFMatch', 'create', array(
383 'contact_id' => $contactID,
384 'uf_name' => 'superman',
388 $session = CRM_Core_Session
::singleton();
389 $session->set('userID', $contactID);
394 * Create default domain contacts for the two domains added during test class.
395 * database population.
397 public function createDomainContacts() {
398 $this->organizationCreate();
399 $this->organizationCreate(array('organization_name' => 'Second Domain'));
403 * Common teardown functions for all unit tests.
405 protected function tearDown() {
406 error_reporting(E_ALL
& ~E_NOTICE
);
407 CRM_Utils_Hook
::singleton()->reset();
408 if ($this->hookClass
) {
409 $this->hookClass
->reset();
411 $session = CRM_Core_Session
::singleton();
412 $session->set('userID', NULL);
415 $this->tx
->rollback()->commit();
418 CRM_Core_Transaction
::forceRollbackIfEnabled();
419 \Civi\Core\Transaction\Manager
::singleton(TRUE);
422 CRM_Core_Transaction
::forceRollbackIfEnabled();
423 \Civi\Core\Transaction\Manager
::singleton(TRUE);
425 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
426 $this->quickCleanup($tablesToTruncate);
427 $this->createDomainContacts();
430 $this->cleanTempDirs();
431 $this->unsetExtensionSystem();
435 * Generic function to compare expected values after an api call to retrieved.
438 * @daoName string DAO Name of object we're evaluating.
439 * @id int Id of object
440 * @match array Associative array of field name => expected value. Empty if asserting
441 * that a DELETE occurred
442 * @delete boolean True if we're checking that a DELETE action occurred.
446 * @param bool $delete
447 * @throws \PHPUnit_Framework_AssertionFailedError
449 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
451 // adding this here since developers forget to check for an id
452 // and hence we get the first value in the db
453 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
456 $object = new $daoName();
460 // If we're asserting successful record deletion, make sure object is NOT found.
462 if ($object->find(TRUE)) {
463 $this->fail("Object not deleted by delete operation: $daoName, $id");
468 // Otherwise check matches of DAO field values against expected values in $match.
469 if ($object->find(TRUE)) {
470 $fields = &$object->fields();
471 foreach ($fields as $name => $value) {
472 $dbName = $value['name'];
473 if (isset($match[$name])) {
475 $this->assertEquals($object->$dbName, $match[$name]);
477 elseif (isset($match[$dbName])) {
479 $this->assertEquals($object->$dbName, $match[$dbName]);
484 $this->fail("Could not retrieve object: $daoName, $id");
487 $matchSize = count($match);
488 if ($verifiedCount != $matchSize) {
489 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
494 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
495 * @param string $daoName
496 * @param $searchValue
497 * @param $returnColumn
498 * @param $searchColumn
501 * @return null|string
502 * @throws PHPUnit_Framework_AssertionFailedError
504 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
505 if (empty($searchValue)) {
506 $this->fail("empty value passed to assertDBNotNull");
508 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
509 $this->assertNotNull($value, $message);
515 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
516 * @param string $daoName
517 * @param $searchValue
518 * @param $returnColumn
519 * @param $searchColumn
522 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
523 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
524 $this->assertNull($value, $message);
528 * Request a record from the DB by id. Success if row not found.
529 * @param string $daoName
531 * @param null $message
533 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
534 $message = $message ?
$message : "$daoName (#$id) should not exist";
535 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
536 $this->assertNull($value, $message);
540 * Request a record from the DB by id. Success if row not found.
541 * @param string $daoName
543 * @param null $message
545 public function assertDBRowExist($daoName, $id, $message = NULL) {
546 $message = $message ?
$message : "$daoName (#$id) should exist";
547 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
548 $this->assertEquals($id, $value, $message);
552 * Compare a single column value in a retrieved DB record to an expected value.
553 * @param string $daoName
554 * @param $searchValue
555 * @param $returnColumn
556 * @param $searchColumn
557 * @param $expectedValue
560 public function assertDBCompareValue(
561 $daoName, $searchValue, $returnColumn, $searchColumn,
562 $expectedValue, $message
564 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
565 $this->assertEquals($expectedValue, $value, $message);
569 * Compare all values in a single retrieved DB record to an array of expected values.
570 * @param string $daoName
571 * @param array $searchParams
572 * @param $expectedValues
574 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
575 //get the values from db
577 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
579 // compare db values with expected values
580 self
::assertAttributesEquals($expectedValues, $dbValues);
584 * Assert that a SQL query returns a given value.
586 * The first argument is an expected value. The remaining arguments are passed
587 * to CRM_Core_DAO::singleValueQuery
589 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
590 * array(1 => array("Whiz", "String")));
593 * @param array $params
594 * @param string $message
596 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
600 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
601 $this->assertEquals($expected, $actual,
602 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
603 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
609 * Assert that two array-trees are exactly equal, notwithstanding
610 * the sorting of keys
612 * @param array $expected
613 * @param array $actual
615 public function assertTreeEquals($expected, $actual) {
618 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
619 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
623 $this->assertEquals($e, $a);
627 * Assert that two numbers are approximately equal.
629 * @param int|float $expected
630 * @param int|float $actual
631 * @param int|float $tolerance
632 * @param string $message
634 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
635 if ($message === NULL) {
636 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
638 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
642 * Assert attributes are equal.
644 * @param $expectedValues
645 * @param $actualValues
646 * @param string $message
648 * @throws PHPUnit_Framework_AssertionFailedError
650 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
651 foreach ($expectedValues as $paramName => $paramValue) {
652 if (isset($actualValues[$paramName])) {
653 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
656 $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
665 public function assertArrayKeyExists($key, &$list) {
666 $result = isset($list[$key]) ?
TRUE : FALSE;
667 $this->assertTrue($result, ts("%1 element exists?",
676 public function assertArrayValueNotNull($key, &$list) {
677 $this->assertArrayKeyExists($key, $list);
679 $value = isset($list[$key]) ?
$list[$key] : NULL;
680 $this->assertTrue($value,
681 ts("%1 element not null?",
690 * @param string $message
692 public function assertType($expected, $actual, $message = '') {
693 return $this->assertInternalType($expected, $actual, $message);
697 * Create a batch of external API calls which can
698 * be executed concurrently.
701 * $calls = $this->createExternalAPI()
702 * ->addCall('Contact', 'get', ...)
703 * ->addCall('Contact', 'get', ...)
709 * @return \Civi\API\ExternalBatch
710 * @throws PHPUnit_Framework_SkippedTestError
712 public function createExternalAPI() {
713 global $civicrm_root;
714 $defaultParams = array(
715 'version' => $this->_apiversion
,
719 $calls = new \Civi\API\
ExternalBatch($defaultParams);
721 if (!$calls->isSupported()) {
722 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
729 * Create required data based on $this->entity & $this->params
730 * This is just a way to set up the test data for delete & get functions
731 * so the distinction between set
732 * up & tested functions is clearer
737 public function createTestEntity() {
738 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
742 * Generic function to create Organisation, to be used in test cases
744 * @param array $params
745 * parameters for civicrm_contact_add api function call
747 * sequence number if creating multiple organizations
750 * id of Organisation created
752 public function organizationCreate($params = array(), $seq = 0) {
756 $params = array_merge($this->sampleContact('Organization', $seq), $params);
757 return $this->_contactCreate($params);
761 * Generic function to create Individual, to be used in test cases
763 * @param array $params
764 * parameters for civicrm_contact_add api function call
766 * sequence number if creating multiple individuals
767 * @param bool $random
770 * id of Individual created
772 public function individualCreate($params = array(), $seq = 0, $random = FALSE) {
773 $params = array_merge($this->sampleContact('Individual', $seq, $random), $params);
774 return $this->_contactCreate($params);
778 * Generic function to create Household, to be used in test cases
780 * @param array $params
781 * parameters for civicrm_contact_add api function call
783 * sequence number if creating multiple households
786 * id of Household created
788 public function householdCreate($params = array(), $seq = 0) {
789 $params = array_merge($this->sampleContact('Household', $seq), $params);
790 return $this->_contactCreate($params);
794 * Helper function for getting sample contact properties.
796 * @param string $contact_type
797 * enum contact type: Individual, Organization
799 * sequence number for the values of this type
802 * properties of sample contact (ie. $params for API call)
804 public function sampleContact($contact_type, $seq = 0, $random = FALSE) {
806 'Individual' => array(
807 // The number of values in each list need to be coprime numbers to not have duplicates
808 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
809 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
810 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
812 'Organization' => array(
813 'organization_name' => array(
814 'Unit Test Organization',
821 'Household' => array(
822 'household_name' => array('Unit Test household'),
825 $params = array('contact_type' => $contact_type);
826 foreach ($samples[$contact_type] as $key => $values) {
827 $params[$key] = $values[$seq %
count($values)];
829 $params[$key] .= substr(sha1(rand()), 0, 5);
832 if ($contact_type == 'Individual') {
833 $params['email'] = strtolower(
834 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
836 $params['prefix_id'] = 3;
837 $params['suffix_id'] = 3;
843 * Private helper function for calling civicrm_contact_add.
845 * @param array $params
846 * For civicrm_contact_add api function call.
851 * id of Household created
853 private function _contactCreate($params) {
854 $result = $this->callAPISuccess('contact', 'create', $params);
855 if (!empty($result['is_error']) ||
empty($result['id'])) {
856 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
858 return $result['id'];
862 * Delete contact, ensuring it is not the domain contact
864 * @param int $contactID
865 * Contact ID to delete
867 public function contactDelete($contactID) {
868 $domain = new CRM_Core_BAO_Domain();
869 $domain->contact_id
= $contactID;
870 if (!$domain->find(TRUE)) {
871 $this->callAPISuccess('contact', 'delete', array(
873 'skip_undelete' => 1,
879 * @param int $contactTypeId
883 public function contactTypeDelete($contactTypeId) {
884 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
886 throw new Exception('Could not delete contact type');
891 * @param array $params
895 public function membershipTypeCreate($params = array()) {
896 CRM_Member_PseudoConstant
::flush('membershipType');
897 CRM_Core_Config
::clearDBCache();
898 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
899 $params = array_merge(array(
901 'duration_unit' => 'year',
902 'duration_interval' => 1,
903 'period_type' => 'rolling',
904 'member_of_contact_id' => $memberOfOrganization,
906 'financial_type_id' => 2,
909 'visibility' => 'Public',
912 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
914 CRM_Member_PseudoConstant
::flush('membershipType');
915 CRM_Utils_Cache
::singleton()->flush();
917 return $result['id'];
921 * @param array $params
925 public function contactMembershipCreate($params) {
926 $params = array_merge(array(
927 'join_date' => '2007-01-21',
928 'start_date' => '2007-01-21',
929 'end_date' => '2007-12-21',
930 'source' => 'Payment',
931 'membership_type_id' => 'General',
933 if (!is_numeric($params['membership_type_id'])) {
934 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
935 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
936 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
940 $result = $this->callAPISuccess('Membership', 'create', $params);
941 return $result['id'];
945 * Delete Membership Type.
947 * @param array $params
949 public function membershipTypeDelete($params) {
950 $this->callAPISuccess('MembershipType', 'Delete', $params);
954 * @param int $membershipID
956 public function membershipDelete($membershipID) {
957 $deleteParams = array('id' => $membershipID);
958 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
962 * @param string $name
966 public function membershipStatusCreate($name = 'test member status') {
967 $params['name'] = $name;
968 $params['start_event'] = 'start_date';
969 $params['end_event'] = 'end_date';
970 $params['is_current_member'] = 1;
971 $params['is_active'] = 1;
973 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
974 CRM_Member_PseudoConstant
::flush('membershipStatus');
975 return $result['id'];
979 * @param int $membershipStatusID
981 public function membershipStatusDelete($membershipStatusID) {
982 if (!$membershipStatusID) {
985 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
988 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
989 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
990 $renewedMembershipEndDate = new DateTime($membershipEndDate);
991 switch ($durationUnit) {
993 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
997 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
998 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
999 $renewedMembershipEndDate->add(new DateInterval('P1D'));
1000 $renewedMembershipEndDate->add(new DateInterval('P1M'));
1001 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
1004 return $renewedMembershipEndDate->format('Y-m-d');
1008 * @param array $params
1012 public function relationshipTypeCreate($params = array()) {
1013 $params = array_merge(array(
1014 'name_a_b' => 'Relation 1 for relationship type create',
1015 'name_b_a' => 'Relation 2 for relationship type create',
1016 'contact_type_a' => 'Individual',
1017 'contact_type_b' => 'Organization',
1024 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1025 CRM_Core_PseudoConstant
::flush('relationshipType');
1027 return $result['id'];
1031 * Delete Relatinship Type.
1033 * @param int $relationshipTypeID
1035 public function relationshipTypeDelete($relationshipTypeID) {
1036 $params['id'] = $relationshipTypeID;
1037 $check = $this->callAPISuccess('relationship_type', 'get', $params);
1038 if (!empty($check['count'])) {
1039 $this->callAPISuccess('relationship_type', 'delete', $params);
1044 * @param array $params
1048 public function paymentProcessorTypeCreate($params = NULL) {
1049 if (is_null($params)) {
1051 'name' => 'API_Test_PP',
1052 'title' => 'API Test Payment Processor',
1053 'class_name' => 'CRM_Core_Payment_APITest',
1054 'billing_mode' => 'form',
1060 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1062 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1064 return $result['id'];
1068 * Create test Authorize.net instance.
1070 * @param array $params
1074 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1075 $params = array_merge(array(
1076 'name' => 'Authorize',
1077 'domain_id' => CRM_Core_Config
::domainID(),
1078 'payment_processor_type_id' => 'AuthNet',
1079 'title' => 'AuthNet',
1084 'user_name' => '4y5BfuW7jm',
1085 'password' => '4cAmW927n8uLf5J8',
1086 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1087 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1088 'class_name' => 'Payment_AuthorizeNet',
1089 'billing_mode' => 1,
1092 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1093 return $result['id'];
1097 * Create Participant.
1099 * @param array $params
1100 * Array of contact id and event id values.
1103 * $id of participant created
1105 public function participantCreate($params = []) {
1106 if (empty($params['contact_id'])) {
1107 $params['contact_id'] = $this->individualCreate();
1109 if (empty($params['event_id'])) {
1110 $event = $this->eventCreate();
1111 $params['event_id'] = $event['id'];
1116 'register_date' => 20070219,
1117 'source' => 'Wimbeldon',
1118 'event_level' => 'Payment',
1122 $params = array_merge($defaults, $params);
1123 $result = $this->callAPISuccess('Participant', 'create', $params);
1124 return $result['id'];
1128 * Create Payment Processor.
1131 * Id Payment Processor
1133 public function processorCreate($params = array()) {
1134 $processorParams = array(
1137 'payment_processor_type_id' => 'Dummy',
1138 'financial_account_id' => 12,
1142 'url_site' => 'http://dummy.com',
1143 'url_recur' => 'http://dummy.com',
1144 'billing_mode' => 1,
1146 'payment_instrument_id' => 'Debit Card',
1148 $processorParams = array_merge($processorParams, $params);
1149 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1150 return $processor['id'];
1154 * Create Payment Processor.
1156 * @param array $processorParams
1158 * @return \CRM_Core_Payment_Dummy
1159 * Instance of Dummy Payment Processor
1161 public function dummyProcessorCreate($processorParams = array()) {
1162 $paymentProcessorID = $this->processorCreate($processorParams);
1163 return System
::singleton()->getById($paymentProcessorID);
1167 * Create contribution page.
1169 * @param array $params
1171 * Array of contribution page
1173 public function contributionPageCreate($params = array()) {
1174 $this->_pageParams
= array_merge(array(
1175 'title' => 'Test Contribution Page',
1176 'financial_type_id' => 1,
1177 'currency' => 'USD',
1178 'financial_account_id' => 1,
1180 'is_allow_other_amount' => 1,
1182 'max_amount' => 1000,
1184 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1188 * Create a sample batch.
1190 public function batchCreate() {
1191 $params = $this->_params
;
1192 $params['name'] = $params['title'] = 'Batch_433397';
1193 $params['status_id'] = 1;
1194 $result = $this->callAPISuccess('batch', 'create', $params);
1195 return $result['id'];
1201 * @param array $params
1203 * result of created tag
1205 public function tagCreate($params = array()) {
1207 'name' => 'New Tag3',
1208 'description' => 'This is description for Our New Tag ',
1211 $params = array_merge($defaults, $params);
1212 $result = $this->callAPISuccess('Tag', 'create', $params);
1213 return $result['values'][$result['id']];
1220 * Id of the tag to be deleted.
1224 public function tagDelete($tagId) {
1225 require_once 'api/api.php';
1229 $result = $this->callAPISuccess('Tag', 'delete', $params);
1230 return $result['id'];
1234 * Add entity(s) to the tag
1236 * @param array $params
1240 public function entityTagAdd($params) {
1241 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1248 * @param array $params
1252 * id of created pledge
1254 public function pledgeCreate($params) {
1255 $params = array_merge(array(
1256 'pledge_create_date' => date('Ymd'),
1257 'start_date' => date('Ymd'),
1258 'scheduled_date' => date('Ymd'),
1260 'pledge_status_id' => '2',
1261 'financial_type_id' => '1',
1262 'pledge_original_installment_amount' => 20,
1263 'frequency_interval' => 5,
1264 'frequency_unit' => 'year',
1265 'frequency_day' => 15,
1266 'installments' => 5,
1270 $result = $this->callAPISuccess('Pledge', 'create', $params);
1271 return $result['id'];
1275 * Delete contribution.
1277 * @param int $pledgeId
1279 public function pledgeDelete($pledgeId) {
1281 'pledge_id' => $pledgeId,
1283 $this->callAPISuccess('Pledge', 'delete', $params);
1287 * Create contribution.
1289 * @param array $params
1290 * Array of parameters.
1293 * id of created contribution
1295 public function contributionCreate($params) {
1297 $params = array_merge(array(
1299 'receive_date' => date('Ymd'),
1300 'total_amount' => 100.00,
1301 'fee_amount' => 5.00,
1302 'financial_type_id' => 1,
1303 'payment_instrument_id' => 1,
1304 'non_deductible_amount' => 10.00,
1306 'invoice_id' => 67890,
1308 'contribution_status_id' => 1,
1311 $result = $this->callAPISuccess('contribution', 'create', $params);
1312 return $result['id'];
1316 * Delete contribution.
1318 * @param int $contributionId
1322 public function contributionDelete($contributionId) {
1324 'contribution_id' => $contributionId,
1326 $result = $this->callAPISuccess('contribution', 'delete', $params);
1333 * @param array $params
1334 * Name-value pair for an event.
1338 public function eventCreate($params = array()) {
1339 // if no contact was passed, make up a dummy event creator
1340 if (!isset($params['contact_id'])) {
1341 $params['contact_id'] = $this->_contactCreate(array(
1342 'contact_type' => 'Individual',
1343 'first_name' => 'Event',
1344 'last_name' => 'Creator',
1348 // set defaults for missing params
1349 $params = array_merge(array(
1350 'title' => 'Annual CiviCRM meet',
1351 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1352 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1353 'event_type_id' => 1,
1355 'start_date' => 20081021,
1356 'end_date' => 20081023,
1357 'is_online_registration' => 1,
1358 'registration_start_date' => 20080601,
1359 'registration_end_date' => 20081015,
1360 'max_participants' => 100,
1361 'event_full_text' => 'Sorry! We are already full',
1364 'is_show_location' => 0,
1367 return $this->callAPISuccess('Event', 'create', $params);
1371 * Create a paid event.
1373 * @param array $params
1377 protected function eventCreatePaid($params) {
1378 $event = $this->eventCreate($params);
1379 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1380 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1381 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1382 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1383 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1395 public function eventDelete($id) {
1399 return $this->callAPISuccess('event', 'delete', $params);
1403 * Delete participant.
1405 * @param int $participantID
1409 public function participantDelete($participantID) {
1411 'id' => $participantID,
1413 $check = $this->callAPISuccess('Participant', 'get', $params);
1414 if ($check['count'] > 0) {
1415 return $this->callAPISuccess('Participant', 'delete', $params);
1420 * Create participant payment.
1422 * @param int $participantID
1423 * @param int $contributionID
1425 * $id of created payment
1427 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1428 //Create Participant Payment record With Values
1430 'participant_id' => $participantID,
1431 'contribution_id' => $contributionID,
1434 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1435 return $result['id'];
1439 * Delete participant payment.
1441 * @param int $paymentID
1443 public function participantPaymentDelete($paymentID) {
1447 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1453 * @param int $contactID
1455 * location id of created location
1457 public function locationAdd($contactID) {
1460 'location_type' => 'New Location Type',
1462 'name' => 'Saint Helier St',
1463 'county' => 'Marin',
1464 'country' => 'UNITED STATES',
1465 'state_province' => 'Michigan',
1466 'supplemental_address_1' => 'Hallmark Ct',
1467 'supplemental_address_2' => 'Jersey Village',
1468 'supplemental_address_3' => 'My Town',
1473 'contact_id' => $contactID,
1474 'address' => $address,
1475 'location_format' => '2.0',
1476 'location_type' => 'New Location Type',
1479 $result = $this->callAPISuccess('Location', 'create', $params);
1484 * Delete Locations of contact.
1486 * @param array $params
1489 public function locationDelete($params) {
1490 $this->callAPISuccess('Location', 'delete', $params);
1494 * Add a Location Type.
1496 * @param array $params
1497 * @return CRM_Core_DAO_LocationType
1498 * location id of created location
1500 public function locationTypeCreate($params = NULL) {
1501 if ($params === NULL) {
1503 'name' => 'New Location Type',
1504 'vcard_name' => 'New Location Type',
1505 'description' => 'Location Type for Delete',
1510 $locationType = new CRM_Core_DAO_LocationType();
1511 $locationType->copyValues($params);
1512 $locationType->save();
1513 // clear getfields cache
1514 CRM_Core_PseudoConstant
::flush();
1515 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1516 return $locationType;
1520 * Delete a Location Type.
1522 * @param int $locationTypeId
1524 public function locationTypeDelete($locationTypeId) {
1525 $locationType = new CRM_Core_DAO_LocationType();
1526 $locationType->id
= $locationTypeId;
1527 $locationType->delete();
1533 * @param array $params
1534 * @return CRM_Core_DAO_Mapping
1535 * Mapping id of created mapping
1537 public function mappingCreate($params = NULL) {
1538 if ($params === NULL) {
1540 'name' => 'Mapping name',
1541 'description' => 'Mapping description',
1542 // 'Export Contact' mapping.
1543 'mapping_type_id' => 7,
1547 $mapping = new CRM_Core_DAO_Mapping();
1548 $mapping->copyValues($params);
1550 // clear getfields cache
1551 CRM_Core_PseudoConstant
::flush();
1552 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1559 * @param int $mappingId
1561 public function mappingDelete($mappingId) {
1562 $mapping = new CRM_Core_DAO_Mapping();
1563 $mapping->id
= $mappingId;
1570 * @param array $params
1572 * groupId of created group
1574 public function groupCreate($params = array()) {
1575 $params = array_merge(array(
1576 'name' => 'Test Group 1',
1578 'title' => 'New Test Group Created',
1579 'description' => 'New Test Group Created',
1581 'visibility' => 'Public Pages',
1582 'group_type' => array(
1588 $result = $this->callAPISuccess('Group', 'create', $params);
1589 return $result['id'];
1593 * Prepare class for ACLs.
1595 protected function prepareForACLs() {
1596 $config = CRM_Core_Config
::singleton();
1597 $config->userPermissionClass
->permissions
= array();
1603 protected function cleanUpAfterACLs() {
1604 CRM_Utils_Hook
::singleton()->reset();
1605 $tablesToTruncate = array(
1607 'civicrm_acl_cache',
1608 'civicrm_acl_entity_role',
1609 'civicrm_acl_contact_cache',
1611 $this->quickCleanup($tablesToTruncate);
1612 $config = CRM_Core_Config
::singleton();
1613 unset($config->userPermissionClass
->permissions
);
1616 * Create a smart group.
1618 * By default it will be a group of households.
1620 * @param array $smartGroupParams
1621 * @param array $groupParams
1624 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1625 $smartGroupParams = array_merge(array(
1626 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1629 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1631 $groupParams['saved_search_id'] = $savedSearch->id
;
1632 return $this->groupCreate($groupParams);
1636 * Function to add a Group.
1638 * @params array to add group
1640 * @param int $groupID
1641 * @param int $totalCount
1642 * @param bool $random
1644 * groupId of created group
1646 public function groupContactCreate($groupID, $totalCount = 10, $random = FALSE) {
1647 $params = array('group_id' => $groupID);
1648 for ($i = 1; $i <= $totalCount; $i++
) {
1649 $contactID = $this->individualCreate(array(), 0, $random);
1651 $params +
= array('contact_id' => $contactID);
1654 $params +
= array("contact_id.$i" => $contactID);
1657 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1667 public function groupDelete($gid) {
1673 $this->callAPISuccess('Group', 'delete', $params);
1678 * @param array $params
1680 public function uFFieldCreate($params = array()) {
1681 $params = array_merge(array(
1683 'field_name' => 'first_name',
1686 'visibility' => 'Public Pages and Listings',
1687 'is_searchable' => '1',
1688 'label' => 'first_name',
1689 'field_type' => 'Individual',
1692 $this->callAPISuccess('uf_field', 'create', $params);
1696 * Add a UF Join Entry.
1698 * @param array $params
1700 * $id of created UF Join
1702 public function ufjoinCreate($params = NULL) {
1703 if ($params === NULL) {
1706 'module' => 'CiviEvent',
1707 'entity_table' => 'civicrm_event',
1713 $result = $this->callAPISuccess('uf_join', 'create', $params);
1718 * Delete a UF Join Entry.
1720 * @param array $params
1721 * with missing uf_group_id
1723 public function ufjoinDelete($params = NULL) {
1724 if ($params === NULL) {
1727 'module' => 'CiviEvent',
1728 'entity_table' => 'civicrm_event',
1731 'uf_group_id' => '',
1735 crm_add_uf_join($params);
1739 * @param array $params
1740 * Optional parameters.
1741 * @param bool $reloadConfig
1742 * While enabling CiviCampaign component, we shouldn't always forcibly
1743 * reload config as this hinder hook call in test environment
1748 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1749 $this->enableCiviCampaign($reloadConfig);
1750 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1751 'name' => 'big_campaign',
1752 'title' => 'Campaign',
1754 return $campaign['id'];
1758 * Create Group for a contact.
1760 * @param int $contactId
1762 public function contactGroupCreate($contactId) {
1764 'contact_id.1' => $contactId,
1768 $this->callAPISuccess('GroupContact', 'Create', $params);
1772 * Delete Group for a contact.
1774 * @param int $contactId
1776 public function contactGroupDelete($contactId) {
1778 'contact_id.1' => $contactId,
1781 $this->civicrm_api('GroupContact', 'Delete', $params);
1787 * @param array $params
1790 public function activityCreate($params = array()) {
1791 $params = array_merge(array(
1792 'subject' => 'Discussion on warm beer',
1793 'activity_date_time' => date('Ymd'),
1794 'duration_hours' => 30,
1795 'duration_minutes' => 20,
1796 'location' => 'Baker Street',
1797 'details' => 'Lets schedule a meeting',
1799 'activity_type_id' => 'Meeting',
1801 if (!isset($params['source_contact_id'])) {
1802 $params['source_contact_id'] = $this->individualCreate();
1804 if (!isset($params['target_contact_id'])) {
1805 $params['target_contact_id'] = $this->individualCreate(array(
1806 'first_name' => 'Julia',
1807 'Last_name' => 'Anderson',
1809 'email' => 'julia_anderson@civicrm.org',
1810 'contact_type' => 'Individual',
1813 if (!isset($params['assignee_contact_id'])) {
1814 $params['assignee_contact_id'] = $params['target_contact_id'];
1817 $result = $this->callAPISuccess('Activity', 'create', $params);
1819 $result['target_contact_id'] = $params['target_contact_id'];
1820 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1825 * Create an activity type.
1827 * @param array $params
1831 public function activityTypeCreate($params) {
1832 return $this->callAPISuccess('ActivityType', 'create', $params);
1836 * Delete activity type.
1838 * @param int $activityTypeId
1839 * Id of the activity type.
1842 public function activityTypeDelete($activityTypeId) {
1843 $params['activity_type_id'] = $activityTypeId;
1844 return $this->callAPISuccess('ActivityType', 'delete', $params);
1848 * Create custom group.
1850 * @param array $params
1853 public function customGroupCreate($params = array()) {
1855 'title' => 'new custom group',
1856 'extends' => 'Contact',
1858 'style' => 'Inline',
1862 $params = array_merge($defaults, $params);
1864 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1865 $this->callAPISuccess('custom_group', 'get', array(
1866 'title' => $params['title'],
1867 array('api.custom_group.delete' => 1),
1870 return $this->callAPISuccess('custom_group', 'create', $params);
1874 * Existing function doesn't allow params to be over-ridden so need a new one
1875 * this one allows you to only pass in the params you want to change
1876 * @param array $params
1879 public function CustomGroupCreateByParams($params = array()) {
1881 'title' => "API Custom Group",
1882 'extends' => 'Contact',
1884 'style' => 'Inline',
1887 $params = array_merge($defaults, $params);
1888 return $this->callAPISuccess('custom_group', 'create', $params);
1892 * Create custom group with multi fields.
1893 * @param array $params
1896 public function CustomGroupMultipleCreateByParams($params = array()) {
1901 $params = array_merge($defaults, $params);
1902 return $this->CustomGroupCreateByParams($params);
1906 * Create custom group with multi fields.
1907 * @param array $params
1910 public function CustomGroupMultipleCreateWithFields($params = array()) {
1911 // also need to pass on $params['custom_field'] if not set but not in place yet
1913 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1914 $ids['custom_group_id'] = $customGroup['id'];
1916 $customField = $this->customFieldCreate(array(
1917 'custom_group_id' => $ids['custom_group_id'],
1918 'label' => 'field_1' . $ids['custom_group_id'],
1922 $ids['custom_field_id'][] = $customField['id'];
1924 $customField = $this->customFieldCreate(array(
1925 'custom_group_id' => $ids['custom_group_id'],
1926 'default_value' => '',
1927 'label' => 'field_2' . $ids['custom_group_id'],
1930 $ids['custom_field_id'][] = $customField['id'];
1932 $customField = $this->customFieldCreate(array(
1933 'custom_group_id' => $ids['custom_group_id'],
1934 'default_value' => '',
1935 'label' => 'field_3' . $ids['custom_group_id'],
1938 $ids['custom_field_id'][] = $customField['id'];
1944 * Create a custom group with a single text custom field. See
1945 * participant:testCreateWithCustom for how to use this
1947 * @param string $function
1949 * @param string $filename
1953 * ids of created objects
1955 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1956 $params = array('title' => $function);
1957 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1958 $params['extends'] = $entity ?
$entity : 'Contact';
1959 $customGroup = $this->CustomGroupCreate($params);
1960 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1961 CRM_Core_PseudoConstant
::flush();
1963 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1967 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1968 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1970 * @param string $function
1972 * @param string $filename
1976 * ids of created objects
1978 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1979 $params = array('title' => $function);
1980 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1981 $params['extends'] = $entity ?
$entity : 'Contact';
1982 $customGroup = $this->CustomGroupCreate($params);
1983 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1984 CRM_Core_PseudoConstant
::flush();
1986 'defaultValue' => 'Default Value',
1987 'lowercasevalue' => 'Lowercase Value',
1988 1 => 'Integer Value',
1990 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1991 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1992 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1993 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1994 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1995 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1996 foreach ($options as $option_value => $option_label) {
1997 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1998 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
2001 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id'], 'custom_field_option_group_id' => $custom_field_api_result['values'][0]['option_group_id'], 'custom_field_group_options' => $options);
2006 * Delete custom group.
2008 * @param int $customGroupID
2012 public function customGroupDelete($customGroupID) {
2013 $params['id'] = $customGroupID;
2014 return $this->callAPISuccess('custom_group', 'delete', $params);
2018 * Create custom field.
2020 * @param array $params
2021 * (custom_group_id) is required.
2024 public function customFieldCreate($params) {
2025 $params = array_merge(array(
2026 'label' => 'Custom Field',
2027 'data_type' => 'String',
2028 'html_type' => 'Text',
2029 'is_searchable' => 1,
2031 'default_value' => 'defaultValue',
2034 $result = $this->callAPISuccess('custom_field', 'create', $params);
2035 // these 2 functions are called with force to flush static caches
2036 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
2037 CRM_Core_Component
::getEnabledComponents(1);
2042 * Delete custom field.
2044 * @param int $customFieldID
2048 public function customFieldDelete($customFieldID) {
2050 $params['id'] = $customFieldID;
2051 return $this->callAPISuccess('custom_field', 'delete', $params);
2060 public function noteCreate($cId) {
2062 'entity_table' => 'civicrm_contact',
2063 'entity_id' => $cId,
2064 'note' => 'hello I am testing Note',
2065 'contact_id' => $cId,
2066 'modified_date' => date('Ymd'),
2067 'subject' => 'Test Note',
2070 return $this->callAPISuccess('Note', 'create', $params);
2074 * Enable CiviCampaign Component.
2076 * @param bool $reloadConfig
2077 * Force relaod config or not
2079 public function enableCiviCampaign($reloadConfig = TRUE) {
2080 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2081 if ($reloadConfig) {
2082 // force reload of config object
2083 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2085 //flush cache by calling with reset
2086 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2090 * Create custom field with Option Values.
2092 * @param array $customGroup
2093 * @param string $name
2094 * Name of custom field.
2095 * @param array $extraParams
2096 * Additional parameters to pass through.
2100 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
2101 $fieldParams = array(
2102 'custom_group_id' => $customGroup['id'],
2103 'name' => 'test_custom_group',
2104 'label' => 'Country',
2105 'html_type' => 'Select',
2106 'data_type' => 'String',
2109 'is_searchable' => 0,
2113 $optionGroup = array(
2115 'name' => 'option_group1',
2116 'label' => 'option_group_label1',
2119 $optionValue = array(
2120 'option_label' => array('Label1', 'Label2'),
2121 'option_value' => array('value1', 'value2'),
2122 'option_name' => array($name . '_1', $name . '_2'),
2123 'option_weight' => array(1, 2),
2124 'option_status' => 1,
2127 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
2129 return $this->callAPISuccess('custom_field', 'create', $params);
2137 public function confirmEntitiesDeleted($entities) {
2138 foreach ($entities as $entity) {
2140 $result = $this->callAPISuccess($entity, 'Get', array());
2141 if ($result['error'] == 1 ||
$result['count'] > 0) {
2142 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2150 * Quick clean by emptying tables created for the test.
2152 * @param array $tablesToTruncate
2153 * @param bool $dropCustomValueTables
2154 * @throws \Exception
2156 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2158 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2160 if ($dropCustomValueTables) {
2161 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2162 while ($optionGroupResult->fetch()) {
2163 if (!empty($optionGroupResult->option_group_id
)) {
2164 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
2167 $tablesToTruncate[] = 'civicrm_custom_group';
2168 $tablesToTruncate[] = 'civicrm_custom_field';
2171 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2173 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2174 foreach ($tablesToTruncate as $table) {
2175 $sql = "TRUNCATE TABLE $table";
2176 CRM_Core_DAO
::executeQuery($sql);
2178 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2180 if ($dropCustomValueTables) {
2181 $dbName = self
::getDBName();
2183 SELECT TABLE_NAME as tableName
2184 FROM INFORMATION_SCHEMA.TABLES
2185 WHERE TABLE_SCHEMA = '{$dbName}'
2186 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2189 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2190 while ($tableDAO->fetch()) {
2191 $sql = "DROP TABLE {$tableDAO->tableName}";
2192 CRM_Core_DAO
::executeQuery($sql);
2198 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2200 public function quickCleanUpFinancialEntities() {
2201 $tablesToTruncate = array(
2203 'civicrm_activity_contact',
2204 'civicrm_contribution',
2205 'civicrm_contribution_soft',
2206 'civicrm_contribution_product',
2207 'civicrm_financial_trxn',
2208 'civicrm_financial_item',
2209 'civicrm_contribution_recur',
2210 'civicrm_line_item',
2211 'civicrm_contribution_page',
2212 'civicrm_payment_processor',
2213 'civicrm_entity_financial_trxn',
2214 'civicrm_membership',
2215 'civicrm_membership_type',
2216 'civicrm_membership_payment',
2217 'civicrm_membership_log',
2218 'civicrm_membership_block',
2220 'civicrm_participant',
2221 'civicrm_participant_payment',
2223 'civicrm_pledge_payment',
2224 'civicrm_price_set_entity',
2225 'civicrm_price_field_value',
2226 'civicrm_price_field',
2228 $this->quickCleanup($tablesToTruncate);
2229 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2230 $this->restoreDefaultPriceSetConfig();
2232 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2233 $this->disableTaxAndInvoicing();
2234 $this->setCurrencySeparators(',');
2235 CRM_Core_PseudoConstant
::flush('taxRates');
2236 System
::singleton()->flushProcessors();
2239 public function restoreDefaultPriceSetConfig() {
2240 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
2241 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
2242 CRM_Core_DAO
::executeQuery("INSERT INTO `civicrm_price_field` (`id`, `price_set_id`, `name`, `label`, `html_type`, `is_enter_qty`, `help_pre`, `help_post`, `weight`, `is_display_amounts`, `options_per_line`, `is_active`, `is_required`, `active_on`, `expire_on`, `javascript`, `visibility_id`) VALUES (1, 1, 'contribution_amount', 'Contribution Amount', 'Text', 0, NULL, NULL, 1, 1, 1, 1, 1, NULL, NULL, NULL, 1)");
2243 CRM_Core_DAO
::executeQuery("INSERT INTO `civicrm_price_field_value` (`id`, `price_field_id`, `name`, `label`, `description`, `amount`, `count`, `max_value`, `weight`, `membership_type_id`, `membership_num_terms`, `is_default`, `is_active`, `financial_type_id`, `non_deductible_amount`) VALUES (1, 1, 'contribution_amount', 'Contribution Amount', NULL, '1', NULL, NULL, 1, NULL, NULL, 0, 1, 1, 0.00)");
2246 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2247 * Default behaviour is to also delete the entity
2248 * @param array $params
2249 * Params array to check against.
2251 * Id of the entity concerned.
2252 * @param string $entity
2253 * Name of entity concerned (e.g. membership).
2254 * @param bool $delete
2255 * Should the entity be deleted as part of this check.
2256 * @param string $errorText
2257 * Text to print on error.
2260 * @param array $params
2263 * @param int $delete
2264 * @param string $errorText
2268 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2270 $result = $this->callAPISuccessGetSingle($entity, array(
2275 $this->callAPISuccess($entity, 'Delete', array(
2279 $dateFields = $keys = $dateTimeFields = array();
2280 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2281 foreach ($fields['values'] as $field => $settings) {
2282 if (array_key_exists($field, $result)) {
2283 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2286 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2288 $type = CRM_Utils_Array
::value('type', $settings);
2289 if ($type == CRM_Utils_Type
::T_DATE
) {
2290 $dateFields[] = $settings['name'];
2291 // we should identify both real names & unique names as dates
2292 if ($field != $settings['name']) {
2293 $dateFields[] = $field;
2296 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2297 $dateTimeFields[] = $settings['name'];
2298 // we should identify both real names & unique names as dates
2299 if ($field != $settings['name']) {
2300 $dateTimeFields[] = $field;
2305 if (strtolower($entity) == 'contribution') {
2306 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2307 // this is not returned in id format
2308 unset($params['payment_instrument_id']);
2309 $params['contribution_source'] = $params['source'];
2310 unset($params['source']);
2313 foreach ($params as $key => $value) {
2314 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2317 if (in_array($key, $dateFields)) {
2318 $value = date('Y-m-d', strtotime($value));
2319 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2321 if (in_array($key, $dateTimeFields)) {
2322 $value = date('Y-m-d H:i:s', strtotime($value));
2323 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2325 $this->assertEquals($value, $result[$keys[$key]], $key . " GetandCheck function determines that for key {$key} value: $value doesn't match " . print_r($result[$keys[$key]], TRUE) . $errorText);
2330 * Get formatted values in the actual and expected result.
2331 * @param array $actual
2332 * Actual calculated values.
2333 * @param array $expected
2336 public function checkArrayEquals(&$actual, &$expected) {
2337 self
::unsetId($actual);
2338 self
::unsetId($expected);
2339 $this->assertEquals($actual, $expected);
2343 * Unset the key 'id' from the array
2344 * @param array $unformattedArray
2345 * The array from which the 'id' has to be unset.
2347 public static function unsetId(&$unformattedArray) {
2348 $formattedArray = array();
2349 if (array_key_exists('id', $unformattedArray)) {
2350 unset($unformattedArray['id']);
2352 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2353 foreach ($unformattedArray['values'] as $key => $value) {
2354 if (is_array($value)) {
2355 foreach ($value as $k => $v) {
2361 elseif ($key == 'id') {
2362 $unformattedArray[$key];
2364 $formattedArray = array($value);
2366 $unformattedArray['values'] = $formattedArray;
2371 * Helper to enable/disable custom directory support
2373 * @param array $customDirs
2375 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2376 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2378 public function customDirectories($customDirs) {
2379 $config = CRM_Core_Config
::singleton();
2381 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2382 unset($config->customPHPPathDir
);
2384 elseif ($customDirs['php_path'] === TRUE) {
2385 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2388 $config->customPHPPathDir
= $php_path;
2391 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2392 unset($config->customTemplateDir
);
2394 elseif ($customDirs['template_path'] === TRUE) {
2395 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2398 $config->customTemplateDir
= $template_path;
2403 * Generate a temporary folder.
2405 * @param string $prefix
2408 public function createTempDir($prefix = 'test-') {
2409 $tempDir = CRM_Utils_File
::tempdir($prefix);
2410 $this->tempDirs
[] = $tempDir;
2414 public function cleanTempDirs() {
2415 if (!is_array($this->tempDirs
)) {
2416 // fix test errors where this is not set
2419 foreach ($this->tempDirs
as $tempDir) {
2420 if (is_dir($tempDir)) {
2421 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2427 * Temporarily replace the singleton extension with a different one.
2428 * @param \CRM_Extension_System $system
2430 public function setExtensionSystem(CRM_Extension_System
$system) {
2431 if ($this->origExtensionSystem
== NULL) {
2432 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2434 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2437 public function unsetExtensionSystem() {
2438 if ($this->origExtensionSystem
!== NULL) {
2439 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2440 $this->origExtensionSystem
= NULL;
2445 * Temporarily alter the settings-metadata to add a mock setting.
2447 * WARNING: The setting metadata will disappear on the next cache-clear.
2452 public function setMockSettingsMetaData($extras) {
2453 Civi
::service('settings_manager')->flush();
2455 CRM_Utils_Hook
::singleton()
2456 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2457 $metadata = array_merge($metadata, $extras);
2460 $fields = $this->callAPISuccess('setting', 'getfields', array());
2461 foreach ($extras as $key => $spec) {
2462 $this->assertNotEmpty($spec['title']);
2463 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2468 * @param string $name
2470 public function financialAccountDelete($name) {
2471 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2472 $financialAccount->name
= $name;
2473 if ($financialAccount->find(TRUE)) {
2474 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2475 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2476 $entityFinancialType->delete();
2477 $financialAccount->delete();
2482 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2483 * (NB unclear if this is still required)
2485 public function _sethtmlGlobals() {
2486 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2487 'required' => array(
2488 'html_quickform_rule_required',
2489 'HTML/QuickForm/Rule/Required.php',
2491 'maxlength' => array(
2492 'html_quickform_rule_range',
2493 'HTML/QuickForm/Rule/Range.php',
2495 'minlength' => array(
2496 'html_quickform_rule_range',
2497 'HTML/QuickForm/Rule/Range.php',
2499 'rangelength' => array(
2500 'html_quickform_rule_range',
2501 'HTML/QuickForm/Rule/Range.php',
2504 'html_quickform_rule_email',
2505 'HTML/QuickForm/Rule/Email.php',
2508 'html_quickform_rule_regex',
2509 'HTML/QuickForm/Rule/Regex.php',
2511 'lettersonly' => array(
2512 'html_quickform_rule_regex',
2513 'HTML/QuickForm/Rule/Regex.php',
2515 'alphanumeric' => array(
2516 'html_quickform_rule_regex',
2517 'HTML/QuickForm/Rule/Regex.php',
2520 'html_quickform_rule_regex',
2521 'HTML/QuickForm/Rule/Regex.php',
2523 'nopunctuation' => array(
2524 'html_quickform_rule_regex',
2525 'HTML/QuickForm/Rule/Regex.php',
2528 'html_quickform_rule_regex',
2529 'HTML/QuickForm/Rule/Regex.php',
2531 'callback' => array(
2532 'html_quickform_rule_callback',
2533 'HTML/QuickForm/Rule/Callback.php',
2536 'html_quickform_rule_compare',
2537 'HTML/QuickForm/Rule/Compare.php',
2540 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2541 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2543 'HTML/QuickForm/group.php',
2544 'HTML_QuickForm_group',
2547 'HTML/QuickForm/hidden.php',
2548 'HTML_QuickForm_hidden',
2551 'HTML/QuickForm/reset.php',
2552 'HTML_QuickForm_reset',
2554 'checkbox' => array(
2555 'HTML/QuickForm/checkbox.php',
2556 'HTML_QuickForm_checkbox',
2559 'HTML/QuickForm/file.php',
2560 'HTML_QuickForm_file',
2563 'HTML/QuickForm/image.php',
2564 'HTML_QuickForm_image',
2566 'password' => array(
2567 'HTML/QuickForm/password.php',
2568 'HTML_QuickForm_password',
2571 'HTML/QuickForm/radio.php',
2572 'HTML_QuickForm_radio',
2575 'HTML/QuickForm/button.php',
2576 'HTML_QuickForm_button',
2579 'HTML/QuickForm/submit.php',
2580 'HTML_QuickForm_submit',
2583 'HTML/QuickForm/select.php',
2584 'HTML_QuickForm_select',
2586 'hiddenselect' => array(
2587 'HTML/QuickForm/hiddenselect.php',
2588 'HTML_QuickForm_hiddenselect',
2591 'HTML/QuickForm/text.php',
2592 'HTML_QuickForm_text',
2594 'textarea' => array(
2595 'HTML/QuickForm/textarea.php',
2596 'HTML_QuickForm_textarea',
2598 'fckeditor' => array(
2599 'HTML/QuickForm/fckeditor.php',
2600 'HTML_QuickForm_FCKEditor',
2603 'HTML/QuickForm/tinymce.php',
2604 'HTML_QuickForm_TinyMCE',
2606 'dojoeditor' => array(
2607 'HTML/QuickForm/dojoeditor.php',
2608 'HTML_QuickForm_dojoeditor',
2611 'HTML/QuickForm/link.php',
2612 'HTML_QuickForm_link',
2614 'advcheckbox' => array(
2615 'HTML/QuickForm/advcheckbox.php',
2616 'HTML_QuickForm_advcheckbox',
2619 'HTML/QuickForm/date.php',
2620 'HTML_QuickForm_date',
2623 'HTML/QuickForm/static.php',
2624 'HTML_QuickForm_static',
2627 'HTML/QuickForm/header.php',
2628 'HTML_QuickForm_header',
2631 'HTML/QuickForm/html.php',
2632 'HTML_QuickForm_html',
2634 'hierselect' => array(
2635 'HTML/QuickForm/hierselect.php',
2636 'HTML_QuickForm_hierselect',
2638 'autocomplete' => array(
2639 'HTML/QuickForm/autocomplete.php',
2640 'HTML_QuickForm_autocomplete',
2643 'HTML/QuickForm/xbutton.php',
2644 'HTML_QuickForm_xbutton',
2646 'advmultiselect' => array(
2647 'HTML/QuickForm/advmultiselect.php',
2648 'HTML_QuickForm_advmultiselect',
2654 * Set up an acl allowing contact to see 2 specified groups
2655 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2657 * You need to have pre-created these groups & created the user e.g
2658 * $this->createLoggedInUser();
2659 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2660 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2662 * @param bool $isProfile
2664 public function setupACL($isProfile = FALSE) {
2666 $_REQUEST = $this->_params
;
2668 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2669 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2670 $ov = new CRM_Core_DAO_OptionValue();
2671 $ov->option_group_id
= $optionGroupID;
2673 if ($ov->find(TRUE)) {
2674 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2676 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2677 'option_group_id' => $optionGroupID,
2678 'label' => 'pick me',
2682 CRM_Core_DAO
::executeQuery("
2683 TRUNCATE civicrm_acl_cache
2686 CRM_Core_DAO
::executeQuery("
2687 TRUNCATE civicrm_acl_contact_cache
2690 CRM_Core_DAO
::executeQuery("
2691 INSERT INTO civicrm_acl_entity_role (
2692 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2693 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2697 CRM_Core_DAO
::executeQuery("
2698 INSERT INTO civicrm_acl (
2699 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2702 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2707 CRM_Core_DAO
::executeQuery("
2708 INSERT INTO civicrm_acl (
2709 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2712 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2716 CRM_Core_DAO
::executeQuery("
2717 INSERT INTO civicrm_acl (
2718 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2721 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2726 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2727 $this->callAPISuccess('group_contact', 'create', array(
2728 'group_id' => $this->_permissionedGroup
,
2729 'contact_id' => $this->_loggedInUser
,
2734 CRM_ACL_BAO_Cache
::resetCache();
2735 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2740 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2742 public function offsetDefaultPriceSet() {
2743 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2744 $firstID = $contributionPriceSet['id'];
2745 $this->callAPISuccess('price_set', 'create', array(
2746 'id' => $contributionPriceSet['id'],
2750 unset($contributionPriceSet['id']);
2751 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2752 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2753 'price_set_id' => $firstID,
2754 'options' => array('limit' => 1),
2756 unset($priceField['id']);
2757 $priceField['price_set_id'] = $newPriceSet['id'];
2758 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2759 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2760 'price_set_id' => $firstID,
2762 'options' => array('limit' => 1),
2765 unset($priceFieldValue['id']);
2766 //create some padding to use up ids
2767 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2768 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2769 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2773 * Create an instance of the paypal processor.
2774 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2775 * this parent class & we don't have a structure for that yet
2776 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2777 * & the best protection against that is the functions this class affords
2778 * @param array $params
2779 * @return int $result['id'] payment processor id
2781 public function paymentProcessorCreate($params = array()) {
2782 $params = array_merge(array(
2784 'domain_id' => CRM_Core_Config
::domainID(),
2785 'payment_processor_type_id' => 'PayPal',
2789 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2790 'password' => '1183377788',
2791 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2792 'url_site' => 'https://www.sandbox.paypal.com/',
2793 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2794 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2795 'class_name' => 'Payment_PayPalImpl',
2796 'billing_mode' => 3,
2797 'financial_type_id' => 1,
2798 'financial_account_id' => 12,
2799 // Credit card = 1 so can pass 'by accident'.
2800 'payment_instrument_id' => 'Debit Card',
2803 if (!is_numeric($params['payment_processor_type_id'])) {
2804 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2806 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2807 'name' => $params['payment_processor_type_id'],
2811 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2812 return $result['id'];
2816 * Set up initial recurring payment allowing subsequent IPN payments.
2818 * @param array $recurParams (Optional)
2819 * @param array $contributionParams (Optional)
2821 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2822 $contributionParams = array_merge([
2823 'total_amount' => '200',
2824 'invoice_id' => $this->_invoiceID
,
2825 'financial_type_id' => 'Donation',
2826 'contribution_status_id' => 'Pending',
2827 'contact_id' => $this->_contactID
,
2828 'contribution_page_id' => $this->_contributionPageID
,
2829 'payment_processor_id' => $this->_paymentProcessorID
,
2831 'skipCleanMoney' => TRUE,
2835 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2836 'contact_id' => $this->_contactID
,
2839 'installments' => 5,
2840 'frequency_unit' => 'Month',
2841 'frequency_interval' => 1,
2842 'invoice_id' => $this->_invoiceID
,
2843 'contribution_status_id' => 2,
2844 'payment_processor_id' => $this->_paymentProcessorID
,
2845 // processor provided ID - use contact ID as proxy.
2846 'processor_id' => $this->_contactID
,
2847 'api.contribution.create' => $contributionParams,
2849 $this->_contributionRecurID
= $contributionRecur['id'];
2850 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2854 * We don't have a good way to set up a recurring contribution with a membership so let's just do one then alter it
2856 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2858 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2859 $membershipParams = $recurParams = array();
2860 if (!empty($params['duration_unit'])) {
2861 $membershipParams['duration_unit'] = $params['duration_unit'];
2863 if (!empty($params['frequency_unit'])) {
2864 $recurParams['frequency_unit'] = $params['frequency_unit'];
2867 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2868 //create a contribution so our membership & contribution don't both have id = 1
2869 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2870 $this->contributionCreate(array(
2871 'contact_id' => $this->_contactID
,
2873 'financial_type_id' => 1,
2874 'invoice_id' => 'abcd',
2878 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2880 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2881 'contact_id' => $this->_contactID
,
2882 'membership_type_id' => $this->ids
['membership_type'],
2883 'contribution_recur_id' => $this->_contributionRecurID
,
2884 'format.only_id' => TRUE,
2886 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2887 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2889 $this->callAPISuccess('line_item', 'create', array(
2890 'entity_table' => 'civicrm_membership',
2891 'entity_id' => $this->ids
['membership'],
2892 'contribution_id' => $this->_contributionID
,
2893 'label' => 'General',
2895 'unit_price' => 200,
2896 'line_total' => 200,
2897 'financial_type_id' => 1,
2898 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2900 'label' => 'Membership Amount',
2901 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2903 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2905 'label' => 'General',
2906 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2909 $this->callAPISuccess('membership_payment', 'create', array(
2910 'contribution_id' => $this->_contributionID
,
2911 'membership_id' => $this->ids
['membership'],
2920 public function CiviUnitTestCase_fatalErrorHandler($message) {
2921 throw new Exception("{$message['message']}: {$message['code']}");
2925 * Helper function to create new mailing.
2927 * @param array $params
2931 public function createMailing($params = array()) {
2932 $params = array_merge(array(
2933 'subject' => 'maild' . rand(),
2934 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
2935 'name' => 'mailing name' . rand(),
2939 $result = $this->callAPISuccess('Mailing', 'create', $params);
2940 return $result['id'];
2944 * Helper function to delete mailing.
2947 public function deleteMailing($id) {
2952 $this->callAPISuccess('Mailing', 'delete', $params);
2956 * Wrap the entire test case in a transaction.
2958 * Only subsequent DB statements will be wrapped in TX -- this cannot
2959 * retroactively wrap old DB statements. Therefore, it makes sense to
2960 * call this at the beginning of setUp().
2962 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2963 * this option does not work with, e.g., custom-data.
2965 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2966 * if TRUNCATE or ALTER is called while using a transaction.
2969 * Whether to use nesting or reference-counting.
2971 public function useTransaction($nest = TRUE) {
2973 $this->tx
= new CRM_Core_Transaction($nest);
2974 $this->tx
->rollback();
2979 * Assert the attachment exists.
2981 * @param bool $exists
2982 * @param array $apiResult
2984 protected function assertAttachmentExistence($exists, $apiResult) {
2985 $fileId = $apiResult['id'];
2986 $this->assertTrue(is_numeric($fileId));
2987 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2988 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2989 1 => array($fileId, 'Int'),
2991 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2992 1 => array($fileId, 'Int'),
2997 * Create a price set for an event.
2999 * @param int $feeTotal
3000 * @param int $minAmt
3001 * @param string $type
3006 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
3007 // creating price set, price field
3008 $paramsSet['title'] = 'Price Set';
3009 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
3010 $paramsSet['is_active'] = FALSE;
3011 $paramsSet['extends'] = 1;
3012 $paramsSet['min_amount'] = $minAmt;
3014 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
3015 $this->_ids
['price_set'] = $priceSet->id
;
3017 $paramsField = array(
3018 'label' => 'Price Field',
3019 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3020 'html_type' => $type,
3021 'price' => $feeTotal,
3022 'option_label' => array('1' => 'Price Field'),
3023 'option_value' => array('1' => $feeTotal),
3024 'option_name' => array('1' => $feeTotal),
3025 'option_weight' => array('1' => 1),
3026 'option_amount' => array('1' => 1),
3027 'is_display_amounts' => 1,
3029 'options_per_line' => 1,
3030 'is_active' => array('1' => 1),
3031 'price_set_id' => $this->_ids
['price_set'],
3032 'is_enter_qty' => 1,
3033 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3035 if ($type === 'Radio') {
3036 $paramsField['is_enter_qty'] = 0;
3037 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
3038 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
3040 CRM_Price_BAO_PriceField
::create($paramsField);
3041 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
3042 $this->_ids
['price_field'] = array_keys($fields['values']);
3043 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
3044 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
3046 return $this->_ids
['price_set'];
3050 * Add a profile to a contribution page.
3052 * @param string $name
3053 * @param int $contributionPageID
3054 * @param string $module
3056 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
3058 'uf_group_id' => $name,
3059 'module' => $module,
3060 'entity_table' => 'civicrm_contribution_page',
3061 'entity_id' => $contributionPageID,
3064 if ($module !== 'CiviContribute') {
3065 $params['module_data'] = [$module => []];
3067 $this->callAPISuccess('UFJoin', 'create', $params);
3071 * Add participant with contribution
3075 protected function createParticipantWithContribution() {
3076 // creating price set, price field
3077 $this->_contactId
= $this->individualCreate();
3078 $event = $this->eventCreate();
3079 $this->_eventId
= $event['id'];
3080 $eventParams = array(
3081 'id' => $this->_eventId
,
3082 'financial_type_id' => 4,
3085 $this->callAPISuccess('event', 'create', $eventParams);
3086 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3087 $participantParams = array(
3088 'financial_type_id' => 4,
3089 'event_id' => $this->_eventId
,
3092 'fee_currency' => 'USD',
3093 'contact_id' => $this->_contactId
,
3095 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3096 $contributionParams = array(
3097 'total_amount' => 150,
3098 'currency' => 'USD',
3099 'contact_id' => $this->_contactId
,
3100 'financial_type_id' => 4,
3101 'contribution_status_id' => 1,
3102 'partial_payment_total' => 300.00,
3103 'partial_amount_to_pay' => 150,
3104 'contribution_mode' => 'participant',
3105 'participant_id' => $participant['id'],
3107 foreach ($priceFields['values'] as $key => $priceField) {
3108 $lineItems[1][$key] = array(
3109 'price_field_id' => $priceField['price_field_id'],
3110 'price_field_value_id' => $priceField['id'],
3111 'label' => $priceField['label'],
3112 'field_title' => $priceField['label'],
3114 'unit_price' => $priceField['amount'],
3115 'line_total' => $priceField['amount'],
3116 'financial_type_id' => $priceField['financial_type_id'],
3119 $contributionParams['line_item'] = $lineItems;
3120 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3121 $paymentParticipant = array(
3122 'participant_id' => $participant['id'],
3123 'contribution_id' => $contribution['id'],
3125 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3126 return array($lineItems, $contribution);
3132 * @param string $component
3133 * @param int $componentId
3137 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
3138 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
3139 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
3140 $paramsSet['is_active'] = TRUE;
3141 $paramsSet['financial_type_id'] = 4;
3142 $paramsSet['extends'] = 1;
3143 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3144 $priceSetId = $priceSet['id'];
3145 //Checking for priceset added in the table.
3146 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3147 'id', $paramsSet['title'], 'Check DB for created priceset'
3149 $paramsField = array_merge(array(
3150 'label' => 'Price Field',
3151 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3152 'html_type' => 'CheckBox',
3153 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3154 'option_value' => array('1' => 100, '2' => 200),
3155 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3156 'option_weight' => array('1' => 1, '2' => 2),
3157 'option_amount' => array('1' => 100, '2' => 200),
3158 'is_display_amounts' => 1,
3160 'options_per_line' => 1,
3161 'is_active' => array('1' => 1, '2' => 1),
3162 'price_set_id' => $priceSet['id'],
3163 'is_enter_qty' => 1,
3164 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3165 ), $priceFieldOptions);
3167 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
3169 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
3171 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
3175 * Replace the template with a test-oriented template designed to show all the variables.
3177 * @param string $templateName
3179 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
3180 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
3181 CRM_Core_DAO
::executeQuery(
3182 "UPDATE civicrm_option_group og
3183 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3184 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3185 SET m.msg_html = '{$testTemplate}'
3186 WHERE og.name = 'msg_tpl_workflow_contribution'
3187 AND ov.name = '{$templateName}'
3188 AND m.is_default = 1"
3193 * Reinstate the default template.
3195 * @param string $templateName
3197 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
3198 CRM_Core_DAO
::executeQuery(
3199 "UPDATE civicrm_option_group og
3200 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3201 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3202 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
3203 SET m.msg_html = m2.msg_html
3204 WHERE og.name = 'msg_tpl_workflow_contribution'
3205 AND ov.name = '{$templateName}'
3206 AND m.is_default = 1"
3211 * Flush statics relating to financial type.
3213 protected function flushFinancialTypeStatics() {
3214 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
3215 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
3217 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
3218 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
3220 CRM_Contribute_PseudoConstant
::flush('financialType');
3221 CRM_Contribute_PseudoConstant
::flush('membershipType');
3222 // Pseudoconstants may be saved to the cache table.
3223 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
3224 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
3225 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
3229 * Set the permissions to the supplied array.
3231 * @param array $permissions
3233 protected function setPermissions($permissions) {
3234 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
3235 $this->flushFinancialTypeStatics();
3239 * @param array $params
3242 public function _checkFinancialRecords($params, $context) {
3243 $entityParams = array(
3244 'entity_id' => $params['id'],
3245 'entity_table' => 'civicrm_contribution',
3247 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3248 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3249 if ($context == 'pending') {
3250 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
3251 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3254 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3255 $trxnParams = array(
3256 'id' => $trxn['financial_trxn_id'],
3258 if ($context != 'online' && $context != 'payLater') {
3259 $compareParams = array(
3260 'to_financial_account_id' => 6,
3261 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3265 if ($context == 'feeAmount') {
3266 $compareParams['fee_amount'] = 50;
3268 elseif ($context == 'online') {
3269 $compareParams = array(
3270 'to_financial_account_id' => 12,
3271 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3273 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
3276 elseif ($context == 'payLater') {
3277 $compareParams = array(
3278 'to_financial_account_id' => 7,
3279 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3283 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3284 $entityParams = array(
3285 'financial_trxn_id' => $trxn['financial_trxn_id'],
3286 'entity_table' => 'civicrm_financial_item',
3288 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3289 $fitemParams = array(
3290 'id' => $entityTrxn['entity_id'],
3292 $compareParams = array(
3293 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3295 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3297 if ($context == 'payLater') {
3298 $compareParams = array(
3299 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3301 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3304 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3305 if ($context == 'feeAmount') {
3307 'entity_id' => $params['id'],
3308 'entity_table' => 'civicrm_contribution',
3310 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
3311 $trxnParams = array(
3312 'id' => $maxTrxn['financial_trxn_id'],
3314 $compareParams = array(
3315 'to_financial_account_id' => 5,
3316 'from_financial_account_id' => 6,
3317 'total_amount' => 50,
3320 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
3321 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3322 $fitemParams = array(
3323 'entity_id' => $trxnId['financialTrxnId'],
3324 'entity_table' => 'civicrm_financial_trxn',
3326 $compareParams = array(
3329 'financial_account_id' => 5,
3331 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3333 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3334 // line should be copied into all the functions that call this function & evaluated there
3335 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3336 // when calling completeTransaction or repeatTransaction.
3337 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
3341 * Return financial type id on basis of name
3343 * @param string $name Financial type m/c name
3347 public function getFinancialTypeId($name) {
3348 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
3352 * Cleanup function for contents of $this->ids.
3354 * This is a best effort cleanup to use in tear downs etc.
3356 * It will not fail if the data has already been removed (some tests may do
3357 * their own cleanup).
3359 protected function cleanUpSetUpIDs() {
3360 foreach ($this->setupIDs
as $entity => $id) {
3362 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
3364 catch (CiviCRM_API3_Exception
$e) {
3365 // This is a best-effort cleanup function, ignore.
3371 * Create Financial Type.
3373 * @param array $params
3377 protected function createFinancialType($params = array()) {
3378 $params = array_merge($params,
3380 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
3384 return $this->callAPISuccess('FinancialType', 'create', $params);
3388 * Create Payment Instrument.
3390 * @param array $params
3391 * @param string $financialAccountName
3395 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
3396 $params = array_merge(array(
3397 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
3398 'option_group_id' => 'payment_instrument',
3403 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params);
3405 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
3407 $financialAccountParams = [
3408 'entity_table' => 'civicrm_option_value',
3409 'entity_id' => key($newPaymentInstrument),
3410 'account_relationship' => $relationTypeID,
3411 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
3413 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
3415 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
3419 * Enable Tax and Invoicing
3421 protected function enableTaxAndInvoicing($params = array()) {
3422 // Enable component contribute setting
3423 $contributeSetting = array_merge($params,
3426 'invoice_prefix' => 'INV_',
3427 'credit_notes_prefix' => 'CN_',
3429 'due_date_period' => 'days',
3431 'is_email_pdf' => 1,
3432 'tax_term' => 'Sales Tax',
3433 'tax_display_settings' => 'Inclusive',
3436 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3440 * Enable Tax and Invoicing
3442 protected function disableTaxAndInvoicing($params = array()) {
3443 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
3444 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
3446 // Enable component contribute setting
3447 $contributeSetting = array_merge($params,
3452 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3456 * Add Sales Tax relation for financial type with financial account.
3458 * @param int $financialTypeId
3462 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3464 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3465 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3466 'is_deductible' => 1,
3471 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3472 $entityParams = array(
3473 'entity_table' => 'civicrm_financial_type',
3474 'entity_id' => $financialTypeId,
3475 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3478 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3479 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3481 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3482 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3483 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3484 $dao->copyValues($entityParams);
3486 if ($dao->fetch()) {
3487 $entityParams['id'] = $dao->id
;
3489 $entityParams['financial_account_id'] = $account->id
;
3491 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3495 * Create price set with contribution test for test setup.
3497 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3498 * on parent class at some point (fn is not in 4.4).
3501 * @param array $params
3503 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3504 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3505 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3506 'title' => "Test Contribution Page",
3507 'financial_type_id' => 1,
3508 'currency' => 'NZD',
3509 'goal_amount' => 50,
3510 'is_pay_later' => 1,
3511 'is_monetary' => TRUE,
3512 'is_email_receipt' => FALSE,
3514 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3515 'is_quick_config' => 0,
3516 'extends' => 'CiviMember',
3517 'financial_type_id' => 1,
3518 'title' => 'my Page',
3520 $priceSetID = $priceSet['id'];
3522 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3523 $priceField = $this->callAPISuccess('price_field', 'create', array(
3524 'price_set_id' => $priceSetID,
3525 'label' => 'Goat Breed',
3526 'html_type' => 'Radio',
3528 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3529 'price_set_id' => $priceSetID,
3530 'price_field_id' => $priceField['id'],
3531 'label' => 'Long Haired Goat',
3533 'financial_type_id' => 'Donation',
3534 'membership_type_id' => $membershipTypeID,
3535 'membership_num_terms' => 1,
3538 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3539 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3540 'price_set_id' => $priceSetID,
3541 'price_field_id' => $priceField['id'],
3542 'label' => 'Shoe-eating Goat',
3544 'financial_type_id' => 'Donation',
3545 'membership_type_id' => $membershipTypeID,
3546 'membership_num_terms' => 2,
3549 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3551 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3552 'price_set_id' => $priceSetID,
3553 'price_field_id' => $priceField['id'],
3554 'label' => 'Shoe-eating Goat',
3556 'financial_type_id' => 'Donation',
3559 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3561 $this->_ids
['price_set'] = $priceSetID;
3562 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3563 $this->_ids
['price_field'] = array($priceField['id']);
3565 $this->_ids
['membership_type'] = $membershipTypeID;
3569 * No results returned.
3571 * @implements CRM_Utils_Hook::aclWhereClause
3573 * @param string $type
3574 * @param array $tables
3575 * @param array $whereTables
3576 * @param int $contactID
3577 * @param string $where
3579 public function aclWhereHookNoResults($type, &$tables, &$whereTables, &$contactID, &$where) {
3583 * Only specified contact returned.
3584 * @implements CRM_Utils_Hook::aclWhereClause
3587 * @param $whereTables
3591 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3592 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3596 * @implements CRM_Utils_Hook::selectWhereClause
3598 * @param string $entity
3599 * @param array $clauses
3601 public function selectWhereClauseHook($entity, &$clauses) {
3602 if ($entity == 'Event') {
3603 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3608 * An implementation of hook_civicrm_post used with all our test cases.
3611 * @param string $objectName
3612 * @param int $objectId
3615 public function onPost($op, $objectName, $objectId, &$objectRef) {
3616 if ($op == 'create' && $objectName == 'Individual') {
3617 CRM_Core_DAO
::executeQuery(
3618 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3620 1 => array($objectId, 'Integer'),
3625 if ($op == 'edit' && $objectName == 'Participant') {
3627 1 => array($objectId, 'Integer'),
3629 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3630 CRM_Core_DAO
::executeQuery($query, $params);
3636 * Instantiate form object.
3638 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3640 * @param string $class
3641 * Name of form class.
3643 * @return \CRM_Core_Form
3645 public function getFormObject($class) {
3646 $form = new $class();
3647 $_SERVER['REQUEST_METHOD'] = 'GET';
3648 $form->controller
= new CRM_Core_Controller();
3653 * Get possible thousand separators.
3657 public function getThousandSeparators() {
3658 return array(array('.'), array(','));
3662 * Set the separators for thousands and decimal points.
3664 * @param string $thousandSeparator
3666 protected function setCurrencySeparators($thousandSeparator) {
3667 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3669 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3673 * Format money as it would be input.
3675 * @param string $amount
3679 protected function formatMoneyInput($amount) {
3680 return CRM_Utils_Money
::format($amount, NULL, '%a');
3685 * Get the contribution object.
3687 * @param int $contributionID
3689 * @return \CRM_Contribute_BAO_Contribution
3691 protected function getContributionObject($contributionID) {
3692 $contributionObj = new CRM_Contribute_BAO_Contribution();
3693 $contributionObj->id
= $contributionID;
3694 $contributionObj->find(TRUE);
3695 return $contributionObj;
3699 * Enable multilingual.
3701 public function enableMultilingual() {
3702 $this->callAPISuccess('Setting', 'create', array(
3703 'lcMessages' => 'en_US',
3704 'languageLimit' => array(
3709 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3712 $dbLocale = '_en_US';