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();
145 * Because we are overriding the parent class constructor, we
146 * need to show the same arguments as exist in the constructor of
147 * PHPUnit_Framework_TestCase, since
148 * PHPUnit_Framework_TestSuite::createTest() creates a
149 * ReflectionClass of the Test class and checks the constructor
150 * of that class to decide how to set up the test.
152 * @param string $name
154 * @param string $dataName
156 public function __construct($name = NULL, array$data = array(), $dataName = '') {
157 parent
::__construct($name, $data, $dataName);
159 // we need full error reporting
160 error_reporting(E_ALL
& ~E_NOTICE
);
162 self
::$_dbName = self
::getDBName();
164 // also load the class loader
165 require_once 'CRM/Core/ClassLoader.php';
166 CRM_Core_ClassLoader
::singleton()->register();
167 if (function_exists('_civix_phpunit_setUp')) {
168 // FIXME: loosen coupling
169 _civix_phpunit_setUp();
174 * Override to run the test and assert its state.
177 * @throws \PHPUnit_Framework_IncompleteTest
178 * @throws \PHPUnit_Framework_SkippedTest
180 protected function runTest() {
182 return parent
::runTest();
184 catch (PEAR_Exception
$e) {
185 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
186 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
193 public function requireDBReset() {
194 return $this->DBResetRequired
;
200 public static function getDBName() {
201 static $dbName = NULL;
202 if ($dbName === NULL) {
203 require_once "DB.php";
204 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
205 $dbName = $dsninfo['database'];
211 * Create database connection for this instance.
213 * Initialize the test database if it hasn't been initialized
215 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
217 protected function getConnection() {
218 $dbName = self
::$_dbName;
219 if (!self
::$dbInit) {
220 $dbName = self
::getDBName();
222 // install test database
223 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
225 static::_populateDB(FALSE, $this);
227 self
::$dbInit = TRUE;
230 return $this->createDefaultDBConnection(Civi\Test
::pdo(), $dbName);
234 * Required implementation of abstract method.
236 protected function getDataSet() {
240 * @param bool $perClass
241 * @param null $object
243 * TRUE if the populate logic runs; FALSE if it is skipped
245 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
246 if (CIVICRM_UF
!== 'UnitTests') {
247 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
250 if ($perClass ||
$object == NULL) {
254 $dbreset = $object->requireDBReset();
257 if (self
::$populateOnce ||
!$dbreset) {
260 self
::$populateOnce = NULL;
262 Civi\Test
::data()->populate();
267 public static function setUpBeforeClass() {
268 static::_populateDB(TRUE);
270 // also set this global hack
271 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
275 * Common setup functions for all unit tests.
277 protected function setUp() {
278 $session = CRM_Core_Session
::singleton();
279 $session->set('userID', NULL);
281 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException(); // REVERT
282 // Use a temporary file for STDIN
283 $GLOBALS['stdin'] = tmpfile();
284 if ($GLOBALS['stdin'] === FALSE) {
285 echo "Couldn't open temporary file\n";
289 // Get and save a connection to the database
290 $this->_dbconn
= $this->getConnection();
292 // reload database before each test
293 // $this->_populateDB();
295 // "initialize" CiviCRM to avoid problems when running single tests
296 // FIXME: look at it closer in second stage
298 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
299 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
301 // disable any left-over test extensions
302 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
304 // reset all the caches
305 CRM_Utils_System
::flushCache();
307 // initialize the object once db is loaded
309 $config = CRM_Core_Config
::singleton(TRUE, TRUE); // ugh, performance
311 // when running unit tests, use mockup user framework
312 $this->hookClass
= CRM_Utils_Hook
::singleton();
314 // Make sure the DB connection is setup properly
315 $config->userSystem
->setMySQLTimeZone();
316 $env = new CRM_Utils_Check_Component_Env();
317 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
319 // clear permissions stub to not check permissions
320 $config->userPermissionClass
->permissions
= NULL;
322 //flush component settings
323 CRM_Core_Component
::getEnabledComponents(TRUE);
325 error_reporting(E_ALL
);
327 $this->_sethtmlGlobals();
331 * Read everything from the datasets directory and insert into the db.
333 public function loadAllFixtures() {
334 $fixturesDir = __DIR__
. '/../../fixtures';
336 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
338 $xmlFiles = glob($fixturesDir . '/*.xml');
339 foreach ($xmlFiles as $xmlFixture) {
340 $op = new PHPUnit_Extensions_Database_Operation_Insert();
341 $dataset = $this->createXMLDataSet($xmlFixture);
342 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
343 $op->execute($this->_dbconn
, $dataset);
346 $yamlFiles = glob($fixturesDir . '/*.yaml');
347 foreach ($yamlFiles as $yamlFixture) {
348 $op = new PHPUnit_Extensions_Database_Operation_Insert();
349 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
350 $this->_tablesToTruncate
= array_merge($this->_tablesToTruncate
, $dataset->getTableNames());
351 $op->execute($this->_dbconn
, $dataset);
354 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
358 * Emulate a logged in user since certain functions use that.
359 * value to store a record in the DB (like activity)
363 * Contact ID of the created user.
365 public function createLoggedInUser() {
367 'first_name' => 'Logged In',
368 'last_name' => 'User ' . rand(),
369 'contact_type' => 'Individual',
371 $contactID = $this->individualCreate($params);
372 $this->callAPISuccess('UFMatch', 'create', array(
373 'contact_id' => $contactID,
374 'uf_name' => 'superman',
378 $session = CRM_Core_Session
::singleton();
379 $session->set('userID', $contactID);
384 * Create default domain contacts for the two domains added during test class.
385 * database population.
387 public function createDomainContacts() {
388 $this->organizationCreate();
389 $this->organizationCreate(array('organization_name' => 'Second Domain'));
393 * Common teardown functions for all unit tests.
395 protected function tearDown() {
396 error_reporting(E_ALL
& ~E_NOTICE
);
397 CRM_Utils_Hook
::singleton()->reset();
398 $this->hookClass
->reset();
399 $session = CRM_Core_Session
::singleton();
400 $session->set('userID', NULL);
403 $this->tx
->rollback()->commit();
406 CRM_Core_Transaction
::forceRollbackIfEnabled();
407 \Civi\Core\Transaction\Manager
::singleton(TRUE);
410 CRM_Core_Transaction
::forceRollbackIfEnabled();
411 \Civi\Core\Transaction\Manager
::singleton(TRUE);
413 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
414 $this->quickCleanup($tablesToTruncate);
415 $this->createDomainContacts();
418 $this->cleanTempDirs();
419 $this->unsetExtensionSystem();
423 * Generic function to compare expected values after an api call to retrieved.
426 * @daoName string DAO Name of object we're evaluating.
427 * @id int Id of object
428 * @match array Associative array of field name => expected value. Empty if asserting
429 * that a DELETE occurred
430 * @delete boolean True if we're checking that a DELETE action occurred.
434 * @param bool $delete
435 * @throws \PHPUnit_Framework_AssertionFailedError
437 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
439 // adding this here since developers forget to check for an id
440 // and hence we get the first value in the db
441 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
444 $object = new $daoName();
448 // If we're asserting successful record deletion, make sure object is NOT found.
450 if ($object->find(TRUE)) {
451 $this->fail("Object not deleted by delete operation: $daoName, $id");
456 // Otherwise check matches of DAO field values against expected values in $match.
457 if ($object->find(TRUE)) {
458 $fields = &$object->fields();
459 foreach ($fields as $name => $value) {
460 $dbName = $value['name'];
461 if (isset($match[$name])) {
463 $this->assertEquals($object->$dbName, $match[$name]);
465 elseif (isset($match[$dbName])) {
467 $this->assertEquals($object->$dbName, $match[$dbName]);
472 $this->fail("Could not retrieve object: $daoName, $id");
475 $matchSize = count($match);
476 if ($verifiedCount != $matchSize) {
477 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
482 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
483 * @param string $daoName
484 * @param $searchValue
485 * @param $returnColumn
486 * @param $searchColumn
489 * @return null|string
490 * @throws PHPUnit_Framework_AssertionFailedError
492 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
493 if (empty($searchValue)) {
494 $this->fail("empty value passed to assertDBNotNull");
496 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
497 $this->assertNotNull($value, $message);
503 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
504 * @param string $daoName
505 * @param $searchValue
506 * @param $returnColumn
507 * @param $searchColumn
510 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
511 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
512 $this->assertNull($value, $message);
516 * Request a record from the DB by id. Success if row not found.
517 * @param string $daoName
519 * @param null $message
521 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
522 $message = $message ?
$message : "$daoName (#$id) should not exist";
523 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', 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 assertDBRowExist($daoName, $id, $message = NULL) {
534 $message = $message ?
$message : "$daoName (#$id) should exist";
535 $value = CRM_Core_DAO
::getFieldValue($daoName, $id, 'id', 'id', TRUE);
536 $this->assertEquals($id, $value, $message);
540 * Compare a single column value in a retrieved DB record to an expected value.
541 * @param string $daoName
542 * @param $searchValue
543 * @param $returnColumn
544 * @param $searchColumn
545 * @param $expectedValue
548 public function assertDBCompareValue(
549 $daoName, $searchValue, $returnColumn, $searchColumn,
550 $expectedValue, $message
552 $value = CRM_Core_DAO
::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
553 $this->assertEquals($expectedValue, $value, $message);
557 * Compare all values in a single retrieved DB record to an array of expected values.
558 * @param string $daoName
559 * @param array $searchParams
560 * @param $expectedValues
562 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
563 //get the values from db
565 CRM_Core_DAO
::commonRetrieve($daoName, $searchParams, $dbValues);
567 // compare db values with expected values
568 self
::assertAttributesEquals($expectedValues, $dbValues);
572 * Assert that a SQL query returns a given value.
574 * The first argument is an expected value. The remaining arguments are passed
575 * to CRM_Core_DAO::singleValueQuery
577 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
578 * array(1 => array("Whiz", "String")));
581 * @param array $params
582 * @param string $message
584 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
588 $actual = CRM_Core_DAO
::singleValueQuery($query, $params);
589 $this->assertEquals($expected, $actual,
590 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
591 $message, $expected, $actual, CRM_Core_DAO
::composeQuery($query, $params, FALSE)
597 * Assert that two array-trees are exactly equal, notwithstanding
598 * the sorting of keys
600 * @param array $expected
601 * @param array $actual
603 public function assertTreeEquals($expected, $actual) {
606 CRM_Utils_Array
::flatten($expected, $e, '', ':::');
607 CRM_Utils_Array
::flatten($actual, $a, '', ':::');
611 $this->assertEquals($e, $a);
615 * Assert that two numbers are approximately equal.
617 * @param int|float $expected
618 * @param int|float $actual
619 * @param int|float $tolerance
620 * @param string $message
622 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
623 if ($message === NULL) {
624 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
626 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
630 * Assert attributes are equal.
632 * @param $expectedValues
633 * @param $actualValues
634 * @param string $message
636 * @throws PHPUnit_Framework_AssertionFailedError
638 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
639 foreach ($expectedValues as $paramName => $paramValue) {
640 if (isset($actualValues[$paramName])) {
641 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE));
644 $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
653 public function assertArrayKeyExists($key, &$list) {
654 $result = isset($list[$key]) ?
TRUE : FALSE;
655 $this->assertTrue($result, ts("%1 element exists?",
664 public function assertArrayValueNotNull($key, &$list) {
665 $this->assertArrayKeyExists($key, $list);
667 $value = isset($list[$key]) ?
$list[$key] : NULL;
668 $this->assertTrue($value,
669 ts("%1 element not null?",
678 * @param string $message
680 public function assertType($expected, $actual, $message = '') {
681 return $this->assertInternalType($expected, $actual, $message);
685 * Create a batch of external API calls which can
686 * be executed concurrently.
689 * $calls = $this->createExternalAPI()
690 * ->addCall('Contact', 'get', ...)
691 * ->addCall('Contact', 'get', ...)
697 * @return \Civi\API\ExternalBatch
698 * @throws PHPUnit_Framework_SkippedTestError
700 public function createExternalAPI() {
701 global $civicrm_root;
702 $defaultParams = array(
703 'version' => $this->_apiversion
,
707 $calls = new \Civi\API\
ExternalBatch($defaultParams);
709 if (!$calls->isSupported()) {
710 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
717 * Create required data based on $this->entity & $this->params
718 * This is just a way to set up the test data for delete & get functions
719 * so the distinction between set
720 * up & tested functions is clearer
725 public function createTestEntity() {
726 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
730 * Generic function to create Organisation, to be used in test cases
732 * @param array $params
733 * parameters for civicrm_contact_add api function call
735 * sequence number if creating multiple organizations
738 * id of Organisation created
740 public function organizationCreate($params = array(), $seq = 0) {
744 $params = array_merge($this->sampleContact('Organization', $seq), $params);
745 return $this->_contactCreate($params);
749 * Generic function to create Individual, to be used in test cases
751 * @param array $params
752 * parameters for civicrm_contact_add api function call
754 * sequence number if creating multiple individuals
755 * @param bool $random
758 * id of Individual created
760 public function individualCreate($params = array(), $seq = 0, $random = FALSE) {
761 $params = array_merge($this->sampleContact('Individual', $seq, $random), $params);
762 return $this->_contactCreate($params);
766 * Generic function to create Household, to be used in test cases
768 * @param array $params
769 * parameters for civicrm_contact_add api function call
771 * sequence number if creating multiple households
774 * id of Household created
776 public function householdCreate($params = array(), $seq = 0) {
777 $params = array_merge($this->sampleContact('Household', $seq), $params);
778 return $this->_contactCreate($params);
782 * Helper function for getting sample contact properties.
784 * @param string $contact_type
785 * enum contact type: Individual, Organization
787 * sequence number for the values of this type
790 * properties of sample contact (ie. $params for API call)
792 public function sampleContact($contact_type, $seq = 0, $random = FALSE) {
794 'Individual' => array(
795 // The number of values in each list need to be coprime numbers to not have duplicates
796 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
797 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
798 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
800 'Organization' => array(
801 'organization_name' => array(
802 'Unit Test Organization',
809 'Household' => array(
810 'household_name' => array('Unit Test household'),
813 $params = array('contact_type' => $contact_type);
814 foreach ($samples[$contact_type] as $key => $values) {
815 $params[$key] = $values[$seq %
count($values)];
817 $params[$key] .= substr(sha1(rand()), 0, 5);
820 if ($contact_type == 'Individual') {
821 $params['email'] = strtolower(
822 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
824 $params['prefix_id'] = 3;
825 $params['suffix_id'] = 3;
831 * Private helper function for calling civicrm_contact_add.
833 * @param array $params
834 * For civicrm_contact_add api function call.
839 * id of Household created
841 private function _contactCreate($params) {
842 $result = $this->callAPISuccess('contact', 'create', $params);
843 if (!empty($result['is_error']) ||
empty($result['id'])) {
844 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array
::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array
::value('trace', $result));
846 return $result['id'];
850 * Delete contact, ensuring it is not the domain contact
852 * @param int $contactID
853 * Contact ID to delete
855 public function contactDelete($contactID) {
856 $domain = new CRM_Core_BAO_Domain();
857 $domain->contact_id
= $contactID;
858 if (!$domain->find(TRUE)) {
859 $this->callAPISuccess('contact', 'delete', array(
861 'skip_undelete' => 1,
867 * @param int $contactTypeId
871 public function contactTypeDelete($contactTypeId) {
872 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
874 throw new Exception('Could not delete contact type');
879 * @param array $params
883 public function membershipTypeCreate($params = array()) {
884 CRM_Member_PseudoConstant
::flush('membershipType');
885 CRM_Core_Config
::clearDBCache();
886 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
887 $params = array_merge(array(
889 'duration_unit' => 'year',
890 'duration_interval' => 1,
891 'period_type' => 'rolling',
892 'member_of_contact_id' => $memberOfOrganization,
894 'financial_type_id' => 2,
897 'visibility' => 'Public',
900 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
902 CRM_Member_PseudoConstant
::flush('membershipType');
903 CRM_Utils_Cache
::singleton()->flush();
905 return $result['id'];
909 * @param array $params
913 public function contactMembershipCreate($params) {
914 $params = array_merge(array(
915 'join_date' => '2007-01-21',
916 'start_date' => '2007-01-21',
917 'end_date' => '2007-12-21',
918 'source' => 'Payment',
919 'membership_type_id' => 'General',
921 if (!is_numeric($params['membership_type_id'])) {
922 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
923 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
924 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
928 $result = $this->callAPISuccess('Membership', 'create', $params);
929 return $result['id'];
933 * Delete Membership Type.
935 * @param array $params
937 public function membershipTypeDelete($params) {
938 $this->callAPISuccess('MembershipType', 'Delete', $params);
942 * @param int $membershipID
944 public function membershipDelete($membershipID) {
945 $deleteParams = array('id' => $membershipID);
946 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
950 * @param string $name
954 public function membershipStatusCreate($name = 'test member status') {
955 $params['name'] = $name;
956 $params['start_event'] = 'start_date';
957 $params['end_event'] = 'end_date';
958 $params['is_current_member'] = 1;
959 $params['is_active'] = 1;
961 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
962 CRM_Member_PseudoConstant
::flush('membershipStatus');
963 return $result['id'];
967 * @param int $membershipStatusID
969 public function membershipStatusDelete($membershipStatusID) {
970 if (!$membershipStatusID) {
973 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
976 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
977 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
978 $renewedMembershipEndDate = new DateTime($membershipEndDate);
979 switch ($durationUnit) {
981 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
985 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
986 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
987 $renewedMembershipEndDate->add(new DateInterval('P1D'));
988 $renewedMembershipEndDate->add(new DateInterval('P1M'));
989 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
992 return $renewedMembershipEndDate->format('Y-m-d');
996 * @param array $params
1000 public function relationshipTypeCreate($params = array()) {
1001 $params = array_merge(array(
1002 'name_a_b' => 'Relation 1 for relationship type create',
1003 'name_b_a' => 'Relation 2 for relationship type create',
1004 'contact_type_a' => 'Individual',
1005 'contact_type_b' => 'Organization',
1012 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1013 CRM_Core_PseudoConstant
::flush('relationshipType');
1015 return $result['id'];
1019 * Delete Relatinship Type.
1021 * @param int $relationshipTypeID
1023 public function relationshipTypeDelete($relationshipTypeID) {
1024 $params['id'] = $relationshipTypeID;
1025 $check = $this->callAPISuccess('relationship_type', 'get', $params);
1026 if (!empty($check['count'])) {
1027 $this->callAPISuccess('relationship_type', 'delete', $params);
1032 * @param array $params
1036 public function paymentProcessorTypeCreate($params = NULL) {
1037 if (is_null($params)) {
1039 'name' => 'API_Test_PP',
1040 'title' => 'API Test Payment Processor',
1041 'class_name' => 'CRM_Core_Payment_APITest',
1042 'billing_mode' => 'form',
1048 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1050 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
1052 return $result['id'];
1056 * Create test Authorize.net instance.
1058 * @param array $params
1062 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1063 $params = array_merge(array(
1064 'name' => 'Authorize',
1065 'domain_id' => CRM_Core_Config
::domainID(),
1066 'payment_processor_type_id' => 'AuthNet',
1067 'title' => 'AuthNet',
1072 'user_name' => '4y5BfuW7jm',
1073 'password' => '4cAmW927n8uLf5J8',
1074 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1075 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1076 'class_name' => 'Payment_AuthorizeNet',
1077 'billing_mode' => 1,
1080 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
1081 return $result['id'];
1085 * Create Participant.
1087 * @param array $params
1088 * Array of contact id and event id values.
1091 * $id of participant created
1093 public function participantCreate($params) {
1094 if (empty($params['contact_id'])) {
1095 $params['contact_id'] = $this->individualCreate();
1097 if (empty($params['event_id'])) {
1098 $event = $this->eventCreate();
1099 $params['event_id'] = $event['id'];
1104 'register_date' => 20070219,
1105 'source' => 'Wimbeldon',
1106 'event_level' => 'Payment',
1110 $params = array_merge($defaults, $params);
1111 $result = $this->callAPISuccess('Participant', 'create', $params);
1112 return $result['id'];
1116 * Create Payment Processor.
1119 * Id Payment Processor
1121 public function processorCreate($params = array()) {
1122 $processorParams = array(
1125 'payment_processor_type_id' => 'Dummy',
1126 'financial_account_id' => 12,
1130 'url_site' => 'http://dummy.com',
1131 'url_recur' => 'http://dummy.com',
1132 'billing_mode' => 1,
1134 'payment_instrument_id' => 'Debit Card',
1136 $processorParams = array_merge($processorParams, $params);
1137 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1138 return $processor['id'];
1142 * Create Payment Processor.
1144 * @param array $processorParams
1146 * @return \CRM_Core_Payment_Dummy
1147 * Instance of Dummy Payment Processor
1149 public function dummyProcessorCreate($processorParams = array()) {
1150 $paymentProcessorID = $this->processorCreate($processorParams);
1151 return System
::singleton()->getById($paymentProcessorID);
1155 * Create contribution page.
1157 * @param array $params
1159 * Array of contribution page
1161 public function contributionPageCreate($params = array()) {
1162 $this->_pageParams
= array_merge(array(
1163 'title' => 'Test Contribution Page',
1164 'financial_type_id' => 1,
1165 'currency' => 'USD',
1166 'financial_account_id' => 1,
1168 'is_allow_other_amount' => 1,
1170 'max_amount' => 1000,
1172 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1176 * Create a sample batch.
1178 public function batchCreate() {
1179 $params = $this->_params
;
1180 $params['name'] = $params['title'] = 'Batch_433397';
1181 $params['status_id'] = 1;
1182 $result = $this->callAPISuccess('batch', 'create', $params);
1183 return $result['id'];
1189 * @param array $params
1191 * result of created tag
1193 public function tagCreate($params = array()) {
1195 'name' => 'New Tag3',
1196 'description' => 'This is description for Our New Tag ',
1199 $params = array_merge($defaults, $params);
1200 $result = $this->callAPISuccess('Tag', 'create', $params);
1201 return $result['values'][$result['id']];
1208 * Id of the tag to be deleted.
1212 public function tagDelete($tagId) {
1213 require_once 'api/api.php';
1217 $result = $this->callAPISuccess('Tag', 'delete', $params);
1218 return $result['id'];
1222 * Add entity(s) to the tag
1224 * @param array $params
1228 public function entityTagAdd($params) {
1229 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1236 * @param array $params
1240 * id of created pledge
1242 public function pledgeCreate($params) {
1243 $params = array_merge(array(
1244 'pledge_create_date' => date('Ymd'),
1245 'start_date' => date('Ymd'),
1246 'scheduled_date' => date('Ymd'),
1248 'pledge_status_id' => '2',
1249 'financial_type_id' => '1',
1250 'pledge_original_installment_amount' => 20,
1251 'frequency_interval' => 5,
1252 'frequency_unit' => 'year',
1253 'frequency_day' => 15,
1254 'installments' => 5,
1258 $result = $this->callAPISuccess('Pledge', 'create', $params);
1259 return $result['id'];
1263 * Delete contribution.
1265 * @param int $pledgeId
1267 public function pledgeDelete($pledgeId) {
1269 'pledge_id' => $pledgeId,
1271 $this->callAPISuccess('Pledge', 'delete', $params);
1275 * Create contribution.
1277 * @param array $params
1278 * Array of parameters.
1281 * id of created contribution
1283 public function contributionCreate($params) {
1285 $params = array_merge(array(
1287 'receive_date' => date('Ymd'),
1288 'total_amount' => 100.00,
1289 'fee_amount' => 5.00,
1290 'financial_type_id' => 1,
1291 'payment_instrument_id' => 1,
1292 'non_deductible_amount' => 10.00,
1294 'invoice_id' => 67890,
1296 'contribution_status_id' => 1,
1299 $result = $this->callAPISuccess('contribution', 'create', $params);
1300 return $result['id'];
1304 * Delete contribution.
1306 * @param int $contributionId
1310 public function contributionDelete($contributionId) {
1312 'contribution_id' => $contributionId,
1314 $result = $this->callAPISuccess('contribution', 'delete', $params);
1321 * @param array $params
1322 * Name-value pair for an event.
1326 public function eventCreate($params = array()) {
1327 // if no contact was passed, make up a dummy event creator
1328 if (!isset($params['contact_id'])) {
1329 $params['contact_id'] = $this->_contactCreate(array(
1330 'contact_type' => 'Individual',
1331 'first_name' => 'Event',
1332 'last_name' => 'Creator',
1336 // set defaults for missing params
1337 $params = array_merge(array(
1338 'title' => 'Annual CiviCRM meet',
1339 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1340 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1341 'event_type_id' => 1,
1343 'start_date' => 20081021,
1344 'end_date' => 20081023,
1345 'is_online_registration' => 1,
1346 'registration_start_date' => 20080601,
1347 'registration_end_date' => 20081015,
1348 'max_participants' => 100,
1349 'event_full_text' => 'Sorry! We are already full',
1352 'is_show_location' => 0,
1355 return $this->callAPISuccess('Event', 'create', $params);
1359 * Create a paid event.
1361 * @param array $params
1365 protected function eventCreatePaid($params) {
1366 $event = $this->eventCreate($params);
1367 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1368 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1369 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1370 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1371 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1383 public function eventDelete($id) {
1387 return $this->callAPISuccess('event', 'delete', $params);
1391 * Delete participant.
1393 * @param int $participantID
1397 public function participantDelete($participantID) {
1399 'id' => $participantID,
1401 $check = $this->callAPISuccess('Participant', 'get', $params);
1402 if ($check['count'] > 0) {
1403 return $this->callAPISuccess('Participant', 'delete', $params);
1408 * Create participant payment.
1410 * @param int $participantID
1411 * @param int $contributionID
1413 * $id of created payment
1415 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1416 //Create Participant Payment record With Values
1418 'participant_id' => $participantID,
1419 'contribution_id' => $contributionID,
1422 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1423 return $result['id'];
1427 * Delete participant payment.
1429 * @param int $paymentID
1431 public function participantPaymentDelete($paymentID) {
1435 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1441 * @param int $contactID
1443 * location id of created location
1445 public function locationAdd($contactID) {
1448 'location_type' => 'New Location Type',
1450 'name' => 'Saint Helier St',
1451 'county' => 'Marin',
1452 'country' => 'UNITED STATES',
1453 'state_province' => 'Michigan',
1454 'supplemental_address_1' => 'Hallmark Ct',
1455 'supplemental_address_2' => 'Jersey Village',
1456 'supplemental_address_3' => 'My Town',
1461 'contact_id' => $contactID,
1462 'address' => $address,
1463 'location_format' => '2.0',
1464 'location_type' => 'New Location Type',
1467 $result = $this->callAPISuccess('Location', 'create', $params);
1472 * Delete Locations of contact.
1474 * @param array $params
1477 public function locationDelete($params) {
1478 $this->callAPISuccess('Location', 'delete', $params);
1482 * Add a Location Type.
1484 * @param array $params
1485 * @return CRM_Core_DAO_LocationType
1486 * location id of created location
1488 public function locationTypeCreate($params = NULL) {
1489 if ($params === NULL) {
1491 'name' => 'New Location Type',
1492 'vcard_name' => 'New Location Type',
1493 'description' => 'Location Type for Delete',
1498 $locationType = new CRM_Core_DAO_LocationType();
1499 $locationType->copyValues($params);
1500 $locationType->save();
1501 // clear getfields cache
1502 CRM_Core_PseudoConstant
::flush();
1503 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1504 return $locationType;
1508 * Delete a Location Type.
1510 * @param int $locationTypeId
1512 public function locationTypeDelete($locationTypeId) {
1513 $locationType = new CRM_Core_DAO_LocationType();
1514 $locationType->id
= $locationTypeId;
1515 $locationType->delete();
1521 * @param array $params
1522 * @return CRM_Core_DAO_Mapping
1523 * Mapping id of created mapping
1525 public function mappingCreate($params = NULL) {
1526 if ($params === NULL) {
1528 'name' => 'Mapping name',
1529 'description' => 'Mapping description',
1530 // 'Export Contact' mapping.
1531 'mapping_type_id' => 7,
1535 $mapping = new CRM_Core_DAO_Mapping();
1536 $mapping->copyValues($params);
1538 // clear getfields cache
1539 CRM_Core_PseudoConstant
::flush();
1540 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1547 * @param int $mappingId
1549 public function mappingDelete($mappingId) {
1550 $mapping = new CRM_Core_DAO_Mapping();
1551 $mapping->id
= $mappingId;
1558 * @param array $params
1560 * groupId of created group
1562 public function groupCreate($params = array()) {
1563 $params = array_merge(array(
1564 'name' => 'Test Group 1',
1566 'title' => 'New Test Group Created',
1567 'description' => 'New Test Group Created',
1569 'visibility' => 'Public Pages',
1570 'group_type' => array(
1576 $result = $this->callAPISuccess('Group', 'create', $params);
1577 return $result['id'];
1581 * Prepare class for ACLs.
1583 protected function prepareForACLs() {
1584 $config = CRM_Core_Config
::singleton();
1585 $config->userPermissionClass
->permissions
= array();
1591 protected function cleanUpAfterACLs() {
1592 CRM_Utils_Hook
::singleton()->reset();
1593 $tablesToTruncate = array(
1595 'civicrm_acl_cache',
1596 'civicrm_acl_entity_role',
1597 'civicrm_acl_contact_cache',
1599 $this->quickCleanup($tablesToTruncate);
1600 $config = CRM_Core_Config
::singleton();
1601 unset($config->userPermissionClass
->permissions
);
1604 * Create a smart group.
1606 * By default it will be a group of households.
1608 * @param array $smartGroupParams
1609 * @param array $groupParams
1612 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1613 $smartGroupParams = array_merge(array(
1614 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1617 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1619 $groupParams['saved_search_id'] = $savedSearch->id
;
1620 return $this->groupCreate($groupParams);
1624 * Function to add a Group.
1626 * @params array to add group
1628 * @param int $groupID
1629 * @param int $totalCount
1630 * @param bool $random
1632 * groupId of created group
1634 public function groupContactCreate($groupID, $totalCount = 10, $random = FALSE) {
1635 $params = array('group_id' => $groupID);
1636 for ($i = 1; $i <= $totalCount; $i++
) {
1637 $contactID = $this->individualCreate(array(), 0, $random);
1639 $params +
= array('contact_id' => $contactID);
1642 $params +
= array("contact_id.$i" => $contactID);
1645 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1655 public function groupDelete($gid) {
1661 $this->callAPISuccess('Group', 'delete', $params);
1666 * @param array $params
1668 public function uFFieldCreate($params = array()) {
1669 $params = array_merge(array(
1671 'field_name' => 'first_name',
1674 'visibility' => 'Public Pages and Listings',
1675 'is_searchable' => '1',
1676 'label' => 'first_name',
1677 'field_type' => 'Individual',
1680 $this->callAPISuccess('uf_field', 'create', $params);
1684 * Add a UF Join Entry.
1686 * @param array $params
1688 * $id of created UF Join
1690 public function ufjoinCreate($params = NULL) {
1691 if ($params === NULL) {
1694 'module' => 'CiviEvent',
1695 'entity_table' => 'civicrm_event',
1701 $result = $this->callAPISuccess('uf_join', 'create', $params);
1706 * Delete a UF Join Entry.
1708 * @param array $params
1709 * with missing uf_group_id
1711 public function ufjoinDelete($params = NULL) {
1712 if ($params === NULL) {
1715 'module' => 'CiviEvent',
1716 'entity_table' => 'civicrm_event',
1719 'uf_group_id' => '',
1723 crm_add_uf_join($params);
1727 * @param array $params
1728 * Optional parameters.
1729 * @param bool $reloadConfig
1730 * While enabling CiviCampaign component, we shouldn't always forcibly
1731 * reload config as this hinder hook call in test environment
1736 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1737 $this->enableCiviCampaign($reloadConfig);
1738 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1739 'name' => 'big_campaign',
1740 'title' => 'Campaign',
1742 return $campaign['id'];
1746 * Create Group for a contact.
1748 * @param int $contactId
1750 public function contactGroupCreate($contactId) {
1752 'contact_id.1' => $contactId,
1756 $this->callAPISuccess('GroupContact', 'Create', $params);
1760 * Delete Group for a contact.
1762 * @param int $contactId
1764 public function contactGroupDelete($contactId) {
1766 'contact_id.1' => $contactId,
1769 $this->civicrm_api('GroupContact', 'Delete', $params);
1775 * @param array $params
1778 public function activityCreate($params = array()) {
1779 $params = array_merge(array(
1780 'subject' => 'Discussion on warm beer',
1781 'activity_date_time' => date('Ymd'),
1782 'duration_hours' => 30,
1783 'duration_minutes' => 20,
1784 'location' => 'Baker Street',
1785 'details' => 'Lets schedule a meeting',
1787 'activity_name' => 'Meeting',
1789 if (!isset($params['source_contact_id'])) {
1790 $params['source_contact_id'] = $this->individualCreate();
1792 if (!isset($params['target_contact_id'])) {
1793 $params['target_contact_id'] = $this->individualCreate(array(
1794 'first_name' => 'Julia',
1795 'Last_name' => 'Anderson',
1797 'email' => 'julia_anderson@civicrm.org',
1798 'contact_type' => 'Individual',
1801 if (!isset($params['assignee_contact_id'])) {
1802 $params['assignee_contact_id'] = $params['target_contact_id'];
1805 $result = $this->callAPISuccess('Activity', 'create', $params);
1807 $result['target_contact_id'] = $params['target_contact_id'];
1808 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1813 * Create an activity type.
1815 * @param array $params
1819 public function activityTypeCreate($params) {
1820 return $this->callAPISuccess('ActivityType', 'create', $params);
1824 * Delete activity type.
1826 * @param int $activityTypeId
1827 * Id of the activity type.
1830 public function activityTypeDelete($activityTypeId) {
1831 $params['activity_type_id'] = $activityTypeId;
1832 return $this->callAPISuccess('ActivityType', 'delete', $params);
1836 * Create custom group.
1838 * @param array $params
1841 public function customGroupCreate($params = array()) {
1843 'title' => 'new custom group',
1844 'extends' => 'Contact',
1846 'style' => 'Inline',
1850 $params = array_merge($defaults, $params);
1852 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1853 $this->callAPISuccess('custom_group', 'get', array(
1854 'title' => $params['title'],
1855 array('api.custom_group.delete' => 1),
1858 return $this->callAPISuccess('custom_group', 'create', $params);
1862 * Existing function doesn't allow params to be over-ridden so need a new one
1863 * this one allows you to only pass in the params you want to change
1864 * @param array $params
1867 public function CustomGroupCreateByParams($params = array()) {
1869 'title' => "API Custom Group",
1870 'extends' => 'Contact',
1872 'style' => 'Inline',
1875 $params = array_merge($defaults, $params);
1876 return $this->callAPISuccess('custom_group', 'create', $params);
1880 * Create custom group with multi fields.
1881 * @param array $params
1884 public function CustomGroupMultipleCreateByParams($params = array()) {
1889 $params = array_merge($defaults, $params);
1890 return $this->CustomGroupCreateByParams($params);
1894 * Create custom group with multi fields.
1895 * @param array $params
1898 public function CustomGroupMultipleCreateWithFields($params = array()) {
1899 // also need to pass on $params['custom_field'] if not set but not in place yet
1901 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1902 $ids['custom_group_id'] = $customGroup['id'];
1904 $customField = $this->customFieldCreate(array(
1905 'custom_group_id' => $ids['custom_group_id'],
1906 'label' => 'field_1' . $ids['custom_group_id'],
1910 $ids['custom_field_id'][] = $customField['id'];
1912 $customField = $this->customFieldCreate(array(
1913 'custom_group_id' => $ids['custom_group_id'],
1914 'default_value' => '',
1915 'label' => 'field_2' . $ids['custom_group_id'],
1918 $ids['custom_field_id'][] = $customField['id'];
1920 $customField = $this->customFieldCreate(array(
1921 'custom_group_id' => $ids['custom_group_id'],
1922 'default_value' => '',
1923 'label' => 'field_3' . $ids['custom_group_id'],
1926 $ids['custom_field_id'][] = $customField['id'];
1932 * Create a custom group with a single text custom field. See
1933 * participant:testCreateWithCustom for how to use this
1935 * @param string $function
1937 * @param string $filename
1941 * ids of created objects
1943 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1944 $params = array('title' => $function);
1945 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1946 $params['extends'] = $entity ?
$entity : 'Contact';
1947 $customGroup = $this->CustomGroupCreate($params);
1948 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1949 CRM_Core_PseudoConstant
::flush();
1951 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1955 * Delete custom group.
1957 * @param int $customGroupID
1961 public function customGroupDelete($customGroupID) {
1962 $params['id'] = $customGroupID;
1963 return $this->callAPISuccess('custom_group', 'delete', $params);
1967 * Create custom field.
1969 * @param array $params
1970 * (custom_group_id) is required.
1973 public function customFieldCreate($params) {
1974 $params = array_merge(array(
1975 'label' => 'Custom Field',
1976 'data_type' => 'String',
1977 'html_type' => 'Text',
1978 'is_searchable' => 1,
1980 'default_value' => 'defaultValue',
1983 $result = $this->callAPISuccess('custom_field', 'create', $params);
1984 // these 2 functions are called with force to flush static caches
1985 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1986 CRM_Core_Component
::getEnabledComponents(1);
1991 * Delete custom field.
1993 * @param int $customFieldID
1997 public function customFieldDelete($customFieldID) {
1999 $params['id'] = $customFieldID;
2000 return $this->callAPISuccess('custom_field', 'delete', $params);
2009 public function noteCreate($cId) {
2011 'entity_table' => 'civicrm_contact',
2012 'entity_id' => $cId,
2013 'note' => 'hello I am testing Note',
2014 'contact_id' => $cId,
2015 'modified_date' => date('Ymd'),
2016 'subject' => 'Test Note',
2019 return $this->callAPISuccess('Note', 'create', $params);
2023 * Enable CiviCampaign Component.
2025 * @param bool $reloadConfig
2026 * Force relaod config or not
2028 public function enableCiviCampaign($reloadConfig = TRUE) {
2029 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
2030 if ($reloadConfig) {
2031 // force reload of config object
2032 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
2034 //flush cache by calling with reset
2035 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2039 * Create custom field with Option Values.
2041 * @param array $customGroup
2042 * @param string $name
2043 * Name of custom field.
2044 * @param array $extraParams
2045 * Additional parameters to pass through.
2049 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
2050 $fieldParams = array(
2051 'custom_group_id' => $customGroup['id'],
2052 'name' => 'test_custom_group',
2053 'label' => 'Country',
2054 'html_type' => 'Select',
2055 'data_type' => 'String',
2058 'is_searchable' => 0,
2062 $optionGroup = array(
2064 'name' => 'option_group1',
2065 'label' => 'option_group_label1',
2068 $optionValue = array(
2069 'option_label' => array('Label1', 'Label2'),
2070 'option_value' => array('value1', 'value2'),
2071 'option_name' => array($name . '_1', $name . '_2'),
2072 'option_weight' => array(1, 2),
2073 'option_status' => 1,
2076 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
2078 return $this->callAPISuccess('custom_field', 'create', $params);
2086 public function confirmEntitiesDeleted($entities) {
2087 foreach ($entities as $entity) {
2089 $result = $this->callAPISuccess($entity, 'Get', array());
2090 if ($result['error'] == 1 ||
$result['count'] > 0) {
2091 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2099 * Quick clean by emptying tables created for the test.
2101 * @param array $tablesToTruncate
2102 * @param bool $dropCustomValueTables
2103 * @throws \Exception
2105 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2107 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2109 if ($dropCustomValueTables) {
2110 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2111 while ($optionGroupResult->fetch()) {
2112 if (!empty($optionGroupResult->option_group_id
)) {
2113 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
2116 $tablesToTruncate[] = 'civicrm_custom_group';
2117 $tablesToTruncate[] = 'civicrm_custom_field';
2120 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
2122 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2123 foreach ($tablesToTruncate as $table) {
2124 $sql = "TRUNCATE TABLE $table";
2125 CRM_Core_DAO
::executeQuery($sql);
2127 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2129 if ($dropCustomValueTables) {
2130 $dbName = self
::getDBName();
2132 SELECT TABLE_NAME as tableName
2133 FROM INFORMATION_SCHEMA.TABLES
2134 WHERE TABLE_SCHEMA = '{$dbName}'
2135 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2138 $tableDAO = CRM_Core_DAO
::executeQuery($query);
2139 while ($tableDAO->fetch()) {
2140 $sql = "DROP TABLE {$tableDAO->tableName}";
2141 CRM_Core_DAO
::executeQuery($sql);
2147 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2149 public function quickCleanUpFinancialEntities() {
2150 $tablesToTruncate = array(
2152 'civicrm_activity_contact',
2153 'civicrm_contribution',
2154 'civicrm_contribution_soft',
2155 'civicrm_contribution_product',
2156 'civicrm_financial_trxn',
2157 'civicrm_financial_item',
2158 'civicrm_contribution_recur',
2159 'civicrm_line_item',
2160 'civicrm_contribution_page',
2161 'civicrm_payment_processor',
2162 'civicrm_entity_financial_trxn',
2163 'civicrm_membership',
2164 'civicrm_membership_type',
2165 'civicrm_membership_payment',
2166 'civicrm_membership_log',
2167 'civicrm_membership_block',
2169 'civicrm_participant',
2170 'civicrm_participant_payment',
2172 'civicrm_pledge_payment',
2173 'civicrm_price_set_entity',
2174 'civicrm_price_field_value',
2175 'civicrm_price_field',
2177 $this->quickCleanup($tablesToTruncate);
2178 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2179 $this->restoreDefaultPriceSetConfig();
2181 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
2182 $this->disableTaxAndInvoicing();
2183 $this->setCurrencySeparators(',');
2184 CRM_Core_PseudoConstant
::flush('taxRates');
2185 System
::singleton()->flushProcessors();
2188 public function restoreDefaultPriceSetConfig() {
2189 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
2190 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
2191 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)");
2192 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)");
2195 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2196 * Default behaviour is to also delete the entity
2197 * @param array $params
2198 * Params array to check against.
2200 * Id of the entity concerned.
2201 * @param string $entity
2202 * Name of entity concerned (e.g. membership).
2203 * @param bool $delete
2204 * Should the entity be deleted as part of this check.
2205 * @param string $errorText
2206 * Text to print on error.
2209 * @param array $params
2212 * @param int $delete
2213 * @param string $errorText
2217 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2219 $result = $this->callAPISuccessGetSingle($entity, array(
2224 $this->callAPISuccess($entity, 'Delete', array(
2228 $dateFields = $keys = $dateTimeFields = array();
2229 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2230 foreach ($fields['values'] as $field => $settings) {
2231 if (array_key_exists($field, $result)) {
2232 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
2235 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
2237 $type = CRM_Utils_Array
::value('type', $settings);
2238 if ($type == CRM_Utils_Type
::T_DATE
) {
2239 $dateFields[] = $settings['name'];
2240 // we should identify both real names & unique names as dates
2241 if ($field != $settings['name']) {
2242 $dateFields[] = $field;
2245 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
2246 $dateTimeFields[] = $settings['name'];
2247 // we should identify both real names & unique names as dates
2248 if ($field != $settings['name']) {
2249 $dateTimeFields[] = $field;
2254 if (strtolower($entity) == 'contribution') {
2255 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2256 // this is not returned in id format
2257 unset($params['payment_instrument_id']);
2258 $params['contribution_source'] = $params['source'];
2259 unset($params['source']);
2262 foreach ($params as $key => $value) {
2263 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
2266 if (in_array($key, $dateFields)) {
2267 $value = date('Y-m-d', strtotime($value));
2268 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2270 if (in_array($key, $dateTimeFields)) {
2271 $value = date('Y-m-d H:i:s', strtotime($value));
2272 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
2274 $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);
2279 * Get formatted values in the actual and expected result.
2280 * @param array $actual
2281 * Actual calculated values.
2282 * @param array $expected
2285 public function checkArrayEquals(&$actual, &$expected) {
2286 self
::unsetId($actual);
2287 self
::unsetId($expected);
2288 $this->assertEquals($actual, $expected);
2292 * Unset the key 'id' from the array
2293 * @param array $unformattedArray
2294 * The array from which the 'id' has to be unset.
2296 public static function unsetId(&$unformattedArray) {
2297 $formattedArray = array();
2298 if (array_key_exists('id', $unformattedArray)) {
2299 unset($unformattedArray['id']);
2301 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2302 foreach ($unformattedArray['values'] as $key => $value) {
2303 if (is_array($value)) {
2304 foreach ($value as $k => $v) {
2310 elseif ($key == 'id') {
2311 $unformattedArray[$key];
2313 $formattedArray = array($value);
2315 $unformattedArray['values'] = $formattedArray;
2320 * Helper to enable/disable custom directory support
2322 * @param array $customDirs
2324 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2325 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2327 public function customDirectories($customDirs) {
2328 $config = CRM_Core_Config
::singleton();
2330 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
2331 unset($config->customPHPPathDir
);
2333 elseif ($customDirs['php_path'] === TRUE) {
2334 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
2337 $config->customPHPPathDir
= $php_path;
2340 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
2341 unset($config->customTemplateDir
);
2343 elseif ($customDirs['template_path'] === TRUE) {
2344 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
2347 $config->customTemplateDir
= $template_path;
2352 * Generate a temporary folder.
2354 * @param string $prefix
2357 public function createTempDir($prefix = 'test-') {
2358 $tempDir = CRM_Utils_File
::tempdir($prefix);
2359 $this->tempDirs
[] = $tempDir;
2363 public function cleanTempDirs() {
2364 if (!is_array($this->tempDirs
)) {
2365 // fix test errors where this is not set
2368 foreach ($this->tempDirs
as $tempDir) {
2369 if (is_dir($tempDir)) {
2370 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
2376 * Temporarily replace the singleton extension with a different one.
2377 * @param \CRM_Extension_System $system
2379 public function setExtensionSystem(CRM_Extension_System
$system) {
2380 if ($this->origExtensionSystem
== NULL) {
2381 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
2383 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2386 public function unsetExtensionSystem() {
2387 if ($this->origExtensionSystem
!== NULL) {
2388 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2389 $this->origExtensionSystem
= NULL;
2394 * Temporarily alter the settings-metadata to add a mock setting.
2396 * WARNING: The setting metadata will disappear on the next cache-clear.
2401 public function setMockSettingsMetaData($extras) {
2402 Civi
::service('settings_manager')->flush();
2404 CRM_Utils_Hook
::singleton()
2405 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2406 $metadata = array_merge($metadata, $extras);
2409 $fields = $this->callAPISuccess('setting', 'getfields', array());
2410 foreach ($extras as $key => $spec) {
2411 $this->assertNotEmpty($spec['title']);
2412 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2417 * @param string $name
2419 public function financialAccountDelete($name) {
2420 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2421 $financialAccount->name
= $name;
2422 if ($financialAccount->find(TRUE)) {
2423 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2424 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2425 $entityFinancialType->delete();
2426 $financialAccount->delete();
2431 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2432 * (NB unclear if this is still required)
2434 public function _sethtmlGlobals() {
2435 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2436 'required' => array(
2437 'html_quickform_rule_required',
2438 'HTML/QuickForm/Rule/Required.php',
2440 'maxlength' => array(
2441 'html_quickform_rule_range',
2442 'HTML/QuickForm/Rule/Range.php',
2444 'minlength' => array(
2445 'html_quickform_rule_range',
2446 'HTML/QuickForm/Rule/Range.php',
2448 'rangelength' => array(
2449 'html_quickform_rule_range',
2450 'HTML/QuickForm/Rule/Range.php',
2453 'html_quickform_rule_email',
2454 'HTML/QuickForm/Rule/Email.php',
2457 'html_quickform_rule_regex',
2458 'HTML/QuickForm/Rule/Regex.php',
2460 'lettersonly' => array(
2461 'html_quickform_rule_regex',
2462 'HTML/QuickForm/Rule/Regex.php',
2464 'alphanumeric' => array(
2465 'html_quickform_rule_regex',
2466 'HTML/QuickForm/Rule/Regex.php',
2469 'html_quickform_rule_regex',
2470 'HTML/QuickForm/Rule/Regex.php',
2472 'nopunctuation' => array(
2473 'html_quickform_rule_regex',
2474 'HTML/QuickForm/Rule/Regex.php',
2477 'html_quickform_rule_regex',
2478 'HTML/QuickForm/Rule/Regex.php',
2480 'callback' => array(
2481 'html_quickform_rule_callback',
2482 'HTML/QuickForm/Rule/Callback.php',
2485 'html_quickform_rule_compare',
2486 'HTML/QuickForm/Rule/Compare.php',
2489 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2490 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2492 'HTML/QuickForm/group.php',
2493 'HTML_QuickForm_group',
2496 'HTML/QuickForm/hidden.php',
2497 'HTML_QuickForm_hidden',
2500 'HTML/QuickForm/reset.php',
2501 'HTML_QuickForm_reset',
2503 'checkbox' => array(
2504 'HTML/QuickForm/checkbox.php',
2505 'HTML_QuickForm_checkbox',
2508 'HTML/QuickForm/file.php',
2509 'HTML_QuickForm_file',
2512 'HTML/QuickForm/image.php',
2513 'HTML_QuickForm_image',
2515 'password' => array(
2516 'HTML/QuickForm/password.php',
2517 'HTML_QuickForm_password',
2520 'HTML/QuickForm/radio.php',
2521 'HTML_QuickForm_radio',
2524 'HTML/QuickForm/button.php',
2525 'HTML_QuickForm_button',
2528 'HTML/QuickForm/submit.php',
2529 'HTML_QuickForm_submit',
2532 'HTML/QuickForm/select.php',
2533 'HTML_QuickForm_select',
2535 'hiddenselect' => array(
2536 'HTML/QuickForm/hiddenselect.php',
2537 'HTML_QuickForm_hiddenselect',
2540 'HTML/QuickForm/text.php',
2541 'HTML_QuickForm_text',
2543 'textarea' => array(
2544 'HTML/QuickForm/textarea.php',
2545 'HTML_QuickForm_textarea',
2547 'fckeditor' => array(
2548 'HTML/QuickForm/fckeditor.php',
2549 'HTML_QuickForm_FCKEditor',
2552 'HTML/QuickForm/tinymce.php',
2553 'HTML_QuickForm_TinyMCE',
2555 'dojoeditor' => array(
2556 'HTML/QuickForm/dojoeditor.php',
2557 'HTML_QuickForm_dojoeditor',
2560 'HTML/QuickForm/link.php',
2561 'HTML_QuickForm_link',
2563 'advcheckbox' => array(
2564 'HTML/QuickForm/advcheckbox.php',
2565 'HTML_QuickForm_advcheckbox',
2568 'HTML/QuickForm/date.php',
2569 'HTML_QuickForm_date',
2572 'HTML/QuickForm/static.php',
2573 'HTML_QuickForm_static',
2576 'HTML/QuickForm/header.php',
2577 'HTML_QuickForm_header',
2580 'HTML/QuickForm/html.php',
2581 'HTML_QuickForm_html',
2583 'hierselect' => array(
2584 'HTML/QuickForm/hierselect.php',
2585 'HTML_QuickForm_hierselect',
2587 'autocomplete' => array(
2588 'HTML/QuickForm/autocomplete.php',
2589 'HTML_QuickForm_autocomplete',
2592 'HTML/QuickForm/xbutton.php',
2593 'HTML_QuickForm_xbutton',
2595 'advmultiselect' => array(
2596 'HTML/QuickForm/advmultiselect.php',
2597 'HTML_QuickForm_advmultiselect',
2603 * Set up an acl allowing contact to see 2 specified groups
2604 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2606 * You need to have pre-created these groups & created the user e.g
2607 * $this->createLoggedInUser();
2608 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2609 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2611 * @param bool $isProfile
2613 public function setupACL($isProfile = FALSE) {
2615 $_REQUEST = $this->_params
;
2617 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2618 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2619 $ov = new CRM_Core_DAO_OptionValue();
2620 $ov->option_group_id
= $optionGroupID;
2622 if ($ov->find(TRUE)) {
2623 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2625 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2626 'option_group_id' => $optionGroupID,
2627 'label' => 'pick me',
2631 CRM_Core_DAO
::executeQuery("
2632 TRUNCATE civicrm_acl_cache
2635 CRM_Core_DAO
::executeQuery("
2636 TRUNCATE civicrm_acl_contact_cache
2639 CRM_Core_DAO
::executeQuery("
2640 INSERT INTO civicrm_acl_entity_role (
2641 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2642 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2646 CRM_Core_DAO
::executeQuery("
2647 INSERT INTO civicrm_acl (
2648 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2651 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2656 CRM_Core_DAO
::executeQuery("
2657 INSERT INTO civicrm_acl (
2658 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2661 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2665 CRM_Core_DAO
::executeQuery("
2666 INSERT INTO civicrm_acl (
2667 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2670 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2675 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2676 $this->callAPISuccess('group_contact', 'create', array(
2677 'group_id' => $this->_permissionedGroup
,
2678 'contact_id' => $this->_loggedInUser
,
2683 CRM_ACL_BAO_Cache
::resetCache();
2684 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
2689 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2691 public function offsetDefaultPriceSet() {
2692 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2693 $firstID = $contributionPriceSet['id'];
2694 $this->callAPISuccess('price_set', 'create', array(
2695 'id' => $contributionPriceSet['id'],
2699 unset($contributionPriceSet['id']);
2700 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2701 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2702 'price_set_id' => $firstID,
2703 'options' => array('limit' => 1),
2705 unset($priceField['id']);
2706 $priceField['price_set_id'] = $newPriceSet['id'];
2707 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2708 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2709 'price_set_id' => $firstID,
2711 'options' => array('limit' => 1),
2714 unset($priceFieldValue['id']);
2715 //create some padding to use up ids
2716 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2717 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2718 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2722 * Create an instance of the paypal processor.
2723 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2724 * this parent class & we don't have a structure for that yet
2725 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2726 * & the best protection against that is the functions this class affords
2727 * @param array $params
2728 * @return int $result['id'] payment processor id
2730 public function paymentProcessorCreate($params = array()) {
2731 $params = array_merge(array(
2733 'domain_id' => CRM_Core_Config
::domainID(),
2734 'payment_processor_type_id' => 'PayPal',
2738 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2739 'password' => '1183377788',
2740 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2741 'url_site' => 'https://www.sandbox.paypal.com/',
2742 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2743 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2744 'class_name' => 'Payment_PayPalImpl',
2745 'billing_mode' => 3,
2746 'financial_type_id' => 1,
2747 'financial_account_id' => 12,
2748 // Credit card = 1 so can pass 'by accident'.
2749 'payment_instrument_id' => 'Debit Card',
2752 if (!is_numeric($params['payment_processor_type_id'])) {
2753 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2755 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2756 'name' => $params['payment_processor_type_id'],
2760 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2761 return $result['id'];
2765 * Set up initial recurring payment allowing subsequent IPN payments.
2767 public function setupRecurringPaymentProcessorTransaction($params = array()) {
2768 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2769 'contact_id' => $this->_contactID
,
2772 'installments' => 5,
2773 'frequency_unit' => 'Month',
2774 'frequency_interval' => 1,
2775 'invoice_id' => $this->_invoiceID
,
2776 'contribution_status_id' => 2,
2777 'payment_processor_id' => $this->_paymentProcessorID
,
2778 // processor provided ID - use contact ID as proxy.
2779 'processor_id' => $this->_contactID
,
2780 'api.contribution.create' => array(
2781 'total_amount' => '200',
2782 'invoice_id' => $this->_invoiceID
,
2783 'financial_type_id' => 1,
2784 'contribution_status_id' => 'Pending',
2785 'contact_id' => $this->_contactID
,
2786 'contribution_page_id' => $this->_contributionPageID
,
2787 'payment_processor_id' => $this->_paymentProcessorID
,
2791 $this->_contributionRecurID
= $contributionRecur['id'];
2792 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2796 * 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
2798 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2800 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2801 $membershipParams = $recurParams = array();
2802 if (!empty($params['duration_unit'])) {
2803 $membershipParams['duration_unit'] = $params['duration_unit'];
2805 if (!empty($params['frequency_unit'])) {
2806 $recurParams['frequency_unit'] = $params['frequency_unit'];
2809 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2810 //create a contribution so our membership & contribution don't both have id = 1
2811 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2812 $this->contributionCreate(array(
2813 'contact_id' => $this->_contactID
,
2815 'financial_type_id' => 1,
2816 'invoice_id' => 'abcd',
2820 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2822 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2823 'contact_id' => $this->_contactID
,
2824 'membership_type_id' => $this->ids
['membership_type'],
2825 'contribution_recur_id' => $this->_contributionRecurID
,
2826 'format.only_id' => TRUE,
2828 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2829 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2831 $this->callAPISuccess('line_item', 'create', array(
2832 'entity_table' => 'civicrm_membership',
2833 'entity_id' => $this->ids
['membership'],
2834 'contribution_id' => $this->_contributionID
,
2835 'label' => 'General',
2837 'unit_price' => 200,
2838 'line_total' => 200,
2839 'financial_type_id' => 1,
2840 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2842 'label' => 'Membership Amount',
2843 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2845 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2847 'label' => 'General',
2848 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2851 $this->callAPISuccess('membership_payment', 'create', array(
2852 'contribution_id' => $this->_contributionID
,
2853 'membership_id' => $this->ids
['membership'],
2862 public function CiviUnitTestCase_fatalErrorHandler($message) {
2863 throw new Exception("{$message['message']}: {$message['code']}");
2867 * Helper function to create new mailing.
2869 * @param array $params
2873 public function createMailing($params = array()) {
2874 $params = array_merge(array(
2875 'subject' => 'maild' . rand(),
2876 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
2877 'name' => 'mailing name' . rand(),
2881 $result = $this->callAPISuccess('Mailing', 'create', $params);
2882 return $result['id'];
2886 * Helper function to delete mailing.
2889 public function deleteMailing($id) {
2894 $this->callAPISuccess('Mailing', 'delete', $params);
2898 * Wrap the entire test case in a transaction.
2900 * Only subsequent DB statements will be wrapped in TX -- this cannot
2901 * retroactively wrap old DB statements. Therefore, it makes sense to
2902 * call this at the beginning of setUp().
2904 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2905 * this option does not work with, e.g., custom-data.
2907 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2908 * if TRUNCATE or ALTER is called while using a transaction.
2911 * Whether to use nesting or reference-counting.
2913 public function useTransaction($nest = TRUE) {
2915 $this->tx
= new CRM_Core_Transaction($nest);
2916 $this->tx
->rollback();
2921 * Assert the attachment exists.
2923 * @param bool $exists
2924 * @param array $apiResult
2926 protected function assertAttachmentExistence($exists, $apiResult) {
2927 $fileId = $apiResult['id'];
2928 $this->assertTrue(is_numeric($fileId));
2929 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2930 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2931 1 => array($fileId, 'Int'),
2933 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2934 1 => array($fileId, 'Int'),
2939 * Create a price set for an event.
2941 * @param int $feeTotal
2942 * @param int $minAmt
2943 * @param string $type
2948 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2949 // creating price set, price field
2950 $paramsSet['title'] = 'Price Set';
2951 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2952 $paramsSet['is_active'] = FALSE;
2953 $paramsSet['extends'] = 1;
2954 $paramsSet['min_amount'] = $minAmt;
2956 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2957 $this->_ids
['price_set'] = $priceSet->id
;
2959 $paramsField = array(
2960 'label' => 'Price Field',
2961 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2962 'html_type' => $type,
2963 'price' => $feeTotal,
2964 'option_label' => array('1' => 'Price Field'),
2965 'option_value' => array('1' => $feeTotal),
2966 'option_name' => array('1' => $feeTotal),
2967 'option_weight' => array('1' => 1),
2968 'option_amount' => array('1' => 1),
2969 'is_display_amounts' => 1,
2971 'options_per_line' => 1,
2972 'is_active' => array('1' => 1),
2973 'price_set_id' => $this->_ids
['price_set'],
2974 'is_enter_qty' => 1,
2975 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2977 if ($type === 'Radio') {
2978 $paramsField['is_enter_qty'] = 0;
2979 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2980 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2982 CRM_Price_BAO_PriceField
::create($paramsField);
2983 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
2984 $this->_ids
['price_field'] = array_keys($fields['values']);
2985 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
2986 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2988 return $this->_ids
['price_set'];
2992 * Add a profile to a contribution page.
2994 * @param string $name
2995 * @param int $contributionPageID
2997 protected function addProfile($name, $contributionPageID) {
2998 $this->callAPISuccess('UFJoin', 'create', array(
2999 'uf_group_id' => $name,
3000 'module' => 'CiviContribute',
3001 'entity_table' => 'civicrm_contribution_page',
3002 'entity_id' => $contributionPageID,
3008 * Add participant with contribution
3012 protected function createParticipantWithContribution() {
3013 // creating price set, price field
3014 $this->_contactId
= $this->individualCreate();
3015 $event = $this->eventCreate();
3016 $this->_eventId
= $event['id'];
3017 $eventParams = array(
3018 'id' => $this->_eventId
,
3019 'financial_type_id' => 4,
3022 $this->callAPISuccess('event', 'create', $eventParams);
3023 $priceFields = $this->createPriceSet('event', $this->_eventId
);
3024 $participantParams = array(
3025 'financial_type_id' => 4,
3026 'event_id' => $this->_eventId
,
3029 'fee_currency' => 'USD',
3030 'contact_id' => $this->_contactId
,
3032 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3033 $contributionParams = array(
3034 'total_amount' => 150,
3035 'currency' => 'USD',
3036 'contact_id' => $this->_contactId
,
3037 'financial_type_id' => 4,
3038 'contribution_status_id' => 1,
3039 'partial_payment_total' => 300.00,
3040 'partial_amount_to_pay' => 150,
3041 'contribution_mode' => 'participant',
3042 'participant_id' => $participant['id'],
3044 foreach ($priceFields['values'] as $key => $priceField) {
3045 $lineItems[1][$key] = array(
3046 'price_field_id' => $priceField['price_field_id'],
3047 'price_field_value_id' => $priceField['id'],
3048 'label' => $priceField['label'],
3049 'field_title' => $priceField['label'],
3051 'unit_price' => $priceField['amount'],
3052 'line_total' => $priceField['amount'],
3053 'financial_type_id' => $priceField['financial_type_id'],
3056 $contributionParams['line_item'] = $lineItems;
3057 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3058 $paymentParticipant = array(
3059 'participant_id' => $participant['id'],
3060 'contribution_id' => $contribution['id'],
3062 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3063 return array($lineItems, $contribution);
3069 * @param string $component
3070 * @param int $componentId
3074 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
3075 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
3076 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
3077 $paramsSet['is_active'] = TRUE;
3078 $paramsSet['financial_type_id'] = 4;
3079 $paramsSet['extends'] = 1;
3080 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3081 $priceSetId = $priceSet['id'];
3082 //Checking for priceset added in the table.
3083 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3084 'id', $paramsSet['title'], 'Check DB for created priceset'
3086 $paramsField = array_merge(array(
3087 'label' => 'Price Field',
3088 'name' => CRM_Utils_String
::titleToVar('Price Field'),
3089 'html_type' => 'CheckBox',
3090 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3091 'option_value' => array('1' => 100, '2' => 200),
3092 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3093 'option_weight' => array('1' => 1, '2' => 2),
3094 'option_amount' => array('1' => 100, '2' => 200),
3095 'is_display_amounts' => 1,
3097 'options_per_line' => 1,
3098 'is_active' => array('1' => 1, '2' => 1),
3099 'price_set_id' => $priceSet['id'],
3100 'is_enter_qty' => 1,
3101 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3102 ), $priceFieldOptions);
3104 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
3106 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
3108 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
3112 * Replace the template with a test-oriented template designed to show all the variables.
3114 * @param string $templateName
3116 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
3117 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
3118 CRM_Core_DAO
::executeQuery(
3119 "UPDATE civicrm_option_group og
3120 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3121 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3122 SET m.msg_html = '{$testTemplate}'
3123 WHERE og.name = 'msg_tpl_workflow_contribution'
3124 AND ov.name = '{$templateName}'
3125 AND m.is_default = 1"
3130 * Reinstate the default template.
3132 * @param string $templateName
3134 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
3135 CRM_Core_DAO
::executeQuery(
3136 "UPDATE civicrm_option_group og
3137 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3138 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3139 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
3140 SET m.msg_html = m2.msg_html
3141 WHERE og.name = 'msg_tpl_workflow_contribution'
3142 AND ov.name = '{$templateName}'
3143 AND m.is_default = 1"
3148 * Flush statics relating to financial type.
3150 protected function flushFinancialTypeStatics() {
3151 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
3152 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
3154 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
3155 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
3157 CRM_Contribute_PseudoConstant
::flush('financialType');
3158 CRM_Contribute_PseudoConstant
::flush('membershipType');
3159 // Pseudoconstants may be saved to the cache table.
3160 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
3161 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
3162 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
3166 * Set the permissions to the supplied array.
3168 * @param array $permissions
3170 protected function setPermissions($permissions) {
3171 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
3172 $this->flushFinancialTypeStatics();
3176 * @param array $params
3179 public function _checkFinancialRecords($params, $context) {
3180 $entityParams = array(
3181 'entity_id' => $params['id'],
3182 'entity_table' => 'civicrm_contribution',
3184 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3185 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3186 if ($context == 'pending') {
3187 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
3188 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3191 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3192 $trxnParams = array(
3193 'id' => $trxn['financial_trxn_id'],
3195 if ($context != 'online' && $context != 'payLater') {
3196 $compareParams = array(
3197 'to_financial_account_id' => 6,
3198 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3202 if ($context == 'feeAmount') {
3203 $compareParams['fee_amount'] = 50;
3205 elseif ($context == 'online') {
3206 $compareParams = array(
3207 'to_financial_account_id' => 12,
3208 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3210 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
3213 elseif ($context == 'payLater') {
3214 $compareParams = array(
3215 'to_financial_account_id' => 7,
3216 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3220 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3221 $entityParams = array(
3222 'financial_trxn_id' => $trxn['financial_trxn_id'],
3223 'entity_table' => 'civicrm_financial_item',
3225 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3226 $fitemParams = array(
3227 'id' => $entityTrxn['entity_id'],
3229 $compareParams = array(
3230 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3232 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3234 if ($context == 'payLater') {
3235 $compareParams = array(
3236 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
3238 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
3241 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3242 if ($context == 'feeAmount') {
3244 'entity_id' => $params['id'],
3245 'entity_table' => 'civicrm_contribution',
3247 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
3248 $trxnParams = array(
3249 'id' => $maxTrxn['financial_trxn_id'],
3251 $compareParams = array(
3252 'to_financial_account_id' => 5,
3253 'from_financial_account_id' => 6,
3254 'total_amount' => 50,
3257 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
3258 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3259 $fitemParams = array(
3260 'entity_id' => $trxnId['financialTrxnId'],
3261 'entity_table' => 'civicrm_financial_trxn',
3263 $compareParams = array(
3266 'financial_account_id' => 5,
3268 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3270 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3271 // line should be copied into all the functions that call this function & evaluated there
3272 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3273 // when calling completeTransaction or repeatTransaction.
3274 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
3278 * Return financial type id on basis of name
3280 * @param string $name Financial type m/c name
3284 public function getFinancialTypeId($name) {
3285 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
3289 * Cleanup function for contents of $this->ids.
3291 * This is a best effort cleanup to use in tear downs etc.
3293 * It will not fail if the data has already been removed (some tests may do
3294 * their own cleanup).
3296 protected function cleanUpSetUpIDs() {
3297 foreach ($this->setupIDs
as $entity => $id) {
3299 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
3301 catch (CiviCRM_API3_Exception
$e) {
3302 // This is a best-effort cleanup function, ignore.
3308 * Create Financial Type.
3310 * @param array $params
3314 protected function createFinancialType($params = array()) {
3315 $params = array_merge($params,
3317 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
3321 return $this->callAPISuccess('FinancialType', 'create', $params);
3325 * Enable Tax and Invoicing
3327 protected function enableTaxAndInvoicing($params = array()) {
3328 // Enable component contribute setting
3329 $contributeSetting = array_merge($params,
3332 'invoice_prefix' => 'INV_',
3333 'credit_notes_prefix' => 'CN_',
3335 'due_date_period' => 'days',
3337 'is_email_pdf' => 1,
3338 'tax_term' => 'Sales Tax',
3339 'tax_display_settings' => 'Inclusive',
3342 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3346 * Enable Tax and Invoicing
3348 protected function disableTaxAndInvoicing($params = array()) {
3349 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
3350 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
3352 // Enable component contribute setting
3353 $contributeSetting = array_merge($params,
3358 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
3362 * Add Sales Tax relation for financial type with financial account.
3364 * @param int $financialTypeId
3368 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3370 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3371 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3372 'is_deductible' => 1,
3377 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3378 $entityParams = array(
3379 'entity_table' => 'civicrm_financial_type',
3380 'entity_id' => $financialTypeId,
3381 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3384 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3385 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3387 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3388 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3389 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3390 $dao->copyValues($entityParams);
3392 if ($dao->fetch()) {
3393 $entityParams['id'] = $dao->id
;
3395 $entityParams['financial_account_id'] = $account->id
;
3397 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3401 * Create price set with contribution test for test setup.
3403 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3404 * on parent class at some point (fn is not in 4.4).
3407 * @param array $params
3409 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3410 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3411 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3412 'title' => "Test Contribution Page",
3413 'financial_type_id' => 1,
3414 'currency' => 'NZD',
3415 'goal_amount' => 50,
3416 'is_pay_later' => 1,
3417 'is_monetary' => TRUE,
3418 'is_email_receipt' => FALSE,
3420 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3421 'is_quick_config' => 0,
3422 'extends' => 'CiviMember',
3423 'financial_type_id' => 1,
3424 'title' => 'my Page',
3426 $priceSetID = $priceSet['id'];
3428 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3429 $priceField = $this->callAPISuccess('price_field', 'create', array(
3430 'price_set_id' => $priceSetID,
3431 'label' => 'Goat Breed',
3432 'html_type' => 'Radio',
3434 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3435 'price_set_id' => $priceSetID,
3436 'price_field_id' => $priceField['id'],
3437 'label' => 'Long Haired Goat',
3439 'financial_type_id' => 'Donation',
3440 'membership_type_id' => $membershipTypeID,
3441 'membership_num_terms' => 1,
3444 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3445 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3446 'price_set_id' => $priceSetID,
3447 'price_field_id' => $priceField['id'],
3448 'label' => 'Shoe-eating Goat',
3450 'financial_type_id' => 'Donation',
3451 'membership_type_id' => $membershipTypeID,
3452 'membership_num_terms' => 2,
3455 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3457 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3458 'price_set_id' => $priceSetID,
3459 'price_field_id' => $priceField['id'],
3460 'label' => 'Shoe-eating Goat',
3462 'financial_type_id' => 'Donation',
3465 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3467 $this->_ids
['price_set'] = $priceSetID;
3468 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3469 $this->_ids
['price_field'] = array($priceField['id']);
3471 $this->_ids
['membership_type'] = $membershipTypeID;
3475 * No results returned.
3477 * @implements CRM_Utils_Hook::aclWhereClause
3479 * @param string $type
3480 * @param array $tables
3481 * @param array $whereTables
3482 * @param int $contactID
3483 * @param string $where
3485 public function aclWhereHookNoResults($type, &$tables, &$whereTables, &$contactID, &$where) {
3489 * Only specified contact returned.
3490 * @implements CRM_Utils_Hook::aclWhereClause
3493 * @param $whereTables
3497 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3498 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3502 * @implements CRM_Utils_Hook::selectWhereClause
3504 * @param string $entity
3505 * @param array $clauses
3507 public function selectWhereClauseHook($entity, &$clauses) {
3508 if ($entity == 'Event') {
3509 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3514 * An implementation of hook_civicrm_post used with all our test cases.
3517 * @param string $objectName
3518 * @param int $objectId
3521 public function onPost($op, $objectName, $objectId, &$objectRef) {
3522 if ($op == 'create' && $objectName == 'Individual') {
3523 CRM_Core_DAO
::executeQuery(
3524 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3526 1 => array($objectId, 'Integer'),
3531 if ($op == 'edit' && $objectName == 'Participant') {
3533 1 => array($objectId, 'Integer'),
3535 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3536 CRM_Core_DAO
::executeQuery($query, $params);
3542 * Instantiate form object.
3544 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3546 * @param string $class
3547 * Name of form class.
3549 * @return \CRM_Core_Form
3551 public function getFormObject($class) {
3552 $form = new $class();
3553 $_SERVER['REQUEST_METHOD'] = 'GET';
3554 $form->controller
= new CRM_Core_Controller();
3559 * Get possible thousand separators.
3563 public function getThousandSeparators() {
3564 return array(array('.'), array(','));
3568 * Set the separators for thousands and decimal points.
3570 * @param string $thousandSeparator
3572 protected function setCurrencySeparators($thousandSeparator) {
3573 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3575 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3579 * Format money as it would be input.
3581 * @param string $amount
3585 protected function formatMoneyInput($amount) {
3586 return CRM_Utils_Money
::format($amount, NULL, '%a');
3591 * Get the contribution object.
3593 * @param int $contributionID
3595 * @return \CRM_Contribute_BAO_Contribution
3597 protected function getContributionObject($contributionID) {
3598 $contributionObj = new CRM_Contribute_BAO_Contribution();
3599 $contributionObj->id
= $contributionID;
3600 $contributionObj->find(TRUE);
3601 return $contributionObj;