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\Framework\TestCase
{
56 use \Civi\Test\Api3DocTrait
;
57 use \Civi\Test\GenericAssertionsTrait
;
58 use \Civi\Test\DbTestTrait
;
59 use \Civi\Test\ContactTestTrait
;
60 use \Civi\Test\MailingTestTrait
;
63 * Database has been initialized.
67 private static $dbInit = FALSE;
70 * Database connection.
72 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
81 static protected $_dbName;
84 * Track tables we have modified during a test.
87 protected $_tablesToTruncate = array();
90 * @var array of temporary directory names
95 * @var bool populateOnce allows to skip db resets in setUp
97 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
98 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
101 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
103 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
105 public static $populateOnce = FALSE;
108 * @var bool DBResetRequired allows skipping DB reset
109 * in specific test case. If you still need
110 * to reset single test (method) of such case, call
111 * $this->cleanDB() in the first line of this
114 public $DBResetRequired = TRUE;
117 * @var CRM_Core_Transaction|NULL
122 * Array of IDs created to support the test.
125 * $this->ids = ['Contact' => ['descriptive_key' => $contactID], 'Group' => [$groupID]];
132 * Class used for hooks during tests.
134 * This can be used to test hooks within tests. For example in the ACL_PermissionTrait:
136 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
138 * @var CRM_Utils_Hook_UnitTests hookClass
140 public $hookClass = NULL;
143 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
145 protected $_params = array();
148 * @var CRM_Extension_System
150 protected $origExtensionSystem;
153 * Array of IDs created during test setup routine.
155 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
159 public $setupIDs = array();
162 * PHPUnit Mock Method to use.
166 public $mockMethod = 'getMock';
171 * Because we are overriding the parent class constructor, we
172 * need to show the same arguments as exist in the constructor of
173 * PHPUnit_Framework_TestCase, since
174 * PHPUnit_Framework_TestSuite::createTest() creates a
175 * ReflectionClass of the Test class and checks the constructor
176 * of that class to decide how to set up the test.
178 * @param string $name
180 * @param string $dataName
182 public function __construct($name = NULL, array $data = array(), $dataName = '') {
183 parent
::__construct($name, $data, $dataName);
185 // we need full error reporting
186 error_reporting(E_ALL
& ~E_NOTICE
);
188 self
::$_dbName = self
::getDBName();
190 // also load the class loader
191 require_once 'CRM/Core/ClassLoader.php';
192 CRM_Core_ClassLoader
::singleton()->register();
193 if (function_exists('_civix_phpunit_setUp')) {
194 // FIXME: loosen coupling
195 _civix_phpunit_setUp();
197 if (class_exists('PHPUnit_Runner_Version') && version_compare(\PHPUnit_Runner_Version
::id(), '5', '>=')) {
198 $this->mockMethod
= 'createMock';
200 elseif (class_exists('PHPUnit\Runner\Version') && version_compare(PHPUnit\Runner\Version
::id(), '6', '>=')) {
201 $this->mockMethod
= 'createMock';
206 * Override to run the test and assert its state.
209 * @throws \PHPUnit_Framework_IncompleteTest
210 * @throws \PHPUnit_Framework_SkippedTest
212 protected function runTest() {
214 return parent
::runTest();
216 catch (PEAR_Exception
$e) {
217 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
218 throw new Exception(\CRM_Core_Error
::formatTextException($e), $e->getCode());
225 public function requireDBReset() {
226 return $this->DBResetRequired
;
232 public static function getDBName() {
233 static $dbName = NULL;
234 if ($dbName === NULL) {
235 require_once "DB.php";
236 $dsninfo = DB
::parseDSN(CIVICRM_DSN
);
237 $dbName = $dsninfo['database'];
243 * Create database connection for this instance.
245 * Initialize the test database if it hasn't been initialized
248 protected function getConnection() {
249 if (!self
::$dbInit) {
250 $dbName = self
::getDBName();
252 // install test database
253 echo PHP_EOL
. "Installing {$dbName} database" . PHP_EOL
;
255 static::_populateDB(FALSE, $this);
257 self
::$dbInit = TRUE;
263 * Required implementation of abstract method.
265 protected function getDataSet() {
269 * @param bool $perClass
270 * @param null $object
272 * TRUE if the populate logic runs; FALSE if it is skipped
274 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
275 if (CIVICRM_UF
!== 'UnitTests') {
276 throw new \
RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
279 if ($perClass ||
$object == NULL) {
283 $dbreset = $object->requireDBReset();
286 if (self
::$populateOnce ||
!$dbreset) {
289 self
::$populateOnce = NULL;
291 Civi\Test
::data()->populate();
296 public static function setUpBeforeClass() {
297 static::_populateDB(TRUE);
299 // also set this global hack
300 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
304 * Common setup functions for all unit tests.
306 protected function setUp() {
307 $session = CRM_Core_Session
::singleton();
308 $session->set('userID', NULL);
310 $this->_apiversion
= 3;
313 $this->errorScope
= CRM_Core_TemporaryErrorScope
::useException();
314 // Use a temporary file for STDIN
315 $GLOBALS['stdin'] = tmpfile();
316 if ($GLOBALS['stdin'] === FALSE) {
317 echo "Couldn't open temporary file\n";
321 // Get and save a connection to the database
322 $this->_dbconn
= $this->getConnection();
324 // reload database before each test
325 // $this->_populateDB();
327 // "initialize" CiviCRM to avoid problems when running single tests
328 // FIXME: look at it closer in second stage
330 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
331 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
333 // disable any left-over test extensions
334 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
336 $extensions = \CRM_Extension_System
::singleton()->getManager();
337 $api4Status = $extensions->getStatus('org.civicrm.api4');
338 if ($api4Status != $extensions::STATUS_INSTALLED
&& $api4Status != $extensions::STATUS_UNKNOWN
) {
339 $extensions->enable(['org.civicrm.api4']);
342 // reset all the caches
343 CRM_Utils_System
::flushCache();
345 // initialize the object once db is loaded
348 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
350 // when running unit tests, use mockup user framework
351 $this->hookClass
= CRM_Utils_Hook
::singleton();
353 // Make sure the DB connection is setup properly
354 $config->userSystem
->setMySQLTimeZone();
355 $env = new CRM_Utils_Check_Component_Env();
356 CRM_Utils_Check
::singleton()->assertValid($env->checkMysqlTime());
358 // clear permissions stub to not check permissions
359 $config->userPermissionClass
->permissions
= NULL;
361 //flush component settings
362 CRM_Core_Component
::getEnabledComponents(TRUE);
364 $_REQUEST = $_GET = $_POST = [];
365 error_reporting(E_ALL
);
367 $this->_sethtmlGlobals();
371 * Read everything from the datasets directory and insert into the db.
373 public function loadAllFixtures() {
374 $fixturesDir = __DIR__
. '/../../fixtures';
376 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
378 $jsonFiles = glob($fixturesDir . '/*.json');
379 foreach ($jsonFiles as $jsonFixture) {
380 $json = json_decode(file_get_contents($jsonFixture));
381 foreach ($json as $tableName => $vars) {
382 if ($tableName === 'civicrm_contact') {
383 CRM_Core_DAO
::executeQuery('DELETE c FROM civicrm_contact c LEFT JOIN civicrm_domain d ON d.contact_id = c.id WHERE d.id IS NULL');
386 CRM_Core_DAO
::executeQuery("TRUNCATE $tableName");
388 foreach ($vars as $entity) {
389 $keys = $values = [];
390 foreach ($entity as $key => $value) {
392 $values[] = is_numeric($value) ?
$value : "'{$value}'";
394 CRM_Core_DAO
::executeQuery("
395 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
402 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
406 * Load the data that used to be handled by the discontinued dbunit class.
408 * This could do with further tidy up - the initial priority is simply to get rid of
409 * the dbunity package which is no longer supported.
411 * @param string $fileName
413 protected function loadXMLDataSet($fileName) {
414 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 0');
415 $xml = json_decode(json_encode(simplexml_load_file($fileName)), TRUE);
416 foreach ($xml as $tableName => $element) {
417 if (!empty($element)) {
418 foreach ($element as $row) {
419 $keys = $values = [];
420 if (isset($row['@attributes'])) {
421 foreach ($row['@attributes'] as $key => $value) {
423 $values[] = is_numeric($value) ?
$value : "'{$value}'";
426 elseif (!empty($row)) {
427 // cos we copied it & it is inconsistent....
428 foreach ($row as $key => $value) {
430 $values[] = is_numeric($value) ?
$value : "'{$value}'";
434 if (!empty($values)) {
435 CRM_Core_DAO
::executeQuery("
436 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
442 CRM_Core_DAO
::executeQuery('SET FOREIGN_KEY_CHECKS = 1');
446 * Create default domain contacts for the two domains added during test class.
447 * database population.
449 public function createDomainContacts() {
450 $this->organizationCreate();
451 $this->organizationCreate(array('organization_name' => 'Second Domain'));
455 * Common teardown functions for all unit tests.
457 protected function tearDown() {
458 $this->_apiversion
= 3;
460 error_reporting(E_ALL
& ~E_NOTICE
);
461 CRM_Utils_Hook
::singleton()->reset();
462 if ($this->hookClass
) {
463 $this->hookClass
->reset();
465 CRM_Core_Session
::singleton()->reset(1);
468 $this->tx
->rollback()->commit();
471 CRM_Core_Transaction
::forceRollbackIfEnabled();
472 \Civi\Core\Transaction\Manager
::singleton(TRUE);
475 CRM_Core_Transaction
::forceRollbackIfEnabled();
476 \Civi\Core\Transaction\Manager
::singleton(TRUE);
478 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
479 $this->quickCleanup($tablesToTruncate);
480 $this->createDomainContacts();
483 $this->cleanTempDirs();
484 $this->unsetExtensionSystem();
488 * Create a batch of external API calls which can
489 * be executed concurrently.
492 * $calls = $this->createExternalAPI()
493 * ->addCall('Contact', 'get', ...)
494 * ->addCall('Contact', 'get', ...)
500 * @return \Civi\API\ExternalBatch
501 * @throws PHPUnit_Framework_SkippedTestError
503 public function createExternalAPI() {
504 global $civicrm_root;
505 $defaultParams = array(
506 'version' => $this->_apiversion
,
510 $calls = new \Civi\API\
ExternalBatch($defaultParams);
512 if (!$calls->isSupported()) {
513 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
520 * Create required data based on $this->entity & $this->params
521 * This is just a way to set up the test data for delete & get functions
522 * so the distinction between set
523 * up & tested functions is clearer
528 public function createTestEntity() {
529 return $entity = $this->callAPISuccess($this->entity
, 'create', $this->params
);
533 * @param int $contactTypeId
537 public function contactTypeDelete($contactTypeId) {
538 $result = CRM_Contact_BAO_ContactType
::del($contactTypeId);
540 throw new Exception('Could not delete contact type');
545 * @param array $params
549 public function membershipTypeCreate($params = array()) {
550 CRM_Member_PseudoConstant
::flush('membershipType');
551 CRM_Core_Config
::clearDBCache();
552 $this->setupIDs
['contact'] = $memberOfOrganization = $this->organizationCreate();
553 $params = array_merge(array(
555 'duration_unit' => 'year',
556 'duration_interval' => 1,
557 'period_type' => 'rolling',
558 'member_of_contact_id' => $memberOfOrganization,
560 'financial_type_id' => 2,
563 'visibility' => 'Public',
566 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
568 CRM_Member_PseudoConstant
::flush('membershipType');
569 CRM_Utils_Cache
::singleton()->flush();
571 return $result['id'];
575 * @param array $params
579 public function contactMembershipCreate($params) {
580 $params = array_merge(array(
581 'join_date' => '2007-01-21',
582 'start_date' => '2007-01-21',
583 'end_date' => '2007-12-21',
584 'source' => 'Payment',
585 'membership_type_id' => 'General',
587 if (!is_numeric($params['membership_type_id'])) {
588 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
589 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
590 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
594 $result = $this->callAPISuccess('Membership', 'create', $params);
595 return $result['id'];
599 * Delete Membership Type.
601 * @param array $params
603 public function membershipTypeDelete($params) {
604 $this->callAPISuccess('MembershipType', 'Delete', $params);
608 * @param int $membershipID
610 public function membershipDelete($membershipID) {
611 $deleteParams = array('id' => $membershipID);
612 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
616 * @param string $name
620 public function membershipStatusCreate($name = 'test member status') {
621 $params['name'] = $name;
622 $params['start_event'] = 'start_date';
623 $params['end_event'] = 'end_date';
624 $params['is_current_member'] = 1;
625 $params['is_active'] = 1;
627 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
628 CRM_Member_PseudoConstant
::flush('membershipStatus');
629 return $result['id'];
633 * @param int $membershipStatusID
635 public function membershipStatusDelete($membershipStatusID) {
636 if (!$membershipStatusID) {
639 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
642 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
643 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
644 $renewedMembershipEndDate = new DateTime($membershipEndDate);
645 switch ($durationUnit) {
647 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
651 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
652 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
653 $renewedMembershipEndDate->add(new DateInterval('P1D'));
654 $renewedMembershipEndDate->add(new DateInterval('P1M'));
655 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
658 return $renewedMembershipEndDate->format('Y-m-d');
662 * @param array $params
666 public function relationshipTypeCreate($params = array()) {
667 $params = array_merge(array(
668 'name_a_b' => 'Relation 1 for relationship type create',
669 'name_b_a' => 'Relation 2 for relationship type create',
670 'contact_type_a' => 'Individual',
671 'contact_type_b' => 'Organization',
676 $result = $this->callAPISuccess('relationship_type', 'create', $params);
677 CRM_Core_PseudoConstant
::flush('relationshipType');
679 return $result['id'];
683 * Delete Relatinship Type.
685 * @param int $relationshipTypeID
687 public function relationshipTypeDelete($relationshipTypeID) {
688 $params['id'] = $relationshipTypeID;
689 $check = $this->callAPISuccess('relationship_type', 'get', $params);
690 if (!empty($check['count'])) {
691 $this->callAPISuccess('relationship_type', 'delete', $params);
696 * @param array $params
700 public function paymentProcessorTypeCreate($params = NULL) {
701 if (is_null($params)) {
703 'name' => 'API_Test_PP',
704 'title' => 'API Test Payment Processor',
705 'class_name' => 'CRM_Core_Payment_APITest',
706 'billing_mode' => 'form',
712 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
714 CRM_Core_PseudoConstant
::flush('paymentProcessorType');
716 return $result['id'];
720 * Create test Authorize.net instance.
722 * @param array $params
726 public function paymentProcessorAuthorizeNetCreate($params = array()) {
727 $params = array_merge(array(
728 'name' => 'Authorize',
729 'domain_id' => CRM_Core_Config
::domainID(),
730 'payment_processor_type_id' => 'AuthNet',
731 'title' => 'AuthNet',
736 'user_name' => '4y5BfuW7jm',
737 'password' => '4cAmW927n8uLf5J8',
738 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
739 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
740 'class_name' => 'Payment_AuthorizeNet',
744 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
745 return $result['id'];
749 * Create Participant.
751 * @param array $params
752 * Array of contact id and event id values.
755 * $id of participant created
757 public function participantCreate($params = []) {
758 if (empty($params['contact_id'])) {
759 $params['contact_id'] = $this->individualCreate();
761 if (empty($params['event_id'])) {
762 $event = $this->eventCreate();
763 $params['event_id'] = $event['id'];
768 'register_date' => 20070219,
769 'source' => 'Wimbeldon',
770 'event_level' => 'Payment',
774 $params = array_merge($defaults, $params);
775 $result = $this->callAPISuccess('Participant', 'create', $params);
776 return $result['id'];
780 * Create Payment Processor.
783 * Id Payment Processor
785 public function processorCreate($params = array()) {
786 $processorParams = array(
789 'payment_processor_type_id' => 'Dummy',
790 'financial_account_id' => 12,
794 'url_site' => 'http://dummy.com',
795 'url_recur' => 'http://dummy.com',
798 'payment_instrument_id' => 'Debit Card',
800 $processorParams = array_merge($processorParams, $params);
801 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
802 return $processor['id'];
806 * Create Payment Processor.
808 * @param array $processorParams
810 * @return \CRM_Core_Payment_Dummy
811 * Instance of Dummy Payment Processor
813 public function dummyProcessorCreate($processorParams = array()) {
814 $paymentProcessorID = $this->processorCreate($processorParams);
815 return System
::singleton()->getById($paymentProcessorID);
819 * Create contribution page.
821 * @param array $params
823 * Array of contribution page
825 public function contributionPageCreate($params = array()) {
826 $this->_pageParams
= array_merge(array(
827 'title' => 'Test Contribution Page',
828 'financial_type_id' => 1,
830 'financial_account_id' => 1,
832 'is_allow_other_amount' => 1,
834 'max_amount' => 1000,
836 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
840 * Create a sample batch.
842 public function batchCreate() {
843 $params = $this->_params
;
844 $params['name'] = $params['title'] = 'Batch_433397';
845 $params['status_id'] = 1;
846 $result = $this->callAPISuccess('batch', 'create', $params);
847 return $result['id'];
853 * @param array $params
855 * result of created tag
857 public function tagCreate($params = array()) {
859 'name' => 'New Tag3',
860 'description' => 'This is description for Our New Tag ',
863 $params = array_merge($defaults, $params);
864 $result = $this->callAPISuccess('Tag', 'create', $params);
865 return $result['values'][$result['id']];
872 * Id of the tag to be deleted.
876 public function tagDelete($tagId) {
877 require_once 'api/api.php';
881 $result = $this->callAPISuccess('Tag', 'delete', $params);
882 return $result['id'];
886 * Add entity(s) to the tag
888 * @param array $params
892 public function entityTagAdd($params) {
893 $result = $this->callAPISuccess('entity_tag', 'create', $params);
900 * @param array $params
904 * id of created pledge
906 public function pledgeCreate($params) {
907 $params = array_merge(array(
908 'pledge_create_date' => date('Ymd'),
909 'start_date' => date('Ymd'),
910 'scheduled_date' => date('Ymd'),
912 'pledge_status_id' => '2',
913 'financial_type_id' => '1',
914 'pledge_original_installment_amount' => 20,
915 'frequency_interval' => 5,
916 'frequency_unit' => 'year',
917 'frequency_day' => 15,
922 $result = $this->callAPISuccess('Pledge', 'create', $params);
923 return $result['id'];
927 * Delete contribution.
929 * @param int $pledgeId
931 public function pledgeDelete($pledgeId) {
933 'pledge_id' => $pledgeId,
935 $this->callAPISuccess('Pledge', 'delete', $params);
939 * Create contribution.
941 * @param array $params
942 * Array of parameters.
945 * id of created contribution
947 public function contributionCreate($params) {
949 $params = array_merge(array(
951 'receive_date' => date('Ymd'),
952 'total_amount' => 100.00,
953 'fee_amount' => 5.00,
954 'financial_type_id' => 1,
955 'payment_instrument_id' => 1,
956 'non_deductible_amount' => 10.00,
958 'contribution_status_id' => 1,
961 $result = $this->callAPISuccess('contribution', 'create', $params);
962 return $result['id'];
966 * Delete contribution.
968 * @param int $contributionId
972 public function contributionDelete($contributionId) {
974 'contribution_id' => $contributionId,
976 $result = $this->callAPISuccess('contribution', 'delete', $params);
983 * @param array $params
984 * Name-value pair for an event.
988 public function eventCreate($params = array()) {
989 // if no contact was passed, make up a dummy event creator
990 if (!isset($params['contact_id'])) {
991 $params['contact_id'] = $this->_contactCreate(array(
992 'contact_type' => 'Individual',
993 'first_name' => 'Event',
994 'last_name' => 'Creator',
998 // set defaults for missing params
999 $params = array_merge(array(
1000 'title' => 'Annual CiviCRM meet',
1001 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1002 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1003 'event_type_id' => 1,
1005 'start_date' => 20081021,
1006 'end_date' => 20081023,
1007 'is_online_registration' => 1,
1008 'registration_start_date' => 20080601,
1009 'registration_end_date' => 20081015,
1010 'max_participants' => 100,
1011 'event_full_text' => 'Sorry! We are already full',
1014 'is_show_location' => 0,
1017 return $this->callAPISuccess('Event', 'create', $params);
1021 * Create a paid event.
1023 * @param array $params
1027 protected function eventCreatePaid($params) {
1028 $event = $this->eventCreate($params);
1029 $this->priceSetID
= $this->eventPriceSetCreate(55, 0, 'Radio');
1030 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $event['id'], $this->priceSetID
);
1031 $priceSet = CRM_Price_BAO_PriceSet
::getSetDetail($this->priceSetID
, TRUE, FALSE);
1032 $priceSet = CRM_Utils_Array
::value($this->priceSetID
, $priceSet);
1033 $this->eventFeeBlock
= CRM_Utils_Array
::value('fields', $priceSet);
1045 public function eventDelete($id) {
1049 return $this->callAPISuccess('event', 'delete', $params);
1053 * Delete participant.
1055 * @param int $participantID
1059 public function participantDelete($participantID) {
1061 'id' => $participantID,
1063 $check = $this->callAPISuccess('Participant', 'get', $params);
1064 if ($check['count'] > 0) {
1065 return $this->callAPISuccess('Participant', 'delete', $params);
1070 * Create participant payment.
1072 * @param int $participantID
1073 * @param int $contributionID
1075 * $id of created payment
1077 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1078 //Create Participant Payment record With Values
1080 'participant_id' => $participantID,
1081 'contribution_id' => $contributionID,
1084 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1085 return $result['id'];
1089 * Delete participant payment.
1091 * @param int $paymentID
1093 public function participantPaymentDelete($paymentID) {
1097 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1103 * @param int $contactID
1105 * location id of created location
1107 public function locationAdd($contactID) {
1110 'location_type' => 'New Location Type',
1112 'name' => 'Saint Helier St',
1113 'county' => 'Marin',
1114 'country' => 'UNITED STATES',
1115 'state_province' => 'Michigan',
1116 'supplemental_address_1' => 'Hallmark Ct',
1117 'supplemental_address_2' => 'Jersey Village',
1118 'supplemental_address_3' => 'My Town',
1123 'contact_id' => $contactID,
1124 'address' => $address,
1125 'location_format' => '2.0',
1126 'location_type' => 'New Location Type',
1129 $result = $this->callAPISuccess('Location', 'create', $params);
1134 * Delete Locations of contact.
1136 * @param array $params
1139 public function locationDelete($params) {
1140 $this->callAPISuccess('Location', 'delete', $params);
1144 * Add a Location Type.
1146 * @param array $params
1147 * @return CRM_Core_DAO_LocationType
1148 * location id of created location
1150 public function locationTypeCreate($params = NULL) {
1151 if ($params === NULL) {
1153 'name' => 'New Location Type',
1154 'vcard_name' => 'New Location Type',
1155 'description' => 'Location Type for Delete',
1160 $locationType = new CRM_Core_DAO_LocationType();
1161 $locationType->copyValues($params);
1162 $locationType->save();
1163 // clear getfields cache
1164 CRM_Core_PseudoConstant
::flush();
1165 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1166 return $locationType;
1170 * Delete a Location Type.
1172 * @param int $locationTypeId
1174 public function locationTypeDelete($locationTypeId) {
1175 $locationType = new CRM_Core_DAO_LocationType();
1176 $locationType->id
= $locationTypeId;
1177 $locationType->delete();
1183 * @param array $params
1184 * @return CRM_Core_DAO_Mapping
1185 * Mapping id of created mapping
1187 public function mappingCreate($params = NULL) {
1188 if ($params === NULL) {
1190 'name' => 'Mapping name',
1191 'description' => 'Mapping description',
1192 // 'Export Contact' mapping.
1193 'mapping_type_id' => 7,
1197 $mapping = new CRM_Core_DAO_Mapping();
1198 $mapping->copyValues($params);
1200 // clear getfields cache
1201 CRM_Core_PseudoConstant
::flush();
1202 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1209 * @param int $mappingId
1211 public function mappingDelete($mappingId) {
1212 $mapping = new CRM_Core_DAO_Mapping();
1213 $mapping->id
= $mappingId;
1218 * Prepare class for ACLs.
1220 protected function prepareForACLs() {
1221 $config = CRM_Core_Config
::singleton();
1222 $config->userPermissionClass
->permissions
= array();
1228 protected function cleanUpAfterACLs() {
1229 CRM_Utils_Hook
::singleton()->reset();
1230 $tablesToTruncate = array(
1232 'civicrm_acl_cache',
1233 'civicrm_acl_entity_role',
1234 'civicrm_acl_contact_cache',
1236 $this->quickCleanup($tablesToTruncate);
1237 $config = CRM_Core_Config
::singleton();
1238 unset($config->userPermissionClass
->permissions
);
1242 * Create a smart group.
1244 * By default it will be a group of households.
1246 * @param array $smartGroupParams
1247 * @param array $groupParams
1250 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1251 $smartGroupParams = array_merge(array(
1252 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1255 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($smartGroupParams);
1257 $groupParams['saved_search_id'] = $savedSearch->id
;
1258 return $this->groupCreate($groupParams);
1263 * @param array $params
1265 public function uFFieldCreate($params = array()) {
1266 $params = array_merge(array(
1268 'field_name' => 'first_name',
1271 'visibility' => 'Public Pages and Listings',
1272 'is_searchable' => '1',
1273 'label' => 'first_name',
1274 'field_type' => 'Individual',
1277 $this->callAPISuccess('uf_field', 'create', $params);
1281 * Add a UF Join Entry.
1283 * @param array $params
1285 * $id of created UF Join
1287 public function ufjoinCreate($params = NULL) {
1288 if ($params === NULL) {
1291 'module' => 'CiviEvent',
1292 'entity_table' => 'civicrm_event',
1298 $result = $this->callAPISuccess('uf_join', 'create', $params);
1303 * @param array $params
1304 * Optional parameters.
1305 * @param bool $reloadConfig
1306 * While enabling CiviCampaign component, we shouldn't always forcibly
1307 * reload config as this hinder hook call in test environment
1312 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1313 $this->enableCiviCampaign($reloadConfig);
1314 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1315 'name' => 'big_campaign',
1316 'title' => 'Campaign',
1318 return $campaign['id'];
1322 * Create Group for a contact.
1324 * @param int $contactId
1326 public function contactGroupCreate($contactId) {
1328 'contact_id.1' => $contactId,
1332 $this->callAPISuccess('GroupContact', 'Create', $params);
1336 * Delete Group for a contact.
1338 * @param int $contactId
1340 public function contactGroupDelete($contactId) {
1342 'contact_id.1' => $contactId,
1345 $this->civicrm_api('GroupContact', 'Delete', $params);
1351 * @param array $params
1354 public function activityCreate($params = array()) {
1355 $params = array_merge(array(
1356 'subject' => 'Discussion on warm beer',
1357 'activity_date_time' => date('Ymd'),
1358 'duration_hours' => 30,
1359 'duration_minutes' => 20,
1360 'location' => 'Baker Street',
1361 'details' => 'Lets schedule a meeting',
1363 'activity_type_id' => 'Meeting',
1365 if (!isset($params['source_contact_id'])) {
1366 $params['source_contact_id'] = $this->individualCreate();
1368 if (!isset($params['target_contact_id'])) {
1369 $params['target_contact_id'] = $this->individualCreate(array(
1370 'first_name' => 'Julia',
1371 'Last_name' => 'Anderson',
1373 'email' => 'julia_anderson@civicrm.org',
1374 'contact_type' => 'Individual',
1377 if (!isset($params['assignee_contact_id'])) {
1378 $params['assignee_contact_id'] = $params['target_contact_id'];
1381 $result = civicrm_api3('Activity', 'create', $params);
1383 $result['target_contact_id'] = $params['target_contact_id'];
1384 $result['assignee_contact_id'] = $params['assignee_contact_id'];
1389 * Create an activity type.
1391 * @param array $params
1395 public function activityTypeCreate($params) {
1396 return $this->callAPISuccess('ActivityType', 'create', $params);
1400 * Delete activity type.
1402 * @param int $activityTypeId
1403 * Id of the activity type.
1406 public function activityTypeDelete($activityTypeId) {
1407 $params['activity_type_id'] = $activityTypeId;
1408 return $this->callAPISuccess('ActivityType', 'delete', $params);
1412 * Create custom group.
1414 * @param array $params
1417 public function customGroupCreate($params = array()) {
1419 'title' => 'new custom group',
1420 'extends' => 'Contact',
1422 'style' => 'Inline',
1426 $params = array_merge($defaults, $params);
1428 return $this->callAPISuccess('custom_group', 'create', $params);
1432 * Existing function doesn't allow params to be over-ridden so need a new one
1433 * this one allows you to only pass in the params you want to change
1434 * @param array $params
1437 public function CustomGroupCreateByParams($params = array()) {
1439 'title' => "API Custom Group",
1440 'extends' => 'Contact',
1442 'style' => 'Inline',
1445 $params = array_merge($defaults, $params);
1446 return $this->callAPISuccess('custom_group', 'create', $params);
1450 * Create custom group with multi fields.
1451 * @param array $params
1454 public function CustomGroupMultipleCreateByParams($params = array()) {
1459 $params = array_merge($defaults, $params);
1460 return $this->CustomGroupCreateByParams($params);
1464 * Create custom group with multi fields.
1465 * @param array $params
1468 public function CustomGroupMultipleCreateWithFields($params = array()) {
1469 // also need to pass on $params['custom_field'] if not set but not in place yet
1471 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1472 $ids['custom_group_id'] = $customGroup['id'];
1474 $customField = $this->customFieldCreate(array(
1475 'custom_group_id' => $ids['custom_group_id'],
1476 'label' => 'field_1' . $ids['custom_group_id'],
1480 $ids['custom_field_id'][] = $customField['id'];
1482 $customField = $this->customFieldCreate(array(
1483 'custom_group_id' => $ids['custom_group_id'],
1484 'default_value' => '',
1485 'label' => 'field_2' . $ids['custom_group_id'],
1488 $ids['custom_field_id'][] = $customField['id'];
1490 $customField = $this->customFieldCreate(array(
1491 'custom_group_id' => $ids['custom_group_id'],
1492 'default_value' => '',
1493 'label' => 'field_3' . $ids['custom_group_id'],
1496 $ids['custom_field_id'][] = $customField['id'];
1502 * Create a custom group with a single text custom field. See
1503 * participant:testCreateWithCustom for how to use this
1505 * @param string $function
1507 * @param string $filename
1511 * ids of created objects
1513 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1514 $params = array('title' => $function);
1515 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1516 $params['extends'] = $entity ?
$entity : 'Contact';
1517 $customGroup = $this->CustomGroupCreate($params);
1518 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1519 CRM_Core_PseudoConstant
::flush();
1521 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1525 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1526 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1528 * @param string $function
1530 * @param string $filename
1534 * ids of created objects
1536 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1537 $params = array('title' => $function);
1538 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1539 $params['extends'] = $entity ?
$entity : 'Contact';
1540 $customGroup = $this->CustomGroupCreate($params);
1541 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1542 CRM_Core_PseudoConstant
::flush();
1544 'defaultValue' => 'Default Value',
1545 'lowercasevalue' => 'Lowercase Value',
1546 1 => 'Integer Value',
1549 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1550 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1551 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1552 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1553 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1554 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1555 foreach ($options as $option_value => $option_label) {
1556 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1557 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1560 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id'], 'custom_field_option_group_id' => $custom_field_api_result['values'][0]['option_group_id'], 'custom_field_group_options' => $options);
1564 * Delete custom group.
1566 * @param int $customGroupID
1570 public function customGroupDelete($customGroupID) {
1571 $params['id'] = $customGroupID;
1572 return $this->callAPISuccess('custom_group', 'delete', $params);
1576 * Create custom field.
1578 * @param array $params
1579 * (custom_group_id) is required.
1582 public function customFieldCreate($params) {
1583 $params = array_merge(array(
1584 'label' => 'Custom Field',
1585 'data_type' => 'String',
1586 'html_type' => 'Text',
1587 'is_searchable' => 1,
1589 'default_value' => 'defaultValue',
1592 $result = $this->callAPISuccess('custom_field', 'create', $params);
1593 // these 2 functions are called with force to flush static caches
1594 CRM_Core_BAO_CustomField
::getTableColumnGroup($result['id'], 1);
1595 CRM_Core_Component
::getEnabledComponents(1);
1600 * Delete custom field.
1602 * @param int $customFieldID
1606 public function customFieldDelete($customFieldID) {
1608 $params['id'] = $customFieldID;
1609 return $this->callAPISuccess('custom_field', 'delete', $params);
1618 public function noteCreate($cId) {
1620 'entity_table' => 'civicrm_contact',
1621 'entity_id' => $cId,
1622 'note' => 'hello I am testing Note',
1623 'contact_id' => $cId,
1624 'modified_date' => date('Ymd'),
1625 'subject' => 'Test Note',
1628 return $this->callAPISuccess('Note', 'create', $params);
1632 * Enable CiviCampaign Component.
1634 * @param bool $reloadConfig
1635 * Force relaod config or not
1637 public function enableCiviCampaign($reloadConfig = TRUE) {
1638 CRM_Core_BAO_ConfigSetting
::enableComponent('CiviCampaign');
1639 if ($reloadConfig) {
1640 // force reload of config object
1641 $config = CRM_Core_Config
::singleton(TRUE, TRUE);
1643 //flush cache by calling with reset
1644 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1648 * Create custom field with Option Values.
1650 * @param array $customGroup
1651 * @param string $name
1652 * Name of custom field.
1653 * @param array $extraParams
1654 * Additional parameters to pass through.
1658 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
1659 $fieldParams = array(
1660 'custom_group_id' => $customGroup['id'],
1661 'name' => 'test_custom_group',
1662 'label' => 'Country',
1663 'html_type' => 'Select',
1664 'data_type' => 'String',
1667 'is_searchable' => 0,
1671 $optionGroup = array(
1673 'name' => 'option_group1',
1674 'label' => 'option_group_label1',
1677 $optionValue = array(
1678 'option_label' => array('Label1', 'Label2'),
1679 'option_value' => array('value1', 'value2'),
1680 'option_name' => array($name . '_1', $name . '_2'),
1681 'option_weight' => array(1, 2),
1682 'option_status' => 1,
1685 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1687 return $this->callAPISuccess('custom_field', 'create', $params);
1695 public function confirmEntitiesDeleted($entities) {
1696 foreach ($entities as $entity) {
1698 $result = $this->callAPISuccess($entity, 'Get', array());
1699 if ($result['error'] == 1 ||
$result['count'] > 0) {
1700 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1708 * Quick clean by emptying tables created for the test.
1710 * @param array $tablesToTruncate
1711 * @param bool $dropCustomValueTables
1712 * @throws \Exception
1714 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
1716 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
1718 if ($dropCustomValueTables) {
1719 $optionGroupResult = CRM_Core_DAO
::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
1720 while ($optionGroupResult->fetch()) {
1721 if (!empty($optionGroupResult->option_group_id
)) {
1722 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id
);
1725 $tablesToTruncate[] = 'civicrm_custom_group';
1726 $tablesToTruncate[] = 'civicrm_custom_field';
1729 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate
, $tablesToTruncate));
1731 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1732 foreach ($tablesToTruncate as $table) {
1733 $sql = "TRUNCATE TABLE $table";
1734 CRM_Core_DAO
::executeQuery($sql);
1736 CRM_Core_DAO
::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1738 if ($dropCustomValueTables) {
1739 $dbName = self
::getDBName();
1741 SELECT TABLE_NAME as tableName
1742 FROM INFORMATION_SCHEMA.TABLES
1743 WHERE TABLE_SCHEMA = '{$dbName}'
1744 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
1747 $tableDAO = CRM_Core_DAO
::executeQuery($query);
1748 while ($tableDAO->fetch()) {
1749 $sql = "DROP TABLE {$tableDAO->tableName}";
1750 CRM_Core_DAO
::executeQuery($sql);
1756 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1758 public function quickCleanUpFinancialEntities() {
1759 $tablesToTruncate = array(
1761 'civicrm_activity_contact',
1762 'civicrm_contribution',
1763 'civicrm_contribution_soft',
1764 'civicrm_contribution_product',
1765 'civicrm_financial_trxn',
1766 'civicrm_financial_item',
1767 'civicrm_contribution_recur',
1768 'civicrm_line_item',
1769 'civicrm_contribution_page',
1770 'civicrm_payment_processor',
1771 'civicrm_entity_financial_trxn',
1772 'civicrm_membership',
1773 'civicrm_membership_type',
1774 'civicrm_membership_payment',
1775 'civicrm_membership_log',
1776 'civicrm_membership_block',
1778 'civicrm_participant',
1779 'civicrm_participant_payment',
1781 'civicrm_pledge_payment',
1782 'civicrm_price_set_entity',
1783 'civicrm_price_field_value',
1784 'civicrm_price_field',
1786 $this->quickCleanup($tablesToTruncate);
1787 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
1788 $this->restoreDefaultPriceSetConfig();
1790 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
1791 $this->disableTaxAndInvoicing();
1792 $this->setCurrencySeparators(',');
1793 CRM_Core_PseudoConstant
::flush('taxRates');
1794 System
::singleton()->flushProcessors();
1797 public function restoreDefaultPriceSetConfig() {
1798 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1799 CRM_Core_DAO
::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
1800 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)");
1801 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)");
1805 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
1806 * Default behaviour is to also delete the entity
1807 * @param array $params
1808 * Params array to check against.
1810 * Id of the entity concerned.
1811 * @param string $entity
1812 * Name of entity concerned (e.g. membership).
1813 * @param bool $delete
1814 * Should the entity be deleted as part of this check.
1815 * @param string $errorText
1816 * Text to print on error.
1820 * @param array $params
1823 * @param int $delete
1824 * @param string $errorText
1828 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
1830 $result = $this->callAPISuccessGetSingle($entity, array(
1835 $this->callAPISuccess($entity, 'Delete', array(
1839 $dateFields = $keys = $dateTimeFields = array();
1840 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
1841 foreach ($fields['values'] as $field => $settings) {
1842 if (array_key_exists($field, $result)) {
1843 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = $field;
1846 $keys[CRM_Utils_Array
::Value('name', $settings, $field)] = CRM_Utils_Array
::value('name', $settings, $field);
1848 $type = CRM_Utils_Array
::value('type', $settings);
1849 if ($type == CRM_Utils_Type
::T_DATE
) {
1850 $dateFields[] = $settings['name'];
1851 // we should identify both real names & unique names as dates
1852 if ($field != $settings['name']) {
1853 $dateFields[] = $field;
1856 if ($type == CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
) {
1857 $dateTimeFields[] = $settings['name'];
1858 // we should identify both real names & unique names as dates
1859 if ($field != $settings['name']) {
1860 $dateTimeFields[] = $field;
1865 if (strtolower($entity) == 'contribution') {
1866 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
1867 // this is not returned in id format
1868 unset($params['payment_instrument_id']);
1869 $params['contribution_source'] = $params['source'];
1870 unset($params['source']);
1873 foreach ($params as $key => $value) {
1874 if ($key == 'version' ||
substr($key, 0, 3) == 'api' ||
!array_key_exists($keys[$key], $result)) {
1877 if (in_array($key, $dateFields)) {
1878 $value = date('Y-m-d', strtotime($value));
1879 $result[$key] = date('Y-m-d', strtotime($result[$key]));
1881 if (in_array($key, $dateTimeFields)) {
1882 $value = date('Y-m-d H:i:s', strtotime($value));
1883 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array
::value($keys[$key], $result, CRM_Utils_Array
::value($key, $result))));
1885 $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);
1890 * Get formatted values in the actual and expected result.
1891 * @param array $actual
1892 * Actual calculated values.
1893 * @param array $expected
1896 public function checkArrayEquals(&$actual, &$expected) {
1897 self
::unsetId($actual);
1898 self
::unsetId($expected);
1899 $this->assertEquals($actual, $expected);
1903 * Unset the key 'id' from the array
1904 * @param array $unformattedArray
1905 * The array from which the 'id' has to be unset.
1907 public static function unsetId(&$unformattedArray) {
1908 $formattedArray = array();
1909 if (array_key_exists('id', $unformattedArray)) {
1910 unset($unformattedArray['id']);
1912 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
1913 foreach ($unformattedArray['values'] as $key => $value) {
1914 if (is_array($value)) {
1915 foreach ($value as $k => $v) {
1921 elseif ($key == 'id') {
1922 $unformattedArray[$key];
1924 $formattedArray = array($value);
1926 $unformattedArray['values'] = $formattedArray;
1931 * Helper to enable/disable custom directory support
1933 * @param array $customDirs
1935 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1936 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1938 public function customDirectories($customDirs) {
1939 $config = CRM_Core_Config
::singleton();
1941 if (empty($customDirs['php_path']) ||
$customDirs['php_path'] === FALSE) {
1942 unset($config->customPHPPathDir
);
1944 elseif ($customDirs['php_path'] === TRUE) {
1945 $config->customPHPPathDir
= dirname(dirname(__FILE__
)) . '/custom_directories/php/';
1948 $config->customPHPPathDir
= $php_path;
1951 if (empty($customDirs['template_path']) ||
$customDirs['template_path'] === FALSE) {
1952 unset($config->customTemplateDir
);
1954 elseif ($customDirs['template_path'] === TRUE) {
1955 $config->customTemplateDir
= dirname(dirname(__FILE__
)) . '/custom_directories/templates/';
1958 $config->customTemplateDir
= $template_path;
1963 * Generate a temporary folder.
1965 * @param string $prefix
1968 public function createTempDir($prefix = 'test-') {
1969 $tempDir = CRM_Utils_File
::tempdir($prefix);
1970 $this->tempDirs
[] = $tempDir;
1974 public function cleanTempDirs() {
1975 if (!is_array($this->tempDirs
)) {
1976 // fix test errors where this is not set
1979 foreach ($this->tempDirs
as $tempDir) {
1980 if (is_dir($tempDir)) {
1981 CRM_Utils_File
::cleanDir($tempDir, TRUE, FALSE);
1987 * Temporarily replace the singleton extension with a different one.
1988 * @param \CRM_Extension_System $system
1990 public function setExtensionSystem(CRM_Extension_System
$system) {
1991 if ($this->origExtensionSystem
== NULL) {
1992 $this->origExtensionSystem
= CRM_Extension_System
::singleton();
1994 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
1997 public function unsetExtensionSystem() {
1998 if ($this->origExtensionSystem
!== NULL) {
1999 CRM_Extension_System
::setSingleton($this->origExtensionSystem
);
2000 $this->origExtensionSystem
= NULL;
2005 * Temporarily alter the settings-metadata to add a mock setting.
2007 * WARNING: The setting metadata will disappear on the next cache-clear.
2012 public function setMockSettingsMetaData($extras) {
2013 CRM_Utils_Hook
::singleton()
2014 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2015 $metadata = array_merge($metadata, $extras);
2018 Civi
::service('settings_manager')->flush();
2020 $fields = $this->callAPISuccess('setting', 'getfields', array());
2021 foreach ($extras as $key => $spec) {
2022 $this->assertNotEmpty($spec['title']);
2023 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2028 * @param string $name
2030 public function financialAccountDelete($name) {
2031 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2032 $financialAccount->name
= $name;
2033 if ($financialAccount->find(TRUE)) {
2034 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2035 $entityFinancialType->financial_account_id
= $financialAccount->id
;
2036 $entityFinancialType->delete();
2037 $financialAccount->delete();
2042 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2043 * (NB unclear if this is still required)
2045 public function _sethtmlGlobals() {
2046 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2047 'required' => array(
2048 'html_quickform_rule_required',
2049 'HTML/QuickForm/Rule/Required.php',
2051 'maxlength' => array(
2052 'html_quickform_rule_range',
2053 'HTML/QuickForm/Rule/Range.php',
2055 'minlength' => array(
2056 'html_quickform_rule_range',
2057 'HTML/QuickForm/Rule/Range.php',
2059 'rangelength' => array(
2060 'html_quickform_rule_range',
2061 'HTML/QuickForm/Rule/Range.php',
2064 'html_quickform_rule_email',
2065 'HTML/QuickForm/Rule/Email.php',
2068 'html_quickform_rule_regex',
2069 'HTML/QuickForm/Rule/Regex.php',
2071 'lettersonly' => array(
2072 'html_quickform_rule_regex',
2073 'HTML/QuickForm/Rule/Regex.php',
2075 'alphanumeric' => array(
2076 'html_quickform_rule_regex',
2077 'HTML/QuickForm/Rule/Regex.php',
2080 'html_quickform_rule_regex',
2081 'HTML/QuickForm/Rule/Regex.php',
2083 'nopunctuation' => array(
2084 'html_quickform_rule_regex',
2085 'HTML/QuickForm/Rule/Regex.php',
2088 'html_quickform_rule_regex',
2089 'HTML/QuickForm/Rule/Regex.php',
2091 'callback' => array(
2092 'html_quickform_rule_callback',
2093 'HTML/QuickForm/Rule/Callback.php',
2096 'html_quickform_rule_compare',
2097 'HTML/QuickForm/Rule/Compare.php',
2100 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2101 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2103 'HTML/QuickForm/group.php',
2104 'HTML_QuickForm_group',
2107 'HTML/QuickForm/hidden.php',
2108 'HTML_QuickForm_hidden',
2111 'HTML/QuickForm/reset.php',
2112 'HTML_QuickForm_reset',
2114 'checkbox' => array(
2115 'HTML/QuickForm/checkbox.php',
2116 'HTML_QuickForm_checkbox',
2119 'HTML/QuickForm/file.php',
2120 'HTML_QuickForm_file',
2123 'HTML/QuickForm/image.php',
2124 'HTML_QuickForm_image',
2126 'password' => array(
2127 'HTML/QuickForm/password.php',
2128 'HTML_QuickForm_password',
2131 'HTML/QuickForm/radio.php',
2132 'HTML_QuickForm_radio',
2135 'HTML/QuickForm/button.php',
2136 'HTML_QuickForm_button',
2139 'HTML/QuickForm/submit.php',
2140 'HTML_QuickForm_submit',
2143 'HTML/QuickForm/select.php',
2144 'HTML_QuickForm_select',
2146 'hiddenselect' => array(
2147 'HTML/QuickForm/hiddenselect.php',
2148 'HTML_QuickForm_hiddenselect',
2151 'HTML/QuickForm/text.php',
2152 'HTML_QuickForm_text',
2154 'textarea' => array(
2155 'HTML/QuickForm/textarea.php',
2156 'HTML_QuickForm_textarea',
2158 'fckeditor' => array(
2159 'HTML/QuickForm/fckeditor.php',
2160 'HTML_QuickForm_FCKEditor',
2163 'HTML/QuickForm/tinymce.php',
2164 'HTML_QuickForm_TinyMCE',
2166 'dojoeditor' => array(
2167 'HTML/QuickForm/dojoeditor.php',
2168 'HTML_QuickForm_dojoeditor',
2171 'HTML/QuickForm/link.php',
2172 'HTML_QuickForm_link',
2174 'advcheckbox' => array(
2175 'HTML/QuickForm/advcheckbox.php',
2176 'HTML_QuickForm_advcheckbox',
2179 'HTML/QuickForm/date.php',
2180 'HTML_QuickForm_date',
2183 'HTML/QuickForm/static.php',
2184 'HTML_QuickForm_static',
2187 'HTML/QuickForm/header.php',
2188 'HTML_QuickForm_header',
2191 'HTML/QuickForm/html.php',
2192 'HTML_QuickForm_html',
2194 'hierselect' => array(
2195 'HTML/QuickForm/hierselect.php',
2196 'HTML_QuickForm_hierselect',
2198 'autocomplete' => array(
2199 'HTML/QuickForm/autocomplete.php',
2200 'HTML_QuickForm_autocomplete',
2203 'HTML/QuickForm/xbutton.php',
2204 'HTML_QuickForm_xbutton',
2206 'advmultiselect' => array(
2207 'HTML/QuickForm/advmultiselect.php',
2208 'HTML_QuickForm_advmultiselect',
2214 * Set up an acl allowing contact to see 2 specified groups
2215 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2217 * You need to have pre-created these groups & created the user e.g
2218 * $this->createLoggedInUser();
2219 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2220 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2222 * @param bool $isProfile
2224 public function setupACL($isProfile = FALSE) {
2226 $_REQUEST = $this->_params
;
2228 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= array('access CiviCRM');
2229 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2230 $ov = new CRM_Core_DAO_OptionValue();
2231 $ov->option_group_id
= $optionGroupID;
2233 if ($ov->find(TRUE)) {
2234 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2236 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2237 'option_group_id' => $optionGroupID,
2238 'label' => 'pick me',
2242 CRM_Core_DAO
::executeQuery("
2243 TRUNCATE civicrm_acl_cache
2246 CRM_Core_DAO
::executeQuery("
2247 TRUNCATE civicrm_acl_contact_cache
2250 CRM_Core_DAO
::executeQuery("
2251 INSERT INTO civicrm_acl_entity_role (
2252 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2253 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2257 CRM_Core_DAO
::executeQuery("
2258 INSERT INTO civicrm_acl (
2259 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2262 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2267 CRM_Core_DAO
::executeQuery("
2268 INSERT INTO civicrm_acl (
2269 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2272 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2276 CRM_Core_DAO
::executeQuery("
2277 INSERT INTO civicrm_acl (
2278 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2281 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2286 $this->_loggedInUser
= CRM_Core_Session
::singleton()->get('userID');
2287 $this->callAPISuccess('group_contact', 'create', array(
2288 'group_id' => $this->_permissionedGroup
,
2289 'contact_id' => $this->_loggedInUser
,
2294 CRM_ACL_BAO_Cache
::resetCache();
2295 CRM_ACL_API
::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2300 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2302 public function offsetDefaultPriceSet() {
2303 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2304 $firstID = $contributionPriceSet['id'];
2305 $this->callAPISuccess('price_set', 'create', array(
2306 'id' => $contributionPriceSet['id'],
2310 unset($contributionPriceSet['id']);
2311 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2312 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2313 'price_set_id' => $firstID,
2314 'options' => array('limit' => 1),
2316 unset($priceField['id']);
2317 $priceField['price_set_id'] = $newPriceSet['id'];
2318 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2319 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2320 'price_set_id' => $firstID,
2322 'options' => array('limit' => 1),
2325 unset($priceFieldValue['id']);
2326 //create some padding to use up ids
2327 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2328 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2329 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2333 * Create an instance of the paypal processor.
2334 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2335 * this parent class & we don't have a structure for that yet
2336 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2337 * & the best protection against that is the functions this class affords
2338 * @param array $params
2339 * @return int $result['id'] payment processor id
2341 public function paymentProcessorCreate($params = array()) {
2342 $params = array_merge(array(
2344 'domain_id' => CRM_Core_Config
::domainID(),
2345 'payment_processor_type_id' => 'PayPal',
2349 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2350 'password' => '1183377788',
2351 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2352 'url_site' => 'https://www.sandbox.paypal.com/',
2353 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2354 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2355 'class_name' => 'Payment_PayPalImpl',
2356 'billing_mode' => 3,
2357 'financial_type_id' => 1,
2358 'financial_account_id' => 12,
2359 // Credit card = 1 so can pass 'by accident'.
2360 'payment_instrument_id' => 'Debit Card',
2362 if (!is_numeric($params['payment_processor_type_id'])) {
2363 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2365 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2366 'name' => $params['payment_processor_type_id'],
2370 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2371 return $result['id'];
2375 * Set up initial recurring payment allowing subsequent IPN payments.
2377 * @param array $recurParams (Optional)
2378 * @param array $contributionParams (Optional)
2380 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2381 $contributionParams = array_merge([
2382 'total_amount' => '200',
2383 'invoice_id' => $this->_invoiceID
,
2384 'financial_type_id' => 'Donation',
2385 'contribution_status_id' => 'Pending',
2386 'contact_id' => $this->_contactID
,
2387 'contribution_page_id' => $this->_contributionPageID
,
2388 'payment_processor_id' => $this->_paymentProcessorID
,
2390 'skipCleanMoney' => TRUE,
2391 ], $contributionParams);
2392 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2393 'contact_id' => $this->_contactID
,
2396 'installments' => 5,
2397 'frequency_unit' => 'Month',
2398 'frequency_interval' => 1,
2399 'invoice_id' => $this->_invoiceID
,
2400 'contribution_status_id' => 2,
2401 'payment_processor_id' => $this->_paymentProcessorID
,
2402 // processor provided ID - use contact ID as proxy.
2403 'processor_id' => $this->_contactID
,
2404 'api.contribution.create' => $contributionParams,
2406 $this->_contributionRecurID
= $contributionRecur['id'];
2407 $this->_contributionID
= $contributionRecur['values']['0']['api.contribution.create']['id'];
2411 * 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
2413 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2415 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2416 $membershipParams = $recurParams = array();
2417 if (!empty($params['duration_unit'])) {
2418 $membershipParams['duration_unit'] = $params['duration_unit'];
2420 if (!empty($params['frequency_unit'])) {
2421 $recurParams['frequency_unit'] = $params['frequency_unit'];
2424 $this->ids
['membership_type'] = $this->membershipTypeCreate($membershipParams);
2425 //create a contribution so our membership & contribution don't both have id = 1
2426 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2427 $this->contributionCreate(array(
2428 'contact_id' => $this->_contactID
,
2430 'financial_type_id' => 1,
2431 'invoice_id' => 'abcd',
2435 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2437 $this->ids
['membership'] = $this->callAPISuccess('membership', 'create', array(
2438 'contact_id' => $this->_contactID
,
2439 'membership_type_id' => $this->ids
['membership_type'],
2440 'contribution_recur_id' => $this->_contributionRecurID
,
2441 'format.only_id' => TRUE,
2443 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2444 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_line_item");
2446 $this->callAPISuccess('line_item', 'create', array(
2447 'entity_table' => 'civicrm_membership',
2448 'entity_id' => $this->ids
['membership'],
2449 'contribution_id' => $this->_contributionID
,
2450 'label' => 'General',
2452 'unit_price' => 200,
2453 'line_total' => 200,
2454 'financial_type_id' => 1,
2455 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2457 'label' => 'Membership Amount',
2458 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2460 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2462 'label' => 'General',
2463 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2466 $this->callAPISuccess('membership_payment', 'create', array(
2467 'contribution_id' => $this->_contributionID
,
2468 'membership_id' => $this->ids
['membership'],
2477 public function CiviUnitTestCase_fatalErrorHandler($message) {
2478 throw new Exception("{$message['message']}: {$message['code']}");
2482 * Wrap the entire test case in a transaction.
2484 * Only subsequent DB statements will be wrapped in TX -- this cannot
2485 * retroactively wrap old DB statements. Therefore, it makes sense to
2486 * call this at the beginning of setUp().
2488 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2489 * this option does not work with, e.g., custom-data.
2491 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2492 * if TRUNCATE or ALTER is called while using a transaction.
2495 * Whether to use nesting or reference-counting.
2497 public function useTransaction($nest = TRUE) {
2499 $this->tx
= new CRM_Core_Transaction($nest);
2500 $this->tx
->rollback();
2505 * Assert the attachment exists.
2507 * @param bool $exists
2508 * @param array $apiResult
2510 protected function assertAttachmentExistence($exists, $apiResult) {
2511 $fileId = $apiResult['id'];
2512 $this->assertTrue(is_numeric($fileId));
2513 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2514 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2515 1 => array($fileId, 'Int'),
2517 $this->assertDBQuery($exists ?
1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2518 1 => array($fileId, 'Int'),
2523 * Assert 2 sql strings are the same, ignoring double spaces.
2525 * @param string $expectedSQL
2526 * @param string $actualSQL
2527 * @param string $message
2529 protected function assertLike($expectedSQL, $actualSQL, $message = 'different sql') {
2530 $expected = trim((preg_replace('/[ \r\n\t]+/', ' ', $expectedSQL)));
2531 $actual = trim((preg_replace('/[ \r\n\t]+/', ' ', $actualSQL)));
2532 $this->assertEquals($expected, $actual, $message);
2536 * Create a price set for an event.
2538 * @param int $feeTotal
2539 * @param int $minAmt
2540 * @param string $type
2545 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2546 // creating price set, price field
2547 $paramsSet['title'] = 'Price Set';
2548 $paramsSet['name'] = CRM_Utils_String
::titleToVar('Price Set');
2549 $paramsSet['is_active'] = FALSE;
2550 $paramsSet['extends'] = 1;
2551 $paramsSet['min_amount'] = $minAmt;
2553 $priceSet = CRM_Price_BAO_PriceSet
::create($paramsSet);
2554 $this->_ids
['price_set'] = $priceSet->id
;
2556 $paramsField = array(
2557 'label' => 'Price Field',
2558 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2559 'html_type' => $type,
2560 'price' => $feeTotal,
2561 'option_label' => array('1' => 'Price Field'),
2562 'option_value' => array('1' => $feeTotal),
2563 'option_name' => array('1' => $feeTotal),
2564 'option_weight' => array('1' => 1),
2565 'option_amount' => array('1' => 1),
2566 'is_display_amounts' => 1,
2568 'options_per_line' => 1,
2569 'is_active' => array('1' => 1),
2570 'price_set_id' => $this->_ids
['price_set'],
2571 'is_enter_qty' => 1,
2572 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2574 if ($type === 'Radio') {
2575 $paramsField['is_enter_qty'] = 0;
2576 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2577 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2579 CRM_Price_BAO_PriceField
::create($paramsField);
2580 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids
['price_set']));
2581 $this->_ids
['price_field'] = array_keys($fields['values']);
2582 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids
['price_field'][0]));
2583 $this->_ids
['price_field_value'] = array_keys($fieldValues['values']);
2585 return $this->_ids
['price_set'];
2589 * Add a profile to a contribution page.
2591 * @param string $name
2592 * @param int $contributionPageID
2593 * @param string $module
2595 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2597 'uf_group_id' => $name,
2598 'module' => $module,
2599 'entity_table' => 'civicrm_contribution_page',
2600 'entity_id' => $contributionPageID,
2603 if ($module !== 'CiviContribute') {
2604 $params['module_data'] = [$module => []];
2606 $this->callAPISuccess('UFJoin', 'create', $params);
2610 * Add participant with contribution
2614 protected function createParticipantWithContribution() {
2615 // creating price set, price field
2616 $this->_contactId
= $this->individualCreate();
2617 $event = $this->eventCreate();
2618 $this->_eventId
= $event['id'];
2619 $eventParams = array(
2620 'id' => $this->_eventId
,
2621 'financial_type_id' => 4,
2624 $this->callAPISuccess('event', 'create', $eventParams);
2625 $priceFields = $this->createPriceSet('event', $this->_eventId
);
2626 $participantParams = array(
2627 'financial_type_id' => 4,
2628 'event_id' => $this->_eventId
,
2631 'fee_currency' => 'USD',
2632 'contact_id' => $this->_contactId
,
2634 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
2635 $contributionParams = array(
2636 'total_amount' => 150,
2637 'currency' => 'USD',
2638 'contact_id' => $this->_contactId
,
2639 'financial_type_id' => 4,
2640 'contribution_status_id' => 1,
2641 'partial_payment_total' => 300.00,
2642 'partial_amount_to_pay' => 150,
2643 'contribution_mode' => 'participant',
2644 'participant_id' => $participant['id'],
2646 foreach ($priceFields['values'] as $key => $priceField) {
2647 $lineItems[1][$key] = array(
2648 'price_field_id' => $priceField['price_field_id'],
2649 'price_field_value_id' => $priceField['id'],
2650 'label' => $priceField['label'],
2651 'field_title' => $priceField['label'],
2653 'unit_price' => $priceField['amount'],
2654 'line_total' => $priceField['amount'],
2655 'financial_type_id' => $priceField['financial_type_id'],
2658 $contributionParams['line_item'] = $lineItems;
2659 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
2660 $paymentParticipant = array(
2661 'participant_id' => $participant['id'],
2662 'contribution_id' => $contribution['id'],
2664 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
2665 return array($lineItems, $contribution);
2671 * @param string $component
2672 * @param int $componentId
2673 * @param array $priceFieldOptions
2677 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
2678 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2679 $paramsSet['name'] = CRM_Utils_String
::titleToVar($paramsSet['title']);
2680 $paramsSet['is_active'] = TRUE;
2681 $paramsSet['financial_type_id'] = 'Event Fee';
2682 $paramsSet['extends'] = 1;
2683 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2684 $priceSetId = $priceSet['id'];
2685 //Checking for priceset added in the table.
2686 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
2687 'id', $paramsSet['title'], 'Check DB for created priceset'
2689 $paramsField = array_merge(array(
2690 'label' => 'Price Field',
2691 'name' => CRM_Utils_String
::titleToVar('Price Field'),
2692 'html_type' => 'CheckBox',
2693 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2694 'option_value' => array('1' => 100, '2' => 200),
2695 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2696 'option_weight' => array('1' => 1, '2' => 2),
2697 'option_amount' => array('1' => 100, '2' => 200),
2698 'is_display_amounts' => 1,
2700 'options_per_line' => 1,
2701 'is_active' => array('1' => 1, '2' => 1),
2702 'price_set_id' => $priceSet['id'],
2703 'is_enter_qty' => 1,
2704 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2705 ), $priceFieldOptions);
2707 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
2709 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $component, $componentId, $priceSetId);
2711 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id
));
2715 * Replace the template with a test-oriented template designed to show all the variables.
2717 * @param string $templateName
2719 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
2720 $testTemplate = file_get_contents(__DIR__
. '/../../templates/message_templates/' . $templateName . '_html.tpl');
2721 CRM_Core_DAO
::executeQuery(
2722 "UPDATE civicrm_option_group og
2723 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2724 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2725 SET m.msg_html = '{$testTemplate}'
2726 WHERE og.name = 'msg_tpl_workflow_contribution'
2727 AND ov.name = '{$templateName}'
2728 AND m.is_default = 1"
2733 * Reinstate the default template.
2735 * @param string $templateName
2737 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
2738 CRM_Core_DAO
::executeQuery(
2739 "UPDATE civicrm_option_group og
2740 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2741 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2742 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2743 SET m.msg_html = m2.msg_html
2744 WHERE og.name = 'msg_tpl_workflow_contribution'
2745 AND ov.name = '{$templateName}'
2746 AND m.is_default = 1"
2751 * Flush statics relating to financial type.
2753 protected function flushFinancialTypeStatics() {
2754 if (isset(\Civi
::$statics['CRM_Financial_BAO_FinancialType'])) {
2755 unset(\Civi
::$statics['CRM_Financial_BAO_FinancialType']);
2757 if (isset(\Civi
::$statics['CRM_Contribute_PseudoConstant'])) {
2758 unset(\Civi
::$statics['CRM_Contribute_PseudoConstant']);
2760 CRM_Contribute_PseudoConstant
::flush('financialType');
2761 CRM_Contribute_PseudoConstant
::flush('membershipType');
2762 // Pseudoconstants may be saved to the cache table.
2763 CRM_Core_DAO
::executeQuery("TRUNCATE civicrm_cache");
2764 CRM_Financial_BAO_FinancialType
::$_statusACLFt = array();
2765 CRM_Financial_BAO_FinancialType
::$_availableFinancialTypes = NULL;
2769 * Set the permissions to the supplied array.
2771 * @param array $permissions
2773 protected function setPermissions($permissions) {
2774 CRM_Core_Config
::singleton()->userPermissionClass
->permissions
= $permissions;
2775 $this->flushFinancialTypeStatics();
2779 * @param array $params
2782 public function _checkFinancialRecords($params, $context) {
2783 $entityParams = array(
2784 'entity_id' => $params['id'],
2785 'entity_table' => 'civicrm_contribution',
2787 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
2788 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2789 if ($context == 'pending') {
2790 $trxn = CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams);
2791 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2794 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2795 $trxnParams = array(
2796 'id' => $trxn['financial_trxn_id'],
2798 if ($context != 'online' && $context != 'payLater') {
2799 $compareParams = array(
2800 'to_financial_account_id' => 6,
2801 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2805 if ($context == 'feeAmount') {
2806 $compareParams['fee_amount'] = 50;
2808 elseif ($context == 'online') {
2809 $compareParams = array(
2810 'to_financial_account_id' => 12,
2811 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2813 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, 1),
2816 elseif ($context == 'payLater') {
2817 $compareParams = array(
2818 'to_financial_account_id' => 7,
2819 'total_amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2823 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2824 $entityParams = array(
2825 'financial_trxn_id' => $trxn['financial_trxn_id'],
2826 'entity_table' => 'civicrm_financial_item',
2828 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
2829 $fitemParams = array(
2830 'id' => $entityTrxn['entity_id'],
2832 $compareParams = array(
2833 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2835 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2837 if ($context == 'payLater') {
2838 $compareParams = array(
2839 'amount' => CRM_Utils_Array
::value('total_amount', $params, 100),
2841 'financial_account_id' => CRM_Utils_Array
::value('financial_account_id', $params, 1),
2844 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2845 if ($context == 'feeAmount') {
2847 'entity_id' => $params['id'],
2848 'entity_table' => 'civicrm_contribution',
2850 $maxTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($maxParams, TRUE));
2851 $trxnParams = array(
2852 'id' => $maxTrxn['financial_trxn_id'],
2854 $compareParams = array(
2855 'to_financial_account_id' => 5,
2856 'from_financial_account_id' => 6,
2857 'total_amount' => 50,
2860 $trxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['id'], 'DESC');
2861 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2862 $fitemParams = array(
2863 'entity_id' => $trxnId['financialTrxnId'],
2864 'entity_table' => 'civicrm_financial_trxn',
2866 $compareParams = array(
2869 'financial_account_id' => 5,
2871 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2873 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2874 // line should be copied into all the functions that call this function & evaluated there
2875 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2876 // when calling completeTransaction or repeatTransaction.
2877 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
2881 * Return financial type id on basis of name
2883 * @param string $name Financial type m/c name
2887 public function getFinancialTypeId($name) {
2888 return CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2892 * Cleanup function for contents of $this->ids.
2894 * This is a best effort cleanup to use in tear downs etc.
2896 * It will not fail if the data has already been removed (some tests may do
2897 * their own cleanup).
2899 protected function cleanUpSetUpIDs() {
2900 foreach ($this->setupIDs
as $entity => $id) {
2902 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
2904 catch (CiviCRM_API3_Exception
$e) {
2905 // This is a best-effort cleanup function, ignore.
2911 * Create Financial Type.
2913 * @param array $params
2917 protected function createFinancialType($params = array()) {
2918 $params = array_merge($params,
2920 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2924 return $this->callAPISuccess('FinancialType', 'create', $params);
2928 * Create Payment Instrument.
2930 * @param array $params
2931 * @param string $financialAccountName
2935 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
2936 $params = array_merge(array(
2937 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2938 'option_group_id' => 'payment_instrument',
2941 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
2943 $relationTypeID = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2945 $financialAccountParams = [
2946 'entity_table' => 'civicrm_option_value',
2947 'entity_id' => $newPaymentInstrument,
2948 'account_relationship' => $relationTypeID,
2949 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2951 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2953 return CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2957 * Enable Tax and Invoicing
2959 protected function enableTaxAndInvoicing($params = array()) {
2960 // Enable component contribute setting
2961 $contributeSetting = array_merge($params,
2964 'invoice_prefix' => 'INV_',
2965 'credit_notes_prefix' => 'CN_',
2967 'due_date_period' => 'days',
2969 'is_email_pdf' => 1,
2970 'tax_term' => 'Sales Tax',
2971 'tax_display_settings' => 'Inclusive',
2974 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2978 * Enable Tax and Invoicing
2980 protected function disableTaxAndInvoicing($params = array()) {
2981 if (!empty(\Civi
::$statics['CRM_Core_PseudoConstant']) && isset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
2982 unset(\Civi
::$statics['CRM_Core_PseudoConstant']['taxRates']);
2984 // Enable component contribute setting
2985 $contributeSetting = array_merge($params,
2990 return Civi
::settings()->set('contribution_invoice_settings', $contributeSetting);
2994 * Add Sales Tax relation for financial type with financial account.
2996 * @param int $financialTypeId
3000 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3002 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3003 'financial_account_type_id' => key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3004 'is_deductible' => 1,
3009 $account = CRM_Financial_BAO_FinancialAccount
::add($params);
3010 $entityParams = array(
3011 'entity_table' => 'civicrm_financial_type',
3012 'entity_id' => $financialTypeId,
3013 'account_relationship' => key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3016 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3017 \Civi
::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3019 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3020 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3021 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3022 $dao->copyValues($entityParams);
3024 if ($dao->fetch()) {
3025 $entityParams['id'] = $dao->id
;
3027 $entityParams['financial_account_id'] = $account->id
;
3029 return CRM_Financial_BAO_FinancialTypeAccount
::add($entityParams);
3033 * Create price set with contribution test for test setup.
3035 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3036 * on parent class at some point (fn is not in 4.4).
3039 * @param array $params
3041 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3042 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3043 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3044 'title' => "Test Contribution Page",
3045 'financial_type_id' => 1,
3046 'currency' => 'NZD',
3047 'goal_amount' => 50,
3048 'is_pay_later' => 1,
3049 'is_monetary' => TRUE,
3050 'is_email_receipt' => FALSE,
3052 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3053 'is_quick_config' => 0,
3054 'extends' => 'CiviMember',
3055 'financial_type_id' => 1,
3056 'title' => 'my Page',
3058 $priceSetID = $priceSet['id'];
3060 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3061 $priceField = $this->callAPISuccess('price_field', 'create', array(
3062 'price_set_id' => $priceSetID,
3063 'label' => 'Goat Breed',
3064 'html_type' => 'Radio',
3066 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3067 'price_set_id' => $priceSetID,
3068 'price_field_id' => $priceField['id'],
3069 'label' => 'Long Haired Goat',
3071 'financial_type_id' => 'Donation',
3072 'membership_type_id' => $membershipTypeID,
3073 'membership_num_terms' => 1,
3075 $this->_ids
['price_field_value'] = array($priceFieldValue['id']);
3076 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3077 'price_set_id' => $priceSetID,
3078 'price_field_id' => $priceField['id'],
3079 'label' => 'Shoe-eating Goat',
3081 'financial_type_id' => 'Donation',
3082 'membership_type_id' => $membershipTypeID,
3083 'membership_num_terms' => 2,
3085 $this->_ids
['price_field_value'][] = $priceFieldValue['id'];
3087 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3088 'price_set_id' => $priceSetID,
3089 'price_field_id' => $priceField['id'],
3090 'label' => 'Shoe-eating Goat',
3092 'financial_type_id' => 'Donation',
3094 $this->_ids
['price_field_value']['cont'] = $priceFieldValue['id'];
3096 $this->_ids
['price_set'] = $priceSetID;
3097 $this->_ids
['contribution_page'] = $contributionPageResult['id'];
3098 $this->_ids
['price_field'] = array($priceField['id']);
3100 $this->_ids
['membership_type'] = $membershipTypeID;
3104 * Only specified contact returned.
3105 * @implements CRM_Utils_Hook::aclWhereClause
3108 * @param $whereTables
3112 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3113 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts
) . ")";
3117 * @implements CRM_Utils_Hook::selectWhereClause
3119 * @param string $entity
3120 * @param array $clauses
3122 public function selectWhereClauseHook($entity, &$clauses) {
3123 if ($entity == 'Event') {
3124 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3129 * An implementation of hook_civicrm_post used with all our test cases.
3132 * @param string $objectName
3133 * @param int $objectId
3136 public function onPost($op, $objectName, $objectId, &$objectRef) {
3137 if ($op == 'create' && $objectName == 'Individual') {
3138 CRM_Core_DAO
::executeQuery(
3139 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3141 1 => array($objectId, 'Integer'),
3146 if ($op == 'edit' && $objectName == 'Participant') {
3148 1 => array($objectId, 'Integer'),
3150 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3151 CRM_Core_DAO
::executeQuery($query, $params);
3156 * Instantiate form object.
3158 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3160 * @param string $class
3161 * Name of form class.
3163 * @return \CRM_Core_Form
3165 public function getFormObject($class) {
3166 $form = new $class();
3167 $_SERVER['REQUEST_METHOD'] = 'GET';
3168 $form->controller
= new CRM_Core_Controller();
3173 * Get possible thousand separators.
3177 public function getThousandSeparators() {
3178 return array(array('.'), array(','));
3182 * Set the separators for thousands and decimal points.
3184 * @param string $thousandSeparator
3186 protected function setCurrencySeparators($thousandSeparator) {
3187 Civi
::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3189 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ?
'.' : ','));
3193 * Format money as it would be input.
3195 * @param string $amount
3199 protected function formatMoneyInput($amount) {
3200 return CRM_Utils_Money
::format($amount, NULL, '%a');
3204 * Get the contribution object.
3206 * @param int $contributionID
3208 * @return \CRM_Contribute_BAO_Contribution
3210 protected function getContributionObject($contributionID) {
3211 $contributionObj = new CRM_Contribute_BAO_Contribution();
3212 $contributionObj->id
= $contributionID;
3213 $contributionObj->find(TRUE);
3214 return $contributionObj;
3218 * Enable multilingual.
3220 public function enableMultilingual() {
3221 $this->callAPISuccess('Setting', 'create', array(
3222 'lcMessages' => 'en_US',
3223 'languageLimit' => array(
3228 CRM_Core_I18n_Schema
::makeMultilingual('en_US');
3231 $dbLocale = '_en_US';
3235 * Setup or clean up SMS tests
3236 * @param bool $teardown
3238 * @throws \CiviCRM_API3_Exception
3240 public function setupForSmsTests($teardown = FALSE) {
3241 require_once 'CiviTest/CiviTestSMSProvider.php';
3243 // Option value params for CiviTestSMSProvider
3244 $groupID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'sms_provider_name', 'id', 'name');
3246 'option_group_id' => $groupID,
3247 'label' => 'unittestSMS',
3248 'value' => 'unit.test.sms',
3249 'name' => 'CiviTestSMSProvider',
3256 // Test completed, delete provider
3257 $providerOptionValueResult = civicrm_api3('option_value', 'get', $params);
3258 civicrm_api3('option_value', 'delete', array('id' => $providerOptionValueResult['id']));
3262 // Create an SMS provider "CiviTestSMSProvider". Civi handles "CiviTestSMSProvider" as a special case and allows it to be instantiated
3263 // in CRM/Sms/Provider.php even though it is not an extension.
3264 return civicrm_api3('option_value', 'create', $params);