Merge pull request #15619 from seamuslee001/fix_force_case_form_date
[civicrm-core.git] / tests / phpunit / CiviTest / CiviUnitTestCase.php
CommitLineData
6a488035
TO
1<?php
2/**
3 * File for the CiviUnitTestCase class
4 *
5 * (PHP 5)
6 *
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
10 * @package CiviCRM
11 *
12 * This file is part of CiviCRM
13 *
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.
18 *
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.
23 *
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/>.
27 */
28
1fee3ad2 29use Civi\Payment\System;
68989e71 30use League\Csv\Reader;
1fee3ad2 31
6a488035
TO
32/**
33 * Include class definitions
34 */
6a488035 35require_once 'api/api.php';
6a488035
TO
36define('API_LATEST_VERSION', 3);
37
38/**
39 * Base class for CiviCRM unit tests
40 *
d67f1f28
TO
41 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
42 * may opt for one or neither:
43 *
44 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
45 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
46 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
47 * 2. useTransaction() executes the test inside a transaction. It's easier to use
48 * (because you don't need to identify specific tables), but it doesn't work for tests
49 * which manipulate schema or truncate data -- and could behave inconsistently
50 * for tests which specifically examine DB transactions.
51 *
6a488035
TO
52 * Common functions for unit tests
53 * @package CiviCRM
54 */
1ee79258 55class CiviUnitTestCase extends PHPUnit\Framework\TestCase {
6a488035 56
195557d5 57 use \Civi\Test\Api3DocTrait;
1426d341 58 use \Civi\Test\GenericAssertionsTrait;
8c68b9c9 59 use \Civi\Test\DbTestTrait;
a23e13eb 60 use \Civi\Test\ContactTestTrait;
71f1227b 61 use \Civi\Test\MailingTestTrait;
30f5345c 62
6a488035 63 /**
eceb18cc 64 * Database has been initialized.
6a488035 65 *
d51c6add 66 * @var bool
6a488035
TO
67 */
68 private static $dbInit = FALSE;
69
70 /**
eceb18cc 71 * Database connection.
6a488035
TO
72 *
73 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
74 */
75 protected $_dbconn;
76
77 /**
eceb18cc 78 * The database name.
6a488035
TO
79 *
80 * @var string
81 */
82 static protected $_dbName;
83
0b6f58fa 84 /**
eceb18cc 85 * Track tables we have modified during a test.
39b959db 86 * @var array
0b6f58fa
ARW
87 */
88 protected $_tablesToTruncate = array();
89
6a488035
TO
90 /**
91 * @var array of temporary directory names
92 */
93 protected $tempDirs;
94
6a488035 95 /**
d51c6add 96 * @var bool populateOnce allows to skip db resets in setUp
6a488035
TO
97 *
98 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
99 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
100 * "CHECK RUNS" ONLY!
101 *
102 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
103 *
104 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
105 */
106 public static $populateOnce = FALSE;
107
6a488035 108 /**
d51c6add 109 * @var bool DBResetRequired allows skipping DB reset
6a488035
TO
110 * in specific test case. If you still need
111 * to reset single test (method) of such case, call
112 * $this->cleanDB() in the first line of this
113 * test (method).
114 */
115 public $DBResetRequired = TRUE;
116
d67f1f28
TO
117 /**
118 * @var CRM_Core_Transaction|NULL
119 */
120 private $tx = NULL;
121
f9a5aadd 122 /**
123 * Array of IDs created to support the test.
124 *
125 * e.g
126 * $this->ids = ['Contact' => ['descriptive_key' => $contactID], 'Group' => [$groupID]];
127 *
128 * @var array
129 */
130 protected $ids = [];
131
6c466b51 132 /**
2af6f0c0 133 * Class used for hooks during tests.
134 *
135 * This can be used to test hooks within tests. For example in the ACL_PermissionTrait:
136 *
6c466b51 137 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
2af6f0c0 138 *
139 * @var CRM_Utils_Hook_UnitTests hookClass
6c466b51
EM
140 */
141 public $hookClass = NULL;
142
143 /**
144 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
145 */
146 protected $_params = array();
147
148 /**
149 * @var CRM_Extension_System
150 */
151 protected $origExtensionSystem;
152
204beda3 153 /**
154 * Array of IDs created during test setup routine.
155 *
156 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
157 *
158 * @var array
159 */
160 public $setupIDs = array();
161
dcadbba4 162 /**
8d475ce9 163 * PHPUnit Mock Method to use.
dcadbba4
SL
164 *
165 * @var string
166 */
167 public $mockMethod = 'getMock';
168
6a488035 169 /**
eceb18cc 170 * Constructor.
6a488035
TO
171 *
172 * Because we are overriding the parent class constructor, we
173 * need to show the same arguments as exist in the constructor of
174 * PHPUnit_Framework_TestCase, since
175 * PHPUnit_Framework_TestSuite::createTest() creates a
176 * ReflectionClass of the Test class and checks the constructor
177 * of that class to decide how to set up the test.
178 *
e16033b4
TO
179 * @param string $name
180 * @param array $data
181 * @param string $dataName
6a488035 182 */
420384a0 183 public function __construct($name = NULL, array $data = array(), $dataName = '') {
6a488035
TO
184 parent::__construct($name, $data, $dataName);
185
186 // we need full error reporting
187 error_reporting(E_ALL & ~E_NOTICE);
188
f3e16511 189 self::$_dbName = self::getDBName();
6a488035 190
6a488035
TO
191 // also load the class loader
192 require_once 'CRM/Core/ClassLoader.php';
193 CRM_Core_ClassLoader::singleton()->register();
a130e045
DG
194 if (function_exists('_civix_phpunit_setUp')) {
195 // FIXME: loosen coupling
6a488035
TO
196 _civix_phpunit_setUp();
197 }
a6439b6a
SL
198 if (class_exists('PHPUnit_Runner_Version') && version_compare(\PHPUnit_Runner_Version::id(), '5', '>=')) {
199 $this->mockMethod = 'createMock';
200 }
201 elseif (class_exists('PHPUnit\Runner\Version') && version_compare(PHPUnit\Runner\Version::id(), '6', '>=')) {
dcadbba4
SL
202 $this->mockMethod = 'createMock';
203 }
6a488035
TO
204 }
205
f0be539a
EM
206 /**
207 * Override to run the test and assert its state.
208 * @return mixed
209 * @throws \Exception
210 * @throws \PHPUnit_Framework_IncompleteTest
211 * @throws \PHPUnit_Framework_SkippedTest
212 */
2e90bf37
TO
213 protected function runTest() {
214 try {
215 return parent::runTest();
5896d037
TO
216 }
217 catch (PEAR_Exception $e) {
2e90bf37
TO
218 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
219 throw new Exception(\CRM_Core_Error::formatTextException($e), $e->getCode());
220 }
221 }
222
4cbe18b8
EM
223 /**
224 * @return bool
225 */
00be9182 226 public function requireDBReset() {
6a488035
TO
227 return $this->DBResetRequired;
228 }
229
4cbe18b8
EM
230 /**
231 * @return string
232 */
00be9182 233 public static function getDBName() {
f3e16511 234 static $dbName = NULL;
649d6dd0 235 if ($dbName === NULL) {
f3e16511
TO
236 require_once "DB.php";
237 $dsninfo = DB::parseDSN(CIVICRM_DSN);
238 $dbName = $dsninfo['database'];
239 }
6a488035
TO
240 return $dbName;
241 }
242
243 /**
eceb18cc 244 * Create database connection for this instance.
6a488035
TO
245 *
246 * Initialize the test database if it hasn't been initialized
247 *
6a488035
TO
248 */
249 protected function getConnection() {
6a488035
TO
250 if (!self::$dbInit) {
251 $dbName = self::getDBName();
252
253 // install test database
254 echo PHP_EOL . "Installing {$dbName} database" . PHP_EOL;
255
99117745 256 static::_populateDB(FALSE, $this);
6a488035
TO
257
258 self::$dbInit = TRUE;
259 }
bc560b0a 260
6a488035
TO
261 }
262
263 /**
eceb18cc 264 * Required implementation of abstract method.
6a488035
TO
265 */
266 protected function getDataSet() {
267 }
268
99117745
TO
269 /**
270 * @param bool $perClass
271 * @param null $object
a6c01b45
CW
272 * @return bool
273 * TRUE if the populate logic runs; FALSE if it is skipped
99117745
TO
274 */
275 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
8582a9fc 276 if (CIVICRM_UF !== 'UnitTests') {
cdc44255 277 throw new \RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
8582a9fc 278 }
6a488035
TO
279
280 if ($perClass || $object == NULL) {
281 $dbreset = TRUE;
282 }
283 else {
284 $dbreset = $object->requireDBReset();
285 }
286
287 if (self::$populateOnce || !$dbreset) {
99117745 288 return FALSE;
6a488035
TO
289 }
290 self::$populateOnce = NULL;
291
728bbd5b 292 Civi\Test::data()->populate();
be709432
TO
293
294 return TRUE;
6a488035
TO
295 }
296
297 public static function setUpBeforeClass() {
99117745 298 static::_populateDB(TRUE);
6a488035
TO
299
300 // also set this global hack
301 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
302 }
303
304 /**
eceb18cc 305 * Common setup functions for all unit tests.
6a488035
TO
306 */
307 protected function setUp() {
4db17da0
TO
308 $session = CRM_Core_Session::singleton();
309 $session->set('userID', NULL);
310
2d932085
CW
311 $this->_apiversion = 3;
312
39b959db
SL
313 // REVERT
314 $this->errorScope = CRM_Core_TemporaryErrorScope::useException();
6a488035
TO
315 // Use a temporary file for STDIN
316 $GLOBALS['stdin'] = tmpfile();
317 if ($GLOBALS['stdin'] === FALSE) {
318 echo "Couldn't open temporary file\n";
319 exit(1);
320 }
321
322 // Get and save a connection to the database
323 $this->_dbconn = $this->getConnection();
324
325 // reload database before each test
326 // $this->_populateDB();
327
328 // "initialize" CiviCRM to avoid problems when running single tests
329 // FIXME: look at it closer in second stage
330
c0a1f187
TO
331 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
332 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
6a488035
TO
333
334 // disable any left-over test extensions
335 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
336
337 // reset all the caches
338 CRM_Utils_System::flushCache();
339
c0a1f187 340 // initialize the object once db is loaded
218c6f9c 341 \Civi::$statics = array();
39b959db
SL
342 // ugh, performance
343 $config = CRM_Core_Config::singleton(TRUE, TRUE);
c0a1f187
TO
344
345 // when running unit tests, use mockup user framework
edbcbd96 346 $this->hookClass = CRM_Utils_Hook::singleton();
c0a1f187 347
26684821
TO
348 // Make sure the DB connection is setup properly
349 $config->userSystem->setMySQLTimeZone();
a8de1c22 350 $env = new CRM_Utils_Check_Component_Env();
26684821
TO
351 CRM_Utils_Check::singleton()->assertValid($env->checkMysqlTime());
352
6a488035 353 // clear permissions stub to not check permissions
6a488035
TO
354 $config->userPermissionClass->permissions = NULL;
355
356 //flush component settings
357 CRM_Core_Component::getEnabledComponents(TRUE);
358
88a90442 359 $_REQUEST = $_GET = $_POST = [];
c3d574fc
EM
360 error_reporting(E_ALL);
361
91786f44 362 $this->renameLabels();
d58b453e 363 $this->_sethtmlGlobals();
6a488035
TO
364 }
365
0b6f58fa 366 /**
eceb18cc 367 * Read everything from the datasets directory and insert into the db.
0b6f58fa
ARW
368 */
369 public function loadAllFixtures() {
370 $fixturesDir = __DIR__ . '/../../fixtures';
371
8fee8f1c 372 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
0b6f58fa 373
b01b546f
TO
374 $jsonFiles = glob($fixturesDir . '/*.json');
375 foreach ($jsonFiles as $jsonFixture) {
376 $json = json_decode(file_get_contents($jsonFixture));
377 foreach ($json as $tableName => $vars) {
8fee8f1c 378 if ($tableName === 'civicrm_contact') {
379 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');
380 }
381 else {
382 CRM_Core_DAO::executeQuery("TRUNCATE $tableName");
383 }
384 foreach ($vars as $entity) {
385 $keys = $values = [];
386 foreach ($entity as $key => $value) {
387 $keys[] = $key;
388 $values[] = is_numeric($value) ? $value : "'{$value}'";
389 }
390 CRM_Core_DAO::executeQuery("
391 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
392 );
393 }
394
395 }
0b6f58fa
ARW
396 }
397
8fee8f1c 398 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
0b6f58fa
ARW
399 }
400
08d620bc 401 /**
402 * Load the data that used to be handled by the discontinued dbunit class.
403 *
404 * This could do with further tidy up - the initial priority is simply to get rid of
405 * the dbunity package which is no longer supported.
406 *
407 * @param string $fileName
408 */
409 protected function loadXMLDataSet($fileName) {
410 CRM_Core_DAO::executeQuery('SET FOREIGN_KEY_CHECKS = 0');
411 $xml = json_decode(json_encode(simplexml_load_file($fileName)), TRUE);
412 foreach ($xml as $tableName => $element) {
413 if (!empty($element)) {
414 foreach ($element as $row) {
415 $keys = $values = [];
416 if (isset($row['@attributes'])) {
417 foreach ($row['@attributes'] as $key => $value) {
418 $keys[] = $key;
419 $values[] = is_numeric($value) ? $value : "'{$value}'";
420 }
421 }
1d291c60 422 elseif (!empty($row)) {
08d620bc 423 // cos we copied it & it is inconsistent....
424 foreach ($row as $key => $value) {
425 $keys[] = $key;
426 $values[] = is_numeric($value) ? $value : "'{$value}'";
427 }
428 }
429
1d291c60 430 if (!empty($values)) {
431 CRM_Core_DAO::executeQuery("
08d620bc 432 INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
1d291c60 433 );
434 }
08d620bc 435 }
436 }
437 }
438 CRM_Core_DAO::executeQuery('SET FOREIGN_KEY_CHECKS = 1');
439 }
440
5767aa07 441 /**
eceb18cc 442 * Create default domain contacts for the two domains added during test class.
5767aa07
AN
443 * database population.
444 */
445 public function createDomainContacts() {
1ca22999 446 $this->organizationCreate();
447 $this->organizationCreate(array('organization_name' => 'Second Domain'));
5767aa07
AN
448 }
449
6a488035 450 /**
eceb18cc 451 * Common teardown functions for all unit tests.
6a488035
TO
452 */
453 protected function tearDown() {
2d932085 454 $this->_apiversion = 3;
91786f44 455 $this->resetLabels();
2d932085 456
6a488035 457 error_reporting(E_ALL & ~E_NOTICE);
6c466b51 458 CRM_Utils_Hook::singleton()->reset();
36a29dc0
TO
459 if ($this->hookClass) {
460 $this->hookClass->reset();
461 }
cbe41575 462 CRM_Core_Session::singleton()->reset(1);
d67f1f28
TO
463
464 if ($this->tx) {
465 $this->tx->rollback()->commit();
466 $this->tx = NULL;
467
468 CRM_Core_Transaction::forceRollbackIfEnabled();
469 \Civi\Core\Transaction\Manager::singleton(TRUE);
5896d037
TO
470 }
471 else {
d67f1f28
TO
472 CRM_Core_Transaction::forceRollbackIfEnabled();
473 \Civi\Core\Transaction\Manager::singleton(TRUE);
474
225d474b 475 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
d67f1f28 476 $this->quickCleanup($tablesToTruncate);
a335f6b2 477 $this->createDomainContacts();
d67f1f28
TO
478 }
479
6a488035
TO
480 $this->cleanTempDirs();
481 $this->unsetExtensionSystem();
a80606eb 482 $this->assertEquals([], CRM_Core_DAO::$_nullArray);
483 $this->assertEquals(NULL, CRM_Core_DAO::$_nullObject);
6a488035
TO
484 }
485
888dab1e
TO
486 /**
487 * Create a batch of external API calls which can
488 * be executed concurrently.
489 *
490 * @code
491 * $calls = $this->createExternalAPI()
492 * ->addCall('Contact', 'get', ...)
493 * ->addCall('Contact', 'get', ...)
494 * ...
495 * ->run()
496 * ->getResults();
497 * @endcode
498 *
499 * @return \Civi\API\ExternalBatch
500 * @throws PHPUnit_Framework_SkippedTestError
501 */
502 public function createExternalAPI() {
503 global $civicrm_root;
504 $defaultParams = array(
505 'version' => $this->_apiversion,
506 'debug' => 1,
507 );
508
509 $calls = new \Civi\API\ExternalBatch($defaultParams);
888dab1e
TO
510
511 if (!$calls->isSupported()) {
512 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
513 }
514
515 return $calls;
516 }
517
fbda92d3 518 /**
519 * Create required data based on $this->entity & $this->params
520 * This is just a way to set up the test data for delete & get functions
521 * so the distinction between set
522 * up & tested functions is clearer
523 *
a6c01b45
CW
524 * @return array
525 * api Result
fbda92d3 526 */
5896d037 527 public function createTestEntity() {
fbda92d3 528 return $entity = $this->callAPISuccess($this->entity, 'create', $this->params);
529 }
530
4cbe18b8 531 /**
100fef9d 532 * @param int $contactTypeId
4cbe18b8
EM
533 *
534 * @throws Exception
535 */
00be9182 536 public function contactTypeDelete($contactTypeId) {
6a488035
TO
537 $result = CRM_Contact_BAO_ContactType::del($contactTypeId);
538 if (!$result) {
539 throw new Exception('Could not delete contact type');
540 }
541 }
542
4cbe18b8
EM
543 /**
544 * @param array $params
545 *
546 * @return mixed
547 */
00be9182 548 public function membershipTypeCreate($params = array()) {
6a488035
TO
549 CRM_Member_PseudoConstant::flush('membershipType');
550 CRM_Core_Config::clearDBCache();
204beda3 551 $this->setupIDs['contact'] = $memberOfOrganization = $this->organizationCreate();
75638074 552 $params = array_merge(array(
6a488035
TO
553 'name' => 'General',
554 'duration_unit' => 'year',
555 'duration_interval' => 1,
556 'period_type' => 'rolling',
0090e3d2 557 'member_of_contact_id' => $memberOfOrganization,
6a488035 558 'domain_id' => 1,
4303ea89 559 'financial_type_id' => 2,
6a488035 560 'is_active' => 1,
6a488035 561 'sequential' => 1,
eacf220c 562 'visibility' => 'Public',
75638074 563 ), $params);
564
565 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
6a488035 566
6a488035
TO
567 CRM_Member_PseudoConstant::flush('membershipType');
568 CRM_Utils_Cache::singleton()->flush();
6a488035
TO
569
570 return $result['id'];
571 }
572
4cbe18b8 573 /**
c490a46a 574 * @param array $params
4cbe18b8
EM
575 *
576 * @return mixed
577 */
00be9182 578 public function contactMembershipCreate($params) {
5d8b37be 579 $params = array_merge(array(
6a488035
TO
580 'join_date' => '2007-01-21',
581 'start_date' => '2007-01-21',
582 'end_date' => '2007-12-21',
583 'source' => 'Payment',
5d8b37be 584 'membership_type_id' => 'General',
585 ), $params);
586 if (!is_numeric($params['membership_type_id'])) {
587 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
588 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
589 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
6a488035
TO
590 }
591 }
592
f6722559 593 $result = $this->callAPISuccess('Membership', 'create', $params);
6a488035
TO
594 return $result['id'];
595 }
596
597 /**
eceb18cc 598 * Delete Membership Type.
6a488035 599 *
c490a46a 600 * @param array $params
6a488035 601 */
00be9182 602 public function membershipTypeDelete($params) {
cab024d4 603 $this->callAPISuccess('MembershipType', 'Delete', $params);
6a488035
TO
604 }
605
4cbe18b8 606 /**
100fef9d 607 * @param int $membershipID
4cbe18b8 608 */
00be9182 609 public function membershipDelete($membershipID) {
f6722559 610 $deleteParams = array('id' => $membershipID);
611 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
6a488035
TO
612 }
613
4cbe18b8
EM
614 /**
615 * @param string $name
616 *
617 * @return mixed
618 */
00be9182 619 public function membershipStatusCreate($name = 'test member status') {
6a488035
TO
620 $params['name'] = $name;
621 $params['start_event'] = 'start_date';
622 $params['end_event'] = 'end_date';
623 $params['is_current_member'] = 1;
624 $params['is_active'] = 1;
6a488035 625
f6722559 626 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
6a488035 627 CRM_Member_PseudoConstant::flush('membershipStatus');
6a488035
TO
628 return $result['id'];
629 }
630
4cbe18b8 631 /**
100fef9d 632 * @param int $membershipStatusID
4cbe18b8 633 */
00be9182 634 public function membershipStatusDelete($membershipStatusID) {
6a488035
TO
635 if (!$membershipStatusID) {
636 return;
637 }
4732bb2f 638 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
6a488035
TO
639 }
640
17e615c7
MW
641 public function membershipRenewalDate($durationUnit, $membershipEndDate) {
642 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
643 $renewedMembershipEndDate = new DateTime($membershipEndDate);
644 switch ($durationUnit) {
645 case 'year':
646 $renewedMembershipEndDate->add(new DateInterval('P1Y'));
647 break;
648
649 case 'month':
650 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
651 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
652 $renewedMembershipEndDate->add(new DateInterval('P1D'));
653 $renewedMembershipEndDate->add(new DateInterval('P1M'));
654 $renewedMembershipEndDate->sub(new DateInterval('P1D'));
655 break;
656 }
657 return $renewedMembershipEndDate->format('Y-m-d');
658 }
659
4cbe18b8
EM
660 /**
661 * @param array $params
662 *
663 * @return mixed
664 */
00be9182 665 public function relationshipTypeCreate($params = array()) {
75638074 666 $params = array_merge(array(
39b959db
SL
667 'name_a_b' => 'Relation 1 for relationship type create',
668 'name_b_a' => 'Relation 2 for relationship type create',
669 'contact_type_a' => 'Individual',
670 'contact_type_b' => 'Organization',
671 'is_reserved' => 1,
672 'is_active' => 1,
673 ), $params);
6a488035 674
f6722559 675 $result = $this->callAPISuccess('relationship_type', 'create', $params);
6a488035
TO
676 CRM_Core_PseudoConstant::flush('relationshipType');
677
678 return $result['id'];
679 }
680
681 /**
eceb18cc 682 * Delete Relatinship Type.
6a488035
TO
683 *
684 * @param int $relationshipTypeID
685 */
00be9182 686 public function relationshipTypeDelete($relationshipTypeID) {
6a488035 687 $params['id'] = $relationshipTypeID;
a60c0bc8
SL
688 $check = $this->callAPISuccess('relationship_type', 'get', $params);
689 if (!empty($check['count'])) {
690 $this->callAPISuccess('relationship_type', 'delete', $params);
691 }
6a488035
TO
692 }
693
4cbe18b8 694 /**
100fef9d 695 * @param array $params
4cbe18b8
EM
696 *
697 * @return mixed
698 */
00be9182 699 public function paymentProcessorTypeCreate($params = NULL) {
6a488035
TO
700 if (is_null($params)) {
701 $params = array(
702 'name' => 'API_Test_PP',
703 'title' => 'API Test Payment Processor',
704 'class_name' => 'CRM_Core_Payment_APITest',
705 'billing_mode' => 'form',
706 'is_recur' => 0,
707 'is_reserved' => 1,
708 'is_active' => 1,
709 );
710 }
f6722559 711 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
6a488035 712
6a488035
TO
713 CRM_Core_PseudoConstant::flush('paymentProcessorType');
714
715 return $result['id'];
716 }
717
d6944518
EM
718 /**
719 * Create test Authorize.net instance.
720 *
721 * @param array $params
722 *
723 * @return mixed
724 */
725 public function paymentProcessorAuthorizeNetCreate($params = array()) {
726 $params = array_merge(array(
727 'name' => 'Authorize',
728 'domain_id' => CRM_Core_Config::domainID(),
729 'payment_processor_type_id' => 'AuthNet',
730 'title' => 'AuthNet',
731 'is_active' => 1,
732 'is_default' => 0,
733 'is_test' => 1,
734 'is_recur' => 1,
735 'user_name' => '4y5BfuW7jm',
736 'password' => '4cAmW927n8uLf5J8',
737 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
738 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
739 'class_name' => 'Payment_AuthorizeNet',
740 'billing_mode' => 1,
741 ), $params);
742
4ecbf127 743 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
d6944518
EM
744 return $result['id'];
745 }
746
6a488035 747 /**
eceb18cc 748 * Create Participant.
6a488035 749 *
e16033b4
TO
750 * @param array $params
751 * Array of contact id and event id values.
6a488035 752 *
a6c01b45
CW
753 * @return int
754 * $id of participant created
6a488035 755 */
0f57ba7a 756 public function participantCreate($params = []) {
5896d037 757 if (empty($params['contact_id'])) {
94692f2d 758 $params['contact_id'] = $this->individualCreate();
759 }
5896d037 760 if (empty($params['event_id'])) {
94692f2d 761 $event = $this->eventCreate();
762 $params['event_id'] = $event['id'];
763 }
6a488035 764 $defaults = array(
6a488035
TO
765 'status_id' => 2,
766 'role_id' => 1,
767 'register_date' => 20070219,
768 'source' => 'Wimbeldon',
769 'event_level' => 'Payment',
94692f2d 770 'debug' => 1,
6a488035
TO
771 );
772
773 $params = array_merge($defaults, $params);
f6722559 774 $result = $this->callAPISuccess('Participant', 'create', $params);
6a488035
TO
775 return $result['id'];
776 }
777
778 /**
eceb18cc 779 * Create Payment Processor.
6a488035 780 *
8950ecdc 781 * @return int
782 * Id Payment Processor
6a488035 783 */
0f07bb06 784 public function processorCreate($params = array()) {
6a488035
TO
785 $processorParams = array(
786 'domain_id' => 1,
787 'name' => 'Dummy',
8950ecdc 788 'payment_processor_type_id' => 'Dummy',
6a488035 789 'financial_account_id' => 12,
a8215a8d 790 'is_test' => TRUE,
6a488035
TO
791 'is_active' => 1,
792 'user_name' => '',
793 'url_site' => 'http://dummy.com',
794 'url_recur' => 'http://dummy.com',
795 'billing_mode' => 1,
8950ecdc 796 'sequential' => 1,
204efedd 797 'payment_instrument_id' => 'Debit Card',
6a488035 798 );
0f07bb06 799 $processorParams = array_merge($processorParams, $params);
8950ecdc 800 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
801 return $processor['id'];
22e39333 802 }
803
804 /**
805 * Create Payment Processor.
806 *
807 * @param array $processorParams
808 *
0193ebdb 809 * @return \CRM_Core_Payment_Dummy
39b959db 810 * Instance of Dummy Payment Processor
31eddd0d 811 *
812 * @throws \CiviCRM_API3_Exception
22e39333 813 */
31eddd0d 814 public function dummyProcessorCreate($processorParams = []) {
8950ecdc 815 $paymentProcessorID = $this->processorCreate($processorParams);
31eddd0d 816 // For the tests we don't need a live processor, but as core ALWAYS creates a processor in live mode and one in test mode we do need to create both
817 // Otherwise we are testing a scenario that only exists in tests (and some tests fail because the live processor has not been defined).
818 $processorParams['is_test'] = FALSE;
819 $this->processorCreate($processorParams);
7a3b0ca3 820 return System::singleton()->getById($paymentProcessorID);
6a488035
TO
821 }
822
823 /**
eceb18cc 824 * Create contribution page.
6a488035 825 *
c490a46a 826 * @param array $params
16b10e64
CW
827 * @return array
828 * Array of contribution page
6a488035 829 */
23ead872 830 public function contributionPageCreate($params = array()) {
831 $this->_pageParams = array_merge(array(
6a488035
TO
832 'title' => 'Test Contribution Page',
833 'financial_type_id' => 1,
834 'currency' => 'USD',
835 'financial_account_id' => 1,
6a488035
TO
836 'is_active' => 1,
837 'is_allow_other_amount' => 1,
838 'min_amount' => 10,
839 'max_amount' => 1000,
23ead872 840 ), $params);
841 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
6a488035
TO
842 }
843
a646bdd2
SB
844 /**
845 * Create a sample batch.
846 */
847 public function batchCreate() {
848 $params = $this->_params;
849 $params['name'] = $params['title'] = 'Batch_433397';
850 $params['status_id'] = 1;
851 $result = $this->callAPISuccess('batch', 'create', $params);
852 return $result['id'];
853 }
854
6a488035 855 /**
eceb18cc 856 * Create Tag.
6a488035 857 *
2a6da8d7 858 * @param array $params
a6c01b45
CW
859 * @return array
860 * result of created tag
6a488035 861 */
00be9182 862 public function tagCreate($params = array()) {
fb32de45 863 $defaults = array(
864 'name' => 'New Tag3',
865 'description' => 'This is description for Our New Tag ',
866 'domain_id' => '1',
867 );
868 $params = array_merge($defaults, $params);
6c6e6187 869 $result = $this->callAPISuccess('Tag', 'create', $params);
fb32de45 870 return $result['values'][$result['id']];
6a488035
TO
871 }
872
873 /**
eceb18cc 874 * Delete Tag.
6a488035 875 *
e16033b4
TO
876 * @param int $tagId
877 * Id of the tag to be deleted.
16b10e64
CW
878 *
879 * @return int
6a488035 880 */
00be9182 881 public function tagDelete($tagId) {
6a488035
TO
882 require_once 'api/api.php';
883 $params = array(
884 'tag_id' => $tagId,
6a488035 885 );
f6722559 886 $result = $this->callAPISuccess('Tag', 'delete', $params);
6a488035
TO
887 return $result['id'];
888 }
889
890 /**
891 * Add entity(s) to the tag
892 *
e16033b4 893 * @param array $params
77b97be7
EM
894 *
895 * @return bool
6a488035 896 */
00be9182 897 public function entityTagAdd($params) {
f6722559 898 $result = $this->callAPISuccess('entity_tag', 'create', $params);
6a488035
TO
899 return TRUE;
900 }
901
902 /**
5210fa35 903 * Create pledge.
6a488035 904 *
5210fa35 905 * @param array $params
906 * Parameters.
77b97be7 907 *
a6c01b45 908 * @return int
5210fa35 909 * id of created pledge
6a488035 910 */
5210fa35 911 public function pledgeCreate($params) {
912 $params = array_merge(array(
6a488035
TO
913 'pledge_create_date' => date('Ymd'),
914 'start_date' => date('Ymd'),
915 'scheduled_date' => date('Ymd'),
916 'amount' => 100.00,
917 'pledge_status_id' => '2',
918 'financial_type_id' => '1',
919 'pledge_original_installment_amount' => 20,
920 'frequency_interval' => 5,
921 'frequency_unit' => 'year',
922 'frequency_day' => 15,
923 'installments' => 5,
5210fa35 924 ),
925 $params);
6a488035 926
f6722559 927 $result = $this->callAPISuccess('Pledge', 'create', $params);
6a488035
TO
928 return $result['id'];
929 }
930
931 /**
eceb18cc 932 * Delete contribution.
6a488035 933 *
c490a46a 934 * @param int $pledgeId
6a488035 935 */
00be9182 936 public function pledgeDelete($pledgeId) {
6a488035
TO
937 $params = array(
938 'pledge_id' => $pledgeId,
6a488035 939 );
f6722559 940 $this->callAPISuccess('Pledge', 'delete', $params);
6a488035
TO
941 }
942
943 /**
eceb18cc 944 * Create contribution.
6a488035 945 *
c3a3074f 946 * @param array $params
947 * Array of parameters.
16b10e64 948 *
a6c01b45
CW
949 * @return int
950 * id of created contribution
6a488035 951 */
78ab0ca4 952 public function contributionCreate($params) {
69fccd8f 953
d6944518 954 $params = array_merge(array(
6a488035 955 'domain_id' => 1,
6a488035
TO
956 'receive_date' => date('Ymd'),
957 'total_amount' => 100.00,
69fccd8f 958 'fee_amount' => 5.00,
78ab0ca4 959 'financial_type_id' => 1,
960 'payment_instrument_id' => 1,
6a488035 961 'non_deductible_amount' => 10.00,
6a488035 962 'source' => 'SSF',
6a488035 963 'contribution_status_id' => 1,
d6944518 964 ), $params);
6a488035 965
f6722559 966 $result = $this->callAPISuccess('contribution', 'create', $params);
6a488035
TO
967 return $result['id'];
968 }
969
6a488035 970 /**
eceb18cc 971 * Delete contribution.
6a488035
TO
972 *
973 * @param int $contributionId
8deefe64
EM
974 *
975 * @return array|int
6a488035 976 */
00be9182 977 public function contributionDelete($contributionId) {
6a488035
TO
978 $params = array(
979 'contribution_id' => $contributionId,
6a488035 980 );
f6722559 981 $result = $this->callAPISuccess('contribution', 'delete', $params);
6a488035
TO
982 return $result;
983 }
984
985 /**
eceb18cc 986 * Create an Event.
6a488035 987 *
e16033b4
TO
988 * @param array $params
989 * Name-value pair for an event.
6a488035 990 *
a6c01b45 991 * @return array
6a488035 992 */
00be9182 993 public function eventCreate($params = array()) {
6a488035
TO
994 // if no contact was passed, make up a dummy event creator
995 if (!isset($params['contact_id'])) {
996 $params['contact_id'] = $this->_contactCreate(array(
997 'contact_type' => 'Individual',
998 'first_name' => 'Event',
999 'last_name' => 'Creator',
6a488035
TO
1000 ));
1001 }
1002
1003 // set defaults for missing params
1004 $params = array_merge(array(
1005 'title' => 'Annual CiviCRM meet',
1006 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1007 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1008 'event_type_id' => 1,
1009 'is_public' => 1,
1010 'start_date' => 20081021,
1011 'end_date' => 20081023,
1012 'is_online_registration' => 1,
1013 'registration_start_date' => 20080601,
1014 'registration_end_date' => 20081015,
1015 'max_participants' => 100,
1016 'event_full_text' => 'Sorry! We are already full',
c039f658 1017 'is_monetary' => 0,
6a488035 1018 'is_active' => 1,
6a488035 1019 'is_show_location' => 0,
e579af79 1020 'is_email_confirm' => 1,
6a488035
TO
1021 ), $params);
1022
8cba5814 1023 return $this->callAPISuccess('Event', 'create', $params);
6a488035
TO
1024 }
1025
f660d2ad 1026 /**
1027 * Create a paid event.
1028 *
1029 * @param array $params
1030 *
1031 * @return array
1032 */
1033 protected function eventCreatePaid($params) {
1034 $event = $this->eventCreate($params);
1035 $this->priceSetID = $this->eventPriceSetCreate(55, 0, 'Radio');
1036 CRM_Price_BAO_PriceSet::addTo('civicrm_event', $event['id'], $this->priceSetID);
1037 $priceSet = CRM_Price_BAO_PriceSet::getSetDetail($this->priceSetID, TRUE, FALSE);
1038 $priceSet = CRM_Utils_Array::value($this->priceSetID, $priceSet);
1039 $this->eventFeeBlock = CRM_Utils_Array::value('fields', $priceSet);
1040 return $event;
1041 }
1042
6a488035 1043 /**
eceb18cc 1044 * Delete event.
6a488035 1045 *
e16033b4
TO
1046 * @param int $id
1047 * ID of the event.
8deefe64
EM
1048 *
1049 * @return array|int
6a488035 1050 */
00be9182 1051 public function eventDelete($id) {
6a488035
TO
1052 $params = array(
1053 'event_id' => $id,
6a488035 1054 );
8cba5814 1055 return $this->callAPISuccess('event', 'delete', $params);
6a488035
TO
1056 }
1057
1058 /**
eceb18cc 1059 * Delete participant.
6a488035
TO
1060 *
1061 * @param int $participantID
8deefe64
EM
1062 *
1063 * @return array|int
6a488035 1064 */
00be9182 1065 public function participantDelete($participantID) {
6a488035
TO
1066 $params = array(
1067 'id' => $participantID,
6a488035 1068 );
a60c0bc8
SL
1069 $check = $this->callAPISuccess('Participant', 'get', $params);
1070 if ($check['count'] > 0) {
1071 return $this->callAPISuccess('Participant', 'delete', $params);
1072 }
6a488035
TO
1073 }
1074
1075 /**
eceb18cc 1076 * Create participant payment.
6a488035 1077 *
100fef9d
CW
1078 * @param int $participantID
1079 * @param int $contributionID
a6c01b45
CW
1080 * @return int
1081 * $id of created payment
6a488035 1082 */
00be9182 1083 public function participantPaymentCreate($participantID, $contributionID = NULL) {
6a488035
TO
1084 //Create Participant Payment record With Values
1085 $params = array(
1086 'participant_id' => $participantID,
1087 'contribution_id' => $contributionID,
6a488035
TO
1088 );
1089
f6722559 1090 $result = $this->callAPISuccess('participant_payment', 'create', $params);
6a488035
TO
1091 return $result['id'];
1092 }
1093
1094 /**
eceb18cc 1095 * Delete participant payment.
6a488035
TO
1096 *
1097 * @param int $paymentID
1098 */
00be9182 1099 public function participantPaymentDelete($paymentID) {
6a488035
TO
1100 $params = array(
1101 'id' => $paymentID,
6a488035 1102 );
f6722559 1103 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
6a488035
TO
1104 }
1105
1106 /**
eceb18cc 1107 * Add a Location.
6a488035 1108 *
100fef9d 1109 * @param int $contactID
a6c01b45
CW
1110 * @return int
1111 * location id of created location
6a488035 1112 */
00be9182 1113 public function locationAdd($contactID) {
6a488035
TO
1114 $address = array(
1115 1 => array(
1116 'location_type' => 'New Location Type',
1117 'is_primary' => 1,
1118 'name' => 'Saint Helier St',
1119 'county' => 'Marin',
86797006 1120 'country' => 'UNITED STATES',
6a488035
TO
1121 'state_province' => 'Michigan',
1122 'supplemental_address_1' => 'Hallmark Ct',
1123 'supplemental_address_2' => 'Jersey Village',
207f62c6 1124 'supplemental_address_3' => 'My Town',
21dfd5f5 1125 ),
6a488035
TO
1126 );
1127
1128 $params = array(
1129 'contact_id' => $contactID,
1130 'address' => $address,
6a488035
TO
1131 'location_format' => '2.0',
1132 'location_type' => 'New Location Type',
1133 );
1134
f6722559 1135 $result = $this->callAPISuccess('Location', 'create', $params);
6a488035
TO
1136 return $result;
1137 }
1138
1139 /**
eceb18cc 1140 * Delete Locations of contact.
6a488035 1141 *
e16033b4
TO
1142 * @param array $params
1143 * Parameters.
6a488035 1144 */
00be9182 1145 public function locationDelete($params) {
c490a46a 1146 $this->callAPISuccess('Location', 'delete', $params);
6a488035
TO
1147 }
1148
1149 /**
eceb18cc 1150 * Add a Location Type.
6a488035 1151 *
100fef9d 1152 * @param array $params
16b10e64
CW
1153 * @return CRM_Core_DAO_LocationType
1154 * location id of created location
6a488035 1155 */
00be9182 1156 public function locationTypeCreate($params = NULL) {
6a488035
TO
1157 if ($params === NULL) {
1158 $params = array(
1159 'name' => 'New Location Type',
1160 'vcard_name' => 'New Location Type',
1161 'description' => 'Location Type for Delete',
1162 'is_active' => 1,
1163 );
1164 }
1165
6a488035
TO
1166 $locationType = new CRM_Core_DAO_LocationType();
1167 $locationType->copyValues($params);
1168 $locationType->save();
1169 // clear getfields cache
2683ce94 1170 CRM_Core_PseudoConstant::flush();
f6722559 1171 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
6a488035
TO
1172 return $locationType;
1173 }
1174
1175 /**
eceb18cc 1176 * Delete a Location Type.
6a488035 1177 *
79d7553f 1178 * @param int $locationTypeId
6a488035 1179 */
00be9182 1180 public function locationTypeDelete($locationTypeId) {
6a488035
TO
1181 $locationType = new CRM_Core_DAO_LocationType();
1182 $locationType->id = $locationTypeId;
1183 $locationType->delete();
1184 }
1185
927f93e2
TM
1186 /**
1187 * Add a Mapping.
1188 *
1189 * @param array $params
1190 * @return CRM_Core_DAO_Mapping
1191 * Mapping id of created mapping
1192 */
1193 public function mappingCreate($params = NULL) {
1194 if ($params === NULL) {
1195 $params = array(
1196 'name' => 'Mapping name',
1197 'description' => 'Mapping description',
1198 // 'Export Contact' mapping.
1199 'mapping_type_id' => 7,
1200 );
1201 }
1202
1203 $mapping = new CRM_Core_DAO_Mapping();
1204 $mapping->copyValues($params);
1205 $mapping->save();
1206 // clear getfields cache
1207 CRM_Core_PseudoConstant::flush();
1208 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1209 return $mapping;
1210 }
1211
1212 /**
1213 * Delete a Mapping
1214 *
1215 * @param int $mappingId
1216 */
1217 public function mappingDelete($mappingId) {
1218 $mapping = new CRM_Core_DAO_Mapping();
1219 $mapping->id = $mappingId;
1220 $mapping->delete();
1221 }
1222
5e8daa54 1223 /**
1224 * Prepare class for ACLs.
1225 */
1226 protected function prepareForACLs() {
1227 $config = CRM_Core_Config::singleton();
1228 $config->userPermissionClass->permissions = array();
1229 }
1230
1231 /**
1232 * Reset after ACLs.
1233 */
1234 protected function cleanUpAfterACLs() {
1235 CRM_Utils_Hook::singleton()->reset();
1236 $tablesToTruncate = array(
1237 'civicrm_acl',
1238 'civicrm_acl_cache',
1239 'civicrm_acl_entity_role',
1240 'civicrm_acl_contact_cache',
1241 );
1242 $this->quickCleanup($tablesToTruncate);
1243 $config = CRM_Core_Config::singleton();
1244 unset($config->userPermissionClass->permissions);
1245 }
39b959db 1246
c3137c08 1247 /**
1248 * Create a smart group.
1249 *
1250 * By default it will be a group of households.
1251 *
1252 * @param array $smartGroupParams
1253 * @param array $groupParams
0d38cb6d 1254 * @param string $contactType
1255 *
c3137c08 1256 * @return int
1257 */
0d38cb6d 1258 public function smartGroupCreate($smartGroupParams = [], $groupParams = [], $contactType = 'Household') {
1259 $smartGroupParams = array_merge([
1260 'formValues' => ['contact_type' => ['IN' => [$contactType]]],
1261 ],
1262 $smartGroupParams);
c3137c08 1263 $savedSearch = CRM_Contact_BAO_SavedSearch::create($smartGroupParams);
1264
1265 $groupParams['saved_search_id'] = $savedSearch->id;
1266 return $this->groupCreate($groupParams);
1267 }
7811a84b 1268
5c496c74 1269 /**
eceb18cc 1270 * Create a UFField.
5c496c74 1271 * @param array $params
1272 */
00be9182 1273 public function uFFieldCreate($params = array()) {
5c496c74 1274 $params = array_merge(array(
1275 'uf_group_id' => 1,
1276 'field_name' => 'first_name',
1277 'is_active' => 1,
1278 'is_required' => 1,
1279 'visibility' => 'Public Pages and Listings',
1280 'is_searchable' => '1',
1281 'label' => 'first_name',
1282 'field_type' => 'Individual',
1283 'weight' => 1,
1284 ), $params);
1285 $this->callAPISuccess('uf_field', 'create', $params);
1286 }
2a6da8d7 1287
6a488035 1288 /**
eceb18cc 1289 * Add a UF Join Entry.
6a488035 1290 *
100fef9d 1291 * @param array $params
a6c01b45
CW
1292 * @return int
1293 * $id of created UF Join
6a488035 1294 */
00be9182 1295 public function ufjoinCreate($params = NULL) {
6a488035
TO
1296 if ($params === NULL) {
1297 $params = array(
1298 'is_active' => 1,
1299 'module' => 'CiviEvent',
1300 'entity_table' => 'civicrm_event',
1301 'entity_id' => 3,
1302 'weight' => 1,
1303 'uf_group_id' => 1,
1304 );
1305 }
f6722559 1306 $result = $this->callAPISuccess('uf_join', 'create', $params);
6a488035
TO
1307 return $result;
1308 }
1309
c03f1689
EM
1310 /**
1311 * @param array $params
1312 * Optional parameters.
d31d0888 1313 * @param bool $reloadConfig
1314 * While enabling CiviCampaign component, we shouldn't always forcibly
1315 * reload config as this hinder hook call in test environment
c03f1689
EM
1316 *
1317 * @return int
1318 * Campaign ID.
1319 */
d31d0888 1320 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1321 $this->enableCiviCampaign($reloadConfig);
c03f1689
EM
1322 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1323 'name' => 'big_campaign',
1324 'title' => 'Campaign',
1325 ), $params));
1326 return $campaign['id'];
1327 }
1328
6a488035 1329 /**
eceb18cc 1330 * Create Group for a contact.
6a488035
TO
1331 *
1332 * @param int $contactId
1333 */
00be9182 1334 public function contactGroupCreate($contactId) {
6a488035
TO
1335 $params = array(
1336 'contact_id.1' => $contactId,
1337 'group_id' => 1,
1338 );
1339
f6722559 1340 $this->callAPISuccess('GroupContact', 'Create', $params);
6a488035
TO
1341 }
1342
1343 /**
eceb18cc 1344 * Delete Group for a contact.
6a488035 1345 *
100fef9d 1346 * @param int $contactId
6a488035 1347 */
00be9182 1348 public function contactGroupDelete($contactId) {
6a488035
TO
1349 $params = array(
1350 'contact_id.1' => $contactId,
1351 'group_id' => 1,
1352 );
0f643fb2 1353 $this->civicrm_api('GroupContact', 'Delete', $params);
6a488035
TO
1354 }
1355
1356 /**
eceb18cc 1357 * Create Activity.
6a488035 1358 *
c490a46a 1359 * @param array $params
2a6da8d7 1360 * @return array|int
6a488035 1361 */
5d8b37be 1362 public function activityCreate($params = array()) {
1363 $params = array_merge(array(
1364 'subject' => 'Discussion on warm beer',
1365 'activity_date_time' => date('Ymd'),
1366 'duration_hours' => 30,
1367 'duration_minutes' => 20,
1368 'location' => 'Baker Street',
1369 'details' => 'Lets schedule a meeting',
1370 'status_id' => 1,
3af8de9f 1371 'activity_type_id' => 'Meeting',
5d8b37be 1372 ), $params);
1373 if (!isset($params['source_contact_id'])) {
1374 $params['source_contact_id'] = $this->individualCreate();
1375 }
1376 if (!isset($params['target_contact_id'])) {
1377 $params['target_contact_id'] = $this->individualCreate(array(
6a488035 1378 'first_name' => 'Julia',
573aab99 1379 'last_name' => 'Anderson',
6a488035
TO
1380 'prefix' => 'Ms.',
1381 'email' => 'julia_anderson@civicrm.org',
1382 'contact_type' => 'Individual',
5d8b37be 1383 ));
1384 }
1385 if (!isset($params['assignee_contact_id'])) {
1386 $params['assignee_contact_id'] = $params['target_contact_id'];
6a488035
TO
1387 }
1388
2d932085 1389 $result = civicrm_api3('Activity', 'create', $params);
6a488035 1390
5d8b37be 1391 $result['target_contact_id'] = $params['target_contact_id'];
1392 $result['assignee_contact_id'] = $params['assignee_contact_id'];
6a488035
TO
1393 return $result;
1394 }
1395
1396 /**
eceb18cc 1397 * Create an activity type.
6a488035 1398 *
e16033b4
TO
1399 * @param array $params
1400 * Parameters.
f0be539a 1401 * @return array
6a488035 1402 */
00be9182 1403 public function activityTypeCreate($params) {
f0be539a 1404 return $this->callAPISuccess('ActivityType', 'create', $params);
79d7553f 1405 }
6a488035
TO
1406
1407 /**
eceb18cc 1408 * Delete activity type.
6a488035 1409 *
e16033b4
TO
1410 * @param int $activityTypeId
1411 * Id of the activity type.
f0be539a 1412 * @return array
6a488035 1413 */
00be9182 1414 public function activityTypeDelete($activityTypeId) {
6a488035 1415 $params['activity_type_id'] = $activityTypeId;
f0be539a 1416 return $this->callAPISuccess('ActivityType', 'delete', $params);
79d7553f 1417 }
6a488035
TO
1418
1419 /**
eceb18cc 1420 * Create custom group.
6a488035 1421 *
2a6da8d7 1422 * @param array $params
27dd6252 1423 * @return array
6a488035 1424 */
00be9182 1425 public function customGroupCreate($params = array()) {
f6722559 1426 $defaults = array(
1427 'title' => 'new custom group',
1428 'extends' => 'Contact',
1429 'domain_id' => 1,
1430 'style' => 'Inline',
1431 'is_active' => 1,
1432 );
6a488035 1433
f6722559 1434 $params = array_merge($defaults, $params);
1435
f6722559 1436 return $this->callAPISuccess('custom_group', 'create', $params);
6a488035
TO
1437 }
1438
1439 /**
100fef9d 1440 * Existing function doesn't allow params to be over-ridden so need a new one
6a488035 1441 * this one allows you to only pass in the params you want to change
1e1fdcf6
EM
1442 * @param array $params
1443 * @return array|int
6a488035 1444 */
00be9182 1445 public function CustomGroupCreateByParams($params = array()) {
6a488035
TO
1446 $defaults = array(
1447 'title' => "API Custom Group",
1448 'extends' => 'Contact',
1449 'domain_id' => 1,
1450 'style' => 'Inline',
1451 'is_active' => 1,
6a488035
TO
1452 );
1453 $params = array_merge($defaults, $params);
f6722559 1454 return $this->callAPISuccess('custom_group', 'create', $params);
6a488035
TO
1455 }
1456
1457 /**
eceb18cc 1458 * Create custom group with multi fields.
1e1fdcf6
EM
1459 * @param array $params
1460 * @return array|int
6a488035 1461 */
00be9182 1462 public function CustomGroupMultipleCreateByParams($params = array()) {
6a488035
TO
1463 $defaults = array(
1464 'style' => 'Tab',
1465 'is_multiple' => 1,
1466 );
1467 $params = array_merge($defaults, $params);
f6722559 1468 return $this->CustomGroupCreateByParams($params);
6a488035
TO
1469 }
1470
1471 /**
eceb18cc 1472 * Create custom group with multi fields.
1e1fdcf6
EM
1473 * @param array $params
1474 * @return array
6a488035 1475 */
00be9182 1476 public function CustomGroupMultipleCreateWithFields($params = array()) {
6a488035
TO
1477 // also need to pass on $params['custom_field'] if not set but not in place yet
1478 $ids = array();
1479 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1480 $ids['custom_group_id'] = $customGroup['id'];
6a488035 1481
5896d037 1482 $customField = $this->customFieldCreate(array(
92915c55
TO
1483 'custom_group_id' => $ids['custom_group_id'],
1484 'label' => 'field_1' . $ids['custom_group_id'],
e525d6af 1485 'in_selector' => 1,
92915c55 1486 ));
6a488035
TO
1487
1488 $ids['custom_field_id'][] = $customField['id'];
f6722559 1489
5896d037 1490 $customField = $this->customFieldCreate(array(
92915c55
TO
1491 'custom_group_id' => $ids['custom_group_id'],
1492 'default_value' => '',
1493 'label' => 'field_2' . $ids['custom_group_id'],
e525d6af 1494 'in_selector' => 1,
92915c55 1495 ));
6a488035 1496 $ids['custom_field_id'][] = $customField['id'];
f6722559 1497
5896d037 1498 $customField = $this->customFieldCreate(array(
92915c55
TO
1499 'custom_group_id' => $ids['custom_group_id'],
1500 'default_value' => '',
1501 'label' => 'field_3' . $ids['custom_group_id'],
e525d6af 1502 'in_selector' => 1,
92915c55 1503 ));
6a488035 1504 $ids['custom_field_id'][] = $customField['id'];
f6722559 1505
6a488035
TO
1506 return $ids;
1507 }
1508
1509 /**
1510 * Create a custom group with a single text custom field. See
1511 * participant:testCreateWithCustom for how to use this
1512 *
e16033b4
TO
1513 * @param string $function
1514 * __FUNCTION__.
5a4f6742
CW
1515 * @param string $filename
1516 * $file __FILE__.
6a488035 1517 *
a6c01b45
CW
1518 * @return array
1519 * ids of created objects
6a488035 1520 */
00be9182 1521 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
f6722559 1522 $params = array('title' => $function);
6a488035 1523 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
6c6e6187 1524 $params['extends'] = $entity ? $entity : 'Contact';
f6722559 1525 $customGroup = $this->CustomGroupCreate($params);
b422b715 1526 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
80085473 1527 CRM_Core_PseudoConstant::flush();
6a488035
TO
1528
1529 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1530 }
1531
d215c0e1
MH
1532 /**
1533 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1534 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1535 *
1536 * @param string $function
1537 * __FUNCTION__.
1538 * @param string $filename
1539 * $file __FILE__.
1540 *
1541 * @return array
1542 * ids of created objects
1543 */
1544 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1545 $params = array('title' => $function);
1546 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1547 $params['extends'] = $entity ? $entity : 'Contact';
1548 $customGroup = $this->CustomGroupCreate($params);
1549 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1550 CRM_Core_PseudoConstant::flush();
1551 $options = [
1552 'defaultValue' => 'Default Value',
1553 'lowercasevalue' => 'Lowercase Value',
1554 1 => 'Integer Value',
08703635 1555 'NULL' => 'NULL',
d215c0e1
MH
1556 ];
1557 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1558 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1559 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1560 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1561 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1562 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1563 foreach ($options as $option_value => $option_label) {
1564 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1565 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1566 }
1567
1568 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);
1569 }
1570
6a488035 1571 /**
eceb18cc 1572 * Delete custom group.
6a488035 1573 *
8deefe64
EM
1574 * @param int $customGroupID
1575 *
1576 * @return array|int
6a488035 1577 */
00be9182 1578 public function customGroupDelete($customGroupID) {
6a488035 1579 $params['id'] = $customGroupID;
f6722559 1580 return $this->callAPISuccess('custom_group', 'delete', $params);
6a488035
TO
1581 }
1582
1583 /**
eceb18cc 1584 * Create custom field.
6a488035 1585 *
e16033b4
TO
1586 * @param array $params
1587 * (custom_group_id) is required.
507d3b64 1588 * @return array
6a488035 1589 */
00be9182 1590 public function customFieldCreate($params) {
b422b715 1591 $params = array_merge(array(
1592 'label' => 'Custom Field',
6a488035
TO
1593 'data_type' => 'String',
1594 'html_type' => 'Text',
1595 'is_searchable' => 1,
1596 'is_active' => 1,
5c496c74 1597 'default_value' => 'defaultValue',
b422b715 1598 ), $params);
6a488035 1599
5c496c74 1600 $result = $this->callAPISuccess('custom_field', 'create', $params);
507d3b64
EM
1601 // these 2 functions are called with force to flush static caches
1602 CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
1603 CRM_Core_Component::getEnabledComponents(1);
1604 return $result;
6a488035
TO
1605 }
1606
1607 /**
eceb18cc 1608 * Delete custom field.
6a488035
TO
1609 *
1610 * @param int $customFieldID
8deefe64
EM
1611 *
1612 * @return array|int
6a488035 1613 */
00be9182 1614 public function customFieldDelete($customFieldID) {
6a488035
TO
1615
1616 $params['id'] = $customFieldID;
f6722559 1617 return $this->callAPISuccess('custom_field', 'delete', $params);
6a488035
TO
1618 }
1619
1620 /**
eceb18cc 1621 * Create note.
6a488035 1622 *
100fef9d 1623 * @param int $cId
a6c01b45 1624 * @return array
6a488035 1625 */
00be9182 1626 public function noteCreate($cId) {
6a488035
TO
1627 $params = array(
1628 'entity_table' => 'civicrm_contact',
1629 'entity_id' => $cId,
1630 'note' => 'hello I am testing Note',
1631 'contact_id' => $cId,
1632 'modified_date' => date('Ymd'),
1633 'subject' => 'Test Note',
6a488035
TO
1634 );
1635
f6722559 1636 return $this->callAPISuccess('Note', 'create', $params);
6a488035
TO
1637 }
1638
07fd63f5 1639 /**
eceb18cc 1640 * Enable CiviCampaign Component.
d31d0888 1641 *
1642 * @param bool $reloadConfig
1643 * Force relaod config or not
07fd63f5 1644 */
d31d0888 1645 public function enableCiviCampaign($reloadConfig = TRUE) {
07fd63f5 1646 CRM_Core_BAO_ConfigSetting::enableComponent('CiviCampaign');
d31d0888 1647 if ($reloadConfig) {
1648 // force reload of config object
1649 $config = CRM_Core_Config::singleton(TRUE, TRUE);
1650 }
07fd63f5
E
1651 //flush cache by calling with reset
1652 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1653 }
1654
6a488035 1655 /**
eceb18cc 1656 * Create custom field with Option Values.
6a488035 1657 *
77b97be7 1658 * @param array $customGroup
e16033b4
TO
1659 * @param string $name
1660 * Name of custom field.
412585fb 1661 * @param array $extraParams
1662 * Additional parameters to pass through.
77b97be7
EM
1663 *
1664 * @return array|int
6a488035 1665 */
412585fb 1666 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
6a488035
TO
1667 $fieldParams = array(
1668 'custom_group_id' => $customGroup['id'],
1669 'name' => 'test_custom_group',
1670 'label' => 'Country',
1671 'html_type' => 'Select',
1672 'data_type' => 'String',
1673 'weight' => 4,
1674 'is_required' => 1,
1675 'is_searchable' => 0,
1676 'is_active' => 1,
6a488035
TO
1677 );
1678
1679 $optionGroup = array(
1680 'domain_id' => 1,
1681 'name' => 'option_group1',
1682 'label' => 'option_group_label1',
1683 );
1684
1685 $optionValue = array(
1686 'option_label' => array('Label1', 'Label2'),
1687 'option_value' => array('value1', 'value2'),
1688 'option_name' => array($name . '_1', $name . '_2'),
1689 'option_weight' => array(1, 2),
875e076b 1690 'option_status' => array(1, 1),
6a488035
TO
1691 );
1692
412585fb 1693 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
6a488035 1694
f6722559 1695 return $this->callAPISuccess('custom_field', 'create', $params);
6a488035
TO
1696 }
1697
4cbe18b8
EM
1698 /**
1699 * @param $entities
1700 *
1701 * @return bool
1702 */
00be9182 1703 public function confirmEntitiesDeleted($entities) {
6a488035
TO
1704 foreach ($entities as $entity) {
1705
f6722559 1706 $result = $this->callAPISuccess($entity, 'Get', array());
6a488035
TO
1707 if ($result['error'] == 1 || $result['count'] > 0) {
1708 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1709 return TRUE;
1710 }
1711 }
f0be539a 1712 return FALSE;
6a488035
TO
1713 }
1714
4cbe18b8 1715 /**
0fff773f 1716 * Quick clean by emptying tables created for the test.
1717 *
1718 * @param array $tablesToTruncate
4cbe18b8 1719 * @param bool $dropCustomValueTables
ca8901aa 1720 * @throws \CRM_Core_Exception
4cbe18b8 1721 */
00be9182 1722 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
d67f1f28 1723 if ($this->tx) {
ca8901aa 1724 throw new \CRM_Core_Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
d67f1f28 1725 }
6a488035 1726 if ($dropCustomValueTables) {
0fff773f 1727 $optionGroupResult = CRM_Core_DAO::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
1728 while ($optionGroupResult->fetch()) {
1729 if (!empty($optionGroupResult->option_group_id)) {
1730 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id);
1731 }
1732 }
6a488035
TO
1733 $tablesToTruncate[] = 'civicrm_custom_group';
1734 $tablesToTruncate[] = 'civicrm_custom_field';
1735 }
1736
0b6f58fa
ARW
1737 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate, $tablesToTruncate));
1738
6a488035
TO
1739 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1740 foreach ($tablesToTruncate as $table) {
1741 $sql = "TRUNCATE TABLE $table";
1742 CRM_Core_DAO::executeQuery($sql);
1743 }
1744 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1745
1746 if ($dropCustomValueTables) {
1747 $dbName = self::getDBName();
1748 $query = "
1749SELECT TABLE_NAME as tableName
1750FROM INFORMATION_SCHEMA.TABLES
1751WHERE TABLE_SCHEMA = '{$dbName}'
1752AND ( TABLE_NAME LIKE 'civicrm_value_%' )
1753";
1754
1755 $tableDAO = CRM_Core_DAO::executeQuery($query);
1756 while ($tableDAO->fetch()) {
1757 $sql = "DROP TABLE {$tableDAO->tableName}";
1758 CRM_Core_DAO::executeQuery($sql);
1759 }
1760 }
1761 }
1762
b38530f2
EM
1763 /**
1764 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1765 */
00be9182 1766 public function quickCleanUpFinancialEntities() {
b38530f2 1767 $tablesToTruncate = array(
a380f4a0
EM
1768 'civicrm_activity',
1769 'civicrm_activity_contact',
b38530f2 1770 'civicrm_contribution',
39d632fd 1771 'civicrm_contribution_soft',
945f423d 1772 'civicrm_contribution_product',
b38530f2 1773 'civicrm_financial_trxn',
39d632fd 1774 'civicrm_financial_item',
b38530f2
EM
1775 'civicrm_contribution_recur',
1776 'civicrm_line_item',
1777 'civicrm_contribution_page',
1778 'civicrm_payment_processor',
1779 'civicrm_entity_financial_trxn',
1780 'civicrm_membership',
1781 'civicrm_membership_type',
1782 'civicrm_membership_payment',
cab024d4 1783 'civicrm_membership_log',
f9342903 1784 'civicrm_membership_block',
b38530f2
EM
1785 'civicrm_event',
1786 'civicrm_participant',
1787 'civicrm_participant_payment',
1788 'civicrm_pledge',
01ead735 1789 'civicrm_pledge_block',
294cc627 1790 'civicrm_pledge_payment',
1cf3c2b1 1791 'civicrm_price_set_entity',
108ff21a
EM
1792 'civicrm_price_field_value',
1793 'civicrm_price_field',
b38530f2
EM
1794 );
1795 $this->quickCleanup($tablesToTruncate);
4278b952 1796 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
108ff21a 1797 $this->restoreDefaultPriceSetConfig();
6d8a45ed
EM
1798 $var = TRUE;
1799 CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE);
9fbf312f 1800 $this->disableTaxAndInvoicing();
83644f47 1801 $this->setCurrencySeparators(',');
1802 CRM_Core_PseudoConstant::flush('taxRates');
7a3b0ca3 1803 System::singleton()->flushProcessors();
bc438a52 1804 // @fixme this parameter is leaking - it should not be defined as a class static
1805 // but for now we just handle in tear down.
1806 CRM_Contribute_BAO_Query::$_contribOrSoftCredit = 'only contribs';
108ff21a
EM
1807 }
1808
00be9182 1809 public function restoreDefaultPriceSetConfig() {
cdd71d6b 1810 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1811 CRM_Core_DAO::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
108ff21a 1812 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)");
5afce5ad 1813 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)");
b38530f2 1814 }
39b959db 1815
6a488035
TO
1816 /*
1817 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
1818 * Default behaviour is to also delete the entity
e16033b4 1819 * @param array $params
e4f46be0 1820 * Params array to check against.
e16033b4
TO
1821 * @param int $id
1822 * Id of the entity concerned.
1823 * @param string $entity
1824 * Name of entity concerned (e.g. membership).
1825 * @param bool $delete
1826 * Should the entity be deleted as part of this check.
1827 * @param string $errorText
1828 * Text to print on error.
6a488035 1829 */
39b959db 1830
4cbe18b8 1831 /**
c490a46a 1832 * @param array $params
100fef9d 1833 * @param int $id
4cbe18b8
EM
1834 * @param $entity
1835 * @param int $delete
1836 * @param string $errorText
1837 *
1838 * @throws Exception
1839 */
00be9182 1840 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
6a488035 1841
f6722559 1842 $result = $this->callAPISuccessGetSingle($entity, array(
6a488035 1843 'id' => $id,
6a488035
TO
1844 ));
1845
1846 if ($delete) {
f6722559 1847 $this->callAPISuccess($entity, 'Delete', array(
6a488035 1848 'id' => $id,
6a488035
TO
1849 ));
1850 }
b0aaad8c 1851 $dateFields = $keys = $dateTimeFields = array();
f6722559 1852 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
6a488035
TO
1853 foreach ($fields['values'] as $field => $settings) {
1854 if (array_key_exists($field, $result)) {
1855 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = $field;
1856 }
1857 else {
1858 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = CRM_Utils_Array::value('name', $settings, $field);
1859 }
afd404ea 1860 $type = CRM_Utils_Array::value('type', $settings);
1861 if ($type == CRM_Utils_Type::T_DATE) {
1862 $dateFields[] = $settings['name'];
1863 // we should identify both real names & unique names as dates
5896d037 1864 if ($field != $settings['name']) {
afd404ea 1865 $dateFields[] = $field;
1866 }
1867 }
5896d037 1868 if ($type == CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) {
afd404ea 1869 $dateTimeFields[] = $settings['name'];
1870 // we should identify both real names & unique names as dates
5896d037 1871 if ($field != $settings['name']) {
afd404ea 1872 $dateTimeFields[] = $field;
1873 }
6a488035
TO
1874 }
1875 }
1876
1877 if (strtolower($entity) == 'contribution') {
1878 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
1879 // this is not returned in id format
1880 unset($params['payment_instrument_id']);
1881 $params['contribution_source'] = $params['source'];
1882 unset($params['source']);
1883 }
1884
1885 foreach ($params as $key => $value) {
afd404ea 1886 if ($key == 'version' || substr($key, 0, 3) == 'api' || !array_key_exists($keys[$key], $result)) {
6a488035
TO
1887 continue;
1888 }
1889 if (in_array($key, $dateFields)) {
1890 $value = date('Y-m-d', strtotime($value));
1891 $result[$key] = date('Y-m-d', strtotime($result[$key]));
1892 }
afd404ea 1893 if (in_array($key, $dateTimeFields)) {
1894 $value = date('Y-m-d H:i:s', strtotime($value));
a72cec08 1895 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array::value($keys[$key], $result, CRM_Utils_Array::value($key, $result))));
afd404ea 1896 }
1897 $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);
6a488035
TO
1898 }
1899 }
1900
1901 /**
eceb18cc 1902 * Get formatted values in the actual and expected result.
e16033b4
TO
1903 * @param array $actual
1904 * Actual calculated values.
1905 * @param array $expected
1906 * Expected values.
6a488035 1907 */
00be9182 1908 public function checkArrayEquals(&$actual, &$expected) {
6a488035
TO
1909 self::unsetId($actual);
1910 self::unsetId($expected);
25115a3e 1911 $this->assertEquals($expected, $actual);
6a488035
TO
1912 }
1913
1914 /**
100fef9d 1915 * Unset the key 'id' from the array
e16033b4
TO
1916 * @param array $unformattedArray
1917 * The array from which the 'id' has to be unset.
6a488035 1918 */
00be9182 1919 public static function unsetId(&$unformattedArray) {
6a488035
TO
1920 $formattedArray = array();
1921 if (array_key_exists('id', $unformattedArray)) {
1922 unset($unformattedArray['id']);
1923 }
a7488080 1924 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
6a488035 1925 foreach ($unformattedArray['values'] as $key => $value) {
6c6e6187 1926 if (is_array($value)) {
6a488035
TO
1927 foreach ($value as $k => $v) {
1928 if ($k == 'id') {
1929 unset($value[$k]);
1930 }
1931 }
1932 }
1933 elseif ($key == 'id') {
1934 $unformattedArray[$key];
1935 }
1936 $formattedArray = array($value);
1937 }
1938 $unformattedArray['values'] = $formattedArray;
1939 }
1940 }
1941
1942 /**
1943 * Helper to enable/disable custom directory support
1944 *
e16033b4
TO
1945 * @param array $customDirs
1946 * With members:.
6a488035
TO
1947 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1948 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1949 */
00be9182 1950 public function customDirectories($customDirs) {
6a488035
TO
1951 $config = CRM_Core_Config::singleton();
1952
1953 if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
1954 unset($config->customPHPPathDir);
1955 }
1956 elseif ($customDirs['php_path'] === TRUE) {
1957 $config->customPHPPathDir = dirname(dirname(__FILE__)) . '/custom_directories/php/';
1958 }
1959 else {
1960 $config->customPHPPathDir = $php_path;
1961 }
1962
1963 if (empty($customDirs['template_path']) || $customDirs['template_path'] === FALSE) {
1964 unset($config->customTemplateDir);
1965 }
1966 elseif ($customDirs['template_path'] === TRUE) {
1967 $config->customTemplateDir = dirname(dirname(__FILE__)) . '/custom_directories/templates/';
1968 }
1969 else {
1970 $config->customTemplateDir = $template_path;
1971 }
1972 }
1973
1974 /**
eceb18cc 1975 * Generate a temporary folder.
6a488035 1976 *
2a6da8d7 1977 * @param string $prefix
a6c01b45 1978 * @return string
6a488035 1979 */
00be9182 1980 public function createTempDir($prefix = 'test-') {
6a488035
TO
1981 $tempDir = CRM_Utils_File::tempdir($prefix);
1982 $this->tempDirs[] = $tempDir;
1983 return $tempDir;
1984 }
1985
00be9182 1986 public function cleanTempDirs() {
6a488035
TO
1987 if (!is_array($this->tempDirs)) {
1988 // fix test errors where this is not set
1989 return;
1990 }
1991 foreach ($this->tempDirs as $tempDir) {
1992 if (is_dir($tempDir)) {
1993 CRM_Utils_File::cleanDir($tempDir, TRUE, FALSE);
1994 }
1995 }
1996 }
1997
1998 /**
eceb18cc 1999 * Temporarily replace the singleton extension with a different one.
1e1fdcf6 2000 * @param \CRM_Extension_System $system
6a488035 2001 */
00be9182 2002 public function setExtensionSystem(CRM_Extension_System $system) {
6a488035
TO
2003 if ($this->origExtensionSystem == NULL) {
2004 $this->origExtensionSystem = CRM_Extension_System::singleton();
2005 }
2006 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2007 }
2008
00be9182 2009 public function unsetExtensionSystem() {
6a488035
TO
2010 if ($this->origExtensionSystem !== NULL) {
2011 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2012 $this->origExtensionSystem = NULL;
2013 }
2014 }
f17d75bb 2015
076d8c82
TO
2016 /**
2017 * Temporarily alter the settings-metadata to add a mock setting.
2018 *
2019 * WARNING: The setting metadata will disappear on the next cache-clear.
2020 *
2021 * @param $extras
2022 * @return void
2023 */
00be9182 2024 public function setMockSettingsMetaData($extras) {
5896d037
TO
2025 CRM_Utils_Hook::singleton()
2026 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2027 $metadata = array_merge($metadata, $extras);
2028 });
076d8c82 2029
1209c8a7
CW
2030 Civi::service('settings_manager')->flush();
2031
076d8c82
TO
2032 $fields = $this->callAPISuccess('setting', 'getfields', array());
2033 foreach ($extras as $key => $spec) {
2034 $this->assertNotEmpty($spec['title']);
2035 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2036 }
2037 }
2038
4cbe18b8 2039 /**
100fef9d 2040 * @param string $name
4cbe18b8 2041 */
00be9182 2042 public function financialAccountDelete($name) {
f17d75bb
PN
2043 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2044 $financialAccount->name = $name;
5896d037 2045 if ($financialAccount->find(TRUE)) {
f17d75bb
PN
2046 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2047 $entityFinancialType->financial_account_id = $financialAccount->id;
2048 $entityFinancialType->delete();
2049 $financialAccount->delete();
2050 }
2051 }
fb32de45 2052
2b7d3f8a 2053 /**
2054 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2055 * (NB unclear if this is still required)
2056 */
00be9182 2057 public function _sethtmlGlobals() {
2b7d3f8a 2058 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2059 'required' => array(
2060 'html_quickform_rule_required',
21dfd5f5 2061 'HTML/QuickForm/Rule/Required.php',
2b7d3f8a 2062 ),
2063 'maxlength' => array(
2064 'html_quickform_rule_range',
21dfd5f5 2065 'HTML/QuickForm/Rule/Range.php',
2b7d3f8a 2066 ),
2067 'minlength' => array(
2068 'html_quickform_rule_range',
21dfd5f5 2069 'HTML/QuickForm/Rule/Range.php',
2b7d3f8a 2070 ),
2071 'rangelength' => array(
2072 'html_quickform_rule_range',
21dfd5f5 2073 'HTML/QuickForm/Rule/Range.php',
2b7d3f8a 2074 ),
2075 'email' => array(
2076 'html_quickform_rule_email',
21dfd5f5 2077 'HTML/QuickForm/Rule/Email.php',
2b7d3f8a 2078 ),
2079 'regex' => array(
2080 'html_quickform_rule_regex',
21dfd5f5 2081 'HTML/QuickForm/Rule/Regex.php',
2b7d3f8a 2082 ),
2083 'lettersonly' => array(
2084 'html_quickform_rule_regex',
21dfd5f5 2085 'HTML/QuickForm/Rule/Regex.php',
2b7d3f8a 2086 ),
2087 'alphanumeric' => array(
2088 'html_quickform_rule_regex',
21dfd5f5 2089 'HTML/QuickForm/Rule/Regex.php',
2b7d3f8a 2090 ),
2091 'numeric' => array(
2092 'html_quickform_rule_regex',
21dfd5f5 2093 'HTML/QuickForm/Rule/Regex.php',
2b7d3f8a 2094 ),
2095 'nopunctuation' => array(
2096 'html_quickform_rule_regex',
21dfd5f5 2097 'HTML/QuickForm/Rule/Regex.php',
2b7d3f8a 2098 ),
2099 'nonzero' => array(
2100 'html_quickform_rule_regex',
21dfd5f5 2101 'HTML/QuickForm/Rule/Regex.php',
2b7d3f8a 2102 ),
2103 'callback' => array(
2104 'html_quickform_rule_callback',
21dfd5f5 2105 'HTML/QuickForm/Rule/Callback.php',
2b7d3f8a 2106 ),
2107 'compare' => array(
2108 'html_quickform_rule_compare',
21dfd5f5
TO
2109 'HTML/QuickForm/Rule/Compare.php',
2110 ),
2b7d3f8a 2111 );
2112 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2113 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2114 'group' => array(
2115 'HTML/QuickForm/group.php',
21dfd5f5 2116 'HTML_QuickForm_group',
2b7d3f8a 2117 ),
2118 'hidden' => array(
2119 'HTML/QuickForm/hidden.php',
21dfd5f5 2120 'HTML_QuickForm_hidden',
2b7d3f8a 2121 ),
2122 'reset' => array(
2123 'HTML/QuickForm/reset.php',
21dfd5f5 2124 'HTML_QuickForm_reset',
2b7d3f8a 2125 ),
2126 'checkbox' => array(
2127 'HTML/QuickForm/checkbox.php',
21dfd5f5 2128 'HTML_QuickForm_checkbox',
2b7d3f8a 2129 ),
2130 'file' => array(
2131 'HTML/QuickForm/file.php',
21dfd5f5 2132 'HTML_QuickForm_file',
2b7d3f8a 2133 ),
2134 'image' => array(
2135 'HTML/QuickForm/image.php',
21dfd5f5 2136 'HTML_QuickForm_image',
2b7d3f8a 2137 ),
2138 'password' => array(
2139 'HTML/QuickForm/password.php',
21dfd5f5 2140 'HTML_QuickForm_password',
2b7d3f8a 2141 ),
2142 'radio' => array(
2143 'HTML/QuickForm/radio.php',
21dfd5f5 2144 'HTML_QuickForm_radio',
2b7d3f8a 2145 ),
2146 'button' => array(
2147 'HTML/QuickForm/button.php',
21dfd5f5 2148 'HTML_QuickForm_button',
2b7d3f8a 2149 ),
2150 'submit' => array(
2151 'HTML/QuickForm/submit.php',
21dfd5f5 2152 'HTML_QuickForm_submit',
2b7d3f8a 2153 ),
2154 'select' => array(
2155 'HTML/QuickForm/select.php',
21dfd5f5 2156 'HTML_QuickForm_select',
2b7d3f8a 2157 ),
2158 'hiddenselect' => array(
2159 'HTML/QuickForm/hiddenselect.php',
21dfd5f5 2160 'HTML_QuickForm_hiddenselect',
2b7d3f8a 2161 ),
2162 'text' => array(
2163 'HTML/QuickForm/text.php',
21dfd5f5 2164 'HTML_QuickForm_text',
2b7d3f8a 2165 ),
2166 'textarea' => array(
2167 'HTML/QuickForm/textarea.php',
21dfd5f5 2168 'HTML_QuickForm_textarea',
2b7d3f8a 2169 ),
2170 'fckeditor' => array(
2171 'HTML/QuickForm/fckeditor.php',
21dfd5f5 2172 'HTML_QuickForm_FCKEditor',
2b7d3f8a 2173 ),
2174 'tinymce' => array(
2175 'HTML/QuickForm/tinymce.php',
21dfd5f5 2176 'HTML_QuickForm_TinyMCE',
2b7d3f8a 2177 ),
2178 'dojoeditor' => array(
2179 'HTML/QuickForm/dojoeditor.php',
21dfd5f5 2180 'HTML_QuickForm_dojoeditor',
2b7d3f8a 2181 ),
2182 'link' => array(
2183 'HTML/QuickForm/link.php',
21dfd5f5 2184 'HTML_QuickForm_link',
2b7d3f8a 2185 ),
2186 'advcheckbox' => array(
2187 'HTML/QuickForm/advcheckbox.php',
21dfd5f5 2188 'HTML_QuickForm_advcheckbox',
2b7d3f8a 2189 ),
2190 'date' => array(
2191 'HTML/QuickForm/date.php',
21dfd5f5 2192 'HTML_QuickForm_date',
2b7d3f8a 2193 ),
2194 'static' => array(
2195 'HTML/QuickForm/static.php',
21dfd5f5 2196 'HTML_QuickForm_static',
2b7d3f8a 2197 ),
2198 'header' => array(
2199 'HTML/QuickForm/header.php',
21dfd5f5 2200 'HTML_QuickForm_header',
2b7d3f8a 2201 ),
2202 'html' => array(
2203 'HTML/QuickForm/html.php',
21dfd5f5 2204 'HTML_QuickForm_html',
2b7d3f8a 2205 ),
2206 'hierselect' => array(
2207 'HTML/QuickForm/hierselect.php',
21dfd5f5 2208 'HTML_QuickForm_hierselect',
2b7d3f8a 2209 ),
2210 'autocomplete' => array(
2211 'HTML/QuickForm/autocomplete.php',
21dfd5f5 2212 'HTML_QuickForm_autocomplete',
2b7d3f8a 2213 ),
2214 'xbutton' => array(
2215 'HTML/QuickForm/xbutton.php',
21dfd5f5 2216 'HTML_QuickForm_xbutton',
2b7d3f8a 2217 ),
2218 'advmultiselect' => array(
2219 'HTML/QuickForm/advmultiselect.php',
21dfd5f5
TO
2220 'HTML_QuickForm_advmultiselect',
2221 ),
2b7d3f8a 2222 );
2223 }
2224
48e399ac
EM
2225 /**
2226 * Set up an acl allowing contact to see 2 specified groups
c206647d 2227 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
48e399ac 2228 *
c206647d 2229 * You need to have pre-created these groups & created the user e.g
48e399ac
EM
2230 * $this->createLoggedInUser();
2231 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2232 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
ea3ddccf 2233 *
2234 * @param bool $isProfile
48e399ac 2235 */
181f536c 2236 public function setupACL($isProfile = FALSE) {
aaac0e0b
EM
2237 global $_REQUEST;
2238 $_REQUEST = $this->_params;
108ff21a 2239
48e399ac
EM
2240 CRM_Core_Config::singleton()->userPermissionClass->permissions = array('access CiviCRM');
2241 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
e5720c45
SL
2242 $ov = new CRM_Core_DAO_OptionValue();
2243 $ov->option_group_id = $optionGroupID;
2244 $ov->value = 55;
2245 if ($ov->find(TRUE)) {
2246 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2247 }
6c6e6187 2248 $optionValue = $this->callAPISuccess('option_value', 'create', array(
5896d037 2249 'option_group_id' => $optionGroupID,
48e399ac
EM
2250 'label' => 'pick me',
2251 'value' => 55,
2252 ));
2253
48e399ac
EM
2254 CRM_Core_DAO::executeQuery("
2255 TRUNCATE civicrm_acl_cache
2256 ");
2257
2258 CRM_Core_DAO::executeQuery("
2259 TRUNCATE civicrm_acl_contact_cache
2260 ");
2261
48e399ac
EM
2262 CRM_Core_DAO::executeQuery("
2263 INSERT INTO civicrm_acl_entity_role (
181f536c 2264 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2265 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
48e399ac
EM
2266 ");
2267
181f536c 2268 if ($isProfile) {
2269 CRM_Core_DAO::executeQuery("
2270 INSERT INTO civicrm_acl (
2271 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2272 )
2273 VALUES (
2274 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2275 );
2276 ");
2277 }
2278 else {
2279 CRM_Core_DAO::executeQuery("
2280 INSERT INTO civicrm_acl (
2281 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2282 )
2283 VALUES (
2284 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2285 );
2286 ");
2287
2288 CRM_Core_DAO::executeQuery("
2289 INSERT INTO civicrm_acl (
2290 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2291 )
2292 VALUES (
2293 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2294 );
2295 ");
181f536c 2296 }
48e399ac 2297
48e399ac
EM
2298 $this->_loggedInUser = CRM_Core_Session::singleton()->get('userID');
2299 $this->callAPISuccess('group_contact', 'create', array(
2300 'group_id' => $this->_permissionedGroup,
2301 'contact_id' => $this->_loggedInUser,
2302 ));
08a2ea5e 2303
2304 if (!$isProfile) {
2305 //flush cache
2306 CRM_ACL_BAO_Cache::resetCache();
340c24cc 2307 CRM_ACL_API::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
08a2ea5e 2308 }
48e399ac
EM
2309 }
2310
cab024d4 2311 /**
100fef9d 2312 * Alter default price set so that the field numbers are not all 1 (hiding errors)
cab024d4 2313 */
00be9182 2314 public function offsetDefaultPriceSet() {
cab024d4
EM
2315 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2316 $firstID = $contributionPriceSet['id'];
5896d037 2317 $this->callAPISuccess('price_set', 'create', array(
92915c55
TO
2318 'id' => $contributionPriceSet['id'],
2319 'is_active' => 0,
2320 'name' => 'old',
2321 ));
cab024d4
EM
2322 unset($contributionPriceSet['id']);
2323 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
5896d037 2324 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
92915c55
TO
2325 'price_set_id' => $firstID,
2326 'options' => array('limit' => 1),
2327 ));
cab024d4
EM
2328 unset($priceField['id']);
2329 $priceField['price_set_id'] = $newPriceSet['id'];
2330 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
5896d037 2331 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
92915c55
TO
2332 'price_set_id' => $firstID,
2333 'sequential' => 1,
2334 'options' => array('limit' => 1),
2335 ));
cab024d4
EM
2336
2337 unset($priceFieldValue['id']);
2338 //create some padding to use up ids
2339 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2340 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2341 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
cab024d4
EM
2342 }
2343
4aef704e 2344 /**
eceb18cc 2345 * Create an instance of the paypal processor.
4aef704e 2346 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2347 * this parent class & we don't have a structure for that yet
2348 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
e4f46be0 2349 * & the best protection against that is the functions this class affords
1e1fdcf6 2350 * @param array $params
79d7553f 2351 * @return int $result['id'] payment processor id
4aef704e 2352 */
00be9182 2353 public function paymentProcessorCreate($params = array()) {
4aef704e 2354 $params = array_merge(array(
39b959db
SL
2355 'name' => 'demo',
2356 'domain_id' => CRM_Core_Config::domainID(),
2357 'payment_processor_type_id' => 'PayPal',
2358 'is_active' => 1,
2359 'is_default' => 0,
2360 'is_test' => 1,
2361 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2362 'password' => '1183377788',
2363 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2364 'url_site' => 'https://www.sandbox.paypal.com/',
2365 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2366 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2367 'class_name' => 'Payment_PayPalImpl',
2368 'billing_mode' => 3,
2369 'financial_type_id' => 1,
2370 'financial_account_id' => 12,
2371 // Credit card = 1 so can pass 'by accident'.
2372 'payment_instrument_id' => 'Debit Card',
2373 ), $params);
5896d037 2374 if (!is_numeric($params['payment_processor_type_id'])) {
4aef704e 2375 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2376 //here
2377 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2378 'name' => $params['payment_processor_type_id'],
2379 'return' => 'id',
2380 ), 'integer');
2381 }
2382 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2383 return $result['id'];
2384 }
a9ac877b 2385
0dbefed3 2386 /**
eceb18cc 2387 * Set up initial recurring payment allowing subsequent IPN payments.
9f68fe61
MW
2388 *
2389 * @param array $recurParams (Optional)
2390 * @param array $contributionParams (Optional)
0dbefed3 2391 */
9f68fe61
MW
2392 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2393 $contributionParams = array_merge([
39b959db
SL
2394 'total_amount' => '200',
2395 'invoice_id' => $this->_invoiceID,
2396 'financial_type_id' => 'Donation',
2397 'contribution_status_id' => 'Pending',
2398 'contact_id' => $this->_contactID,
2399 'contribution_page_id' => $this->_contributionPageID,
2400 'payment_processor_id' => $this->_paymentProcessorID,
2401 'is_test' => 0,
f03241be 2402 'receive_date' => '2019-07-25 07:34:23',
39b959db
SL
2403 'skipCleanMoney' => TRUE,
2404 ], $contributionParams);
b6b59c64 2405 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
0dbefed3
EM
2406 'contact_id' => $this->_contactID,
2407 'amount' => 1000,
2408 'sequential' => 1,
2409 'installments' => 5,
2410 'frequency_unit' => 'Month',
2411 'frequency_interval' => 1,
2412 'invoice_id' => $this->_invoiceID,
2413 'contribution_status_id' => 2,
481312d9 2414 'payment_processor_id' => $this->_paymentProcessorID,
2415 // processor provided ID - use contact ID as proxy.
2416 'processor_id' => $this->_contactID,
9f68fe61
MW
2417 'api.contribution.create' => $contributionParams,
2418 ), $recurParams));
0dbefed3
EM
2419 $this->_contributionRecurID = $contributionRecur['id'];
2420 $this->_contributionID = $contributionRecur['values']['0']['api.contribution.create']['id'];
2421 }
a86d27fc 2422
a9ac877b 2423 /**
100fef9d 2424 * 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
b3c283b4
MW
2425 *
2426 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
a9ac877b 2427 */
b3c283b4
MW
2428 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2429 $membershipParams = $recurParams = array();
2430 if (!empty($params['duration_unit'])) {
2431 $membershipParams['duration_unit'] = $params['duration_unit'];
2432 }
2433 if (!empty($params['frequency_unit'])) {
2434 $recurParams['frequency_unit'] = $params['frequency_unit'];
2435 }
2436
2437 $this->ids['membership_type'] = $this->membershipTypeCreate($membershipParams);
69140e67 2438 //create a contribution so our membership & contribution don't both have id = 1
b6b59c64 2439 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2440 $this->contributionCreate(array(
2441 'contact_id' => $this->_contactID,
2442 'is_test' => 1,
2443 'financial_type_id' => 1,
2444 'invoice_id' => 'abcd',
2445 'trxn_id' => 345,
f03241be 2446 'receive_date' => '2019-07-25 07:34:23',
b6b59c64 2447 ));
2448 }
b3c283b4 2449 $this->setupRecurringPaymentProcessorTransaction($recurParams);
69140e67 2450
a9ac877b
EM
2451 $this->ids['membership'] = $this->callAPISuccess('membership', 'create', array(
2452 'contact_id' => $this->_contactID,
2453 'membership_type_id' => $this->ids['membership_type'],
2454 'contribution_recur_id' => $this->_contributionRecurID,
a9ac877b 2455 'format.only_id' => TRUE,
f03241be 2456 'source' => 'Payment',
a9ac877b 2457 ));
69140e67
EM
2458 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2459 CRM_Core_DAO::executeQuery("TRUNCATE civicrm_line_item");
2460
2461 $this->callAPISuccess('line_item', 'create', array(
2462 'entity_table' => 'civicrm_membership',
2463 'entity_id' => $this->ids['membership'],
2464 'contribution_id' => $this->_contributionID,
2465 'label' => 'General',
2466 'qty' => 1,
2467 'unit_price' => 200,
2468 'line_total' => 200,
2469 'financial_type_id' => 1,
5896d037 2470 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
92915c55
TO
2471 'return' => 'id',
2472 'label' => 'Membership Amount',
b6b59c64 2473 'options' => array('limit' => 1, 'sort' => 'id DESC'),
92915c55 2474 )),
5896d037 2475 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
92915c55
TO
2476 'return' => 'id',
2477 'label' => 'General',
b6b59c64 2478 'options' => array('limit' => 1, 'sort' => 'id DESC'),
92915c55 2479 )),
69140e67 2480 ));
5896d037 2481 $this->callAPISuccess('membership_payment', 'create', array(
92915c55
TO
2482 'contribution_id' => $this->_contributionID,
2483 'membership_id' => $this->ids['membership'],
2484 ));
a9ac877b 2485 }
6a488035 2486
4cbe18b8
EM
2487 /**
2488 * @param $message
2489 *
2490 * @throws Exception
a9ac877b 2491 */
00be9182 2492 public function CiviUnitTestCase_fatalErrorHandler($message) {
a9ac877b
EM
2493 throw new Exception("{$message['message']}: {$message['code']}");
2494 }
4aef704e 2495
d67f1f28 2496 /**
eceb18cc 2497 * Wrap the entire test case in a transaction.
d67f1f28
TO
2498 *
2499 * Only subsequent DB statements will be wrapped in TX -- this cannot
2500 * retroactively wrap old DB statements. Therefore, it makes sense to
2501 * call this at the beginning of setUp().
2502 *
2503 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2504 * this option does not work with, e.g., custom-data.
2505 *
2506 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2507 * if TRUNCATE or ALTER is called while using a transaction.
2508 *
e16033b4
TO
2509 * @param bool $nest
2510 * Whether to use nesting or reference-counting.
d67f1f28 2511 */
00be9182 2512 public function useTransaction($nest = TRUE) {
d67f1f28
TO
2513 if (!$this->tx) {
2514 $this->tx = new CRM_Core_Transaction($nest);
2515 $this->tx->rollback();
2516 }
2517 }
a335f6b2 2518
b3c30fda 2519 /**
54957108 2520 * Assert the attachment exists.
2521 *
2522 * @param bool $exists
b3c30fda
CW
2523 * @param array $apiResult
2524 */
2525 protected function assertAttachmentExistence($exists, $apiResult) {
2526 $fileId = $apiResult['id'];
2527 $this->assertTrue(is_numeric($fileId));
2528 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2529 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2530 1 => array($fileId, 'Int'),
2531 ));
2532 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2533 1 => array($fileId, 'Int'),
2534 ));
2535 }
2536
299c1530 2537 /**
2538 * Assert 2 sql strings are the same, ignoring double spaces.
2539 *
2540 * @param string $expectedSQL
2541 * @param string $actualSQL
2542 * @param string $message
2543 */
2544 protected function assertLike($expectedSQL, $actualSQL, $message = 'different sql') {
2545 $expected = trim((preg_replace('/[ \r\n\t]+/', ' ', $expectedSQL)));
2546 $actual = trim((preg_replace('/[ \r\n\t]+/', ' ', $actualSQL)));
2547 $this->assertEquals($expected, $actual, $message);
2548 }
2549
c039f658 2550 /**
2551 * Create a price set for an event.
2552 *
2553 * @param int $feeTotal
601c7a24 2554 * @param int $minAmt
f660d2ad 2555 * @param string $type
c039f658 2556 *
2557 * @return int
2558 * Price Set ID.
74531938 2559 * @throws \CRM_Core_Exception
c039f658 2560 */
f660d2ad 2561 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
c039f658 2562 // creating price set, price field
2563 $paramsSet['title'] = 'Price Set';
2564 $paramsSet['name'] = CRM_Utils_String::titleToVar('Price Set');
2565 $paramsSet['is_active'] = FALSE;
2566 $paramsSet['extends'] = 1;
601c7a24 2567 $paramsSet['min_amount'] = $minAmt;
c039f658 2568
f660d2ad 2569 $priceSet = CRM_Price_BAO_PriceSet::create($paramsSet);
2570 $this->_ids['price_set'] = $priceSet->id;
c039f658 2571
c039f658 2572 $paramsField = array(
2573 'label' => 'Price Field',
2574 'name' => CRM_Utils_String::titleToVar('Price Field'),
f660d2ad 2575 'html_type' => $type,
c039f658 2576 'price' => $feeTotal,
2577 'option_label' => array('1' => 'Price Field'),
2578 'option_value' => array('1' => $feeTotal),
2579 'option_name' => array('1' => $feeTotal),
2580 'option_weight' => array('1' => 1),
2581 'option_amount' => array('1' => 1),
2582 'is_display_amounts' => 1,
2583 'weight' => 1,
2584 'options_per_line' => 1,
2585 'is_active' => array('1' => 1),
f660d2ad 2586 'price_set_id' => $this->_ids['price_set'],
c039f658 2587 'is_enter_qty' => 1,
8484a5f0 2588 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
c039f658 2589 );
f660d2ad 2590 if ($type === 'Radio') {
2591 $paramsField['is_enter_qty'] = 0;
2592 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2593 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2594 }
74531938 2595 $this->callAPISuccess('PriceField', 'create', $paramsField);
f660d2ad 2596 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids['price_set']));
2597 $this->_ids['price_field'] = array_keys($fields['values']);
2598 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids['price_field'][0]));
2599 $this->_ids['price_field_value'] = array_keys($fieldValues['values']);
c039f658 2600
f660d2ad 2601 return $this->_ids['price_set'];
c039f658 2602 }
2603
481312d9 2604 /**
2605 * Add a profile to a contribution page.
2606 *
2607 * @param string $name
2608 * @param int $contributionPageID
5d6cf648 2609 * @param string $module
481312d9 2610 */
5d6cf648
JM
2611 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2612 $params = [
481312d9 2613 'uf_group_id' => $name,
5d6cf648 2614 'module' => $module,
481312d9 2615 'entity_table' => 'civicrm_contribution_page',
2616 'entity_id' => $contributionPageID,
2617 'weight' => 1,
5d6cf648
JM
2618 ];
2619 if ($module !== 'CiviContribute') {
2620 $params['module_data'] = [$module => []];
2621 }
2622 $this->callAPISuccess('UFJoin', 'create', $params);
481312d9 2623 }
2624
db62fd2b
PN
2625 /**
2626 * Add participant with contribution
2627 *
2628 * @return array
2629 */
2630 protected function createParticipantWithContribution() {
2631 // creating price set, price field
a630a84e 2632 $this->_contactId = $this->individualCreate();
2633 $event = $this->eventCreate();
2634 $this->_eventId = $event['id'];
db62fd2b
PN
2635 $eventParams = array(
2636 'id' => $this->_eventId,
2637 'financial_type_id' => 4,
2638 'is_monetary' => 1,
2639 );
2640 $this->callAPISuccess('event', 'create', $eventParams);
73c0e107 2641 $priceFields = $this->createPriceSet('event', $this->_eventId);
db62fd2b
PN
2642 $participantParams = array(
2643 'financial_type_id' => 4,
2644 'event_id' => $this->_eventId,
2645 'role_id' => 1,
2646 'status_id' => 14,
2647 'fee_currency' => 'USD',
2648 'contact_id' => $this->_contactId,
2649 );
2650 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
2651 $contributionParams = array(
2652 'total_amount' => 150,
2653 'currency' => 'USD',
2654 'contact_id' => $this->_contactId,
2655 'financial_type_id' => 4,
2656 'contribution_status_id' => 1,
2657 'partial_payment_total' => 300.00,
f49cdeab 2658 'partial_amount_to_pay' => 150,
db62fd2b
PN
2659 'contribution_mode' => 'participant',
2660 'participant_id' => $participant['id'],
2661 );
2662 foreach ($priceFields['values'] as $key => $priceField) {
2663 $lineItems[1][$key] = array(
2664 'price_field_id' => $priceField['price_field_id'],
2665 'price_field_value_id' => $priceField['id'],
2666 'label' => $priceField['label'],
2667 'field_title' => $priceField['label'],
2668 'qty' => 1,
2669 'unit_price' => $priceField['amount'],
2670 'line_total' => $priceField['amount'],
2671 'financial_type_id' => $priceField['financial_type_id'],
2672 );
2673 }
2674 $contributionParams['line_item'] = $lineItems;
2675 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
2676 $paymentParticipant = array(
2677 'participant_id' => $participant['id'],
2678 'contribution_id' => $contribution['id'],
2679 );
db62fd2b
PN
2680 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
2681 return array($lineItems, $contribution);
2682 }
2683
73c0e107
PN
2684 /**
2685 * Create price set
2686 *
2687 * @param string $component
2688 * @param int $componentId
39b959db 2689 * @param array $priceFieldOptions
73c0e107
PN
2690 *
2691 * @return array
2692 */
c91b1cc3 2693 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
5c3d600f
PN
2694 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2695 $paramsSet['name'] = CRM_Utils_String::titleToVar($paramsSet['title']);
73c0e107 2696 $paramsSet['is_active'] = TRUE;
faba82fc 2697 $paramsSet['financial_type_id'] = 'Event Fee';
73c0e107
PN
2698 $paramsSet['extends'] = 1;
2699 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2700 $priceSetId = $priceSet['id'];
2701 //Checking for priceset added in the table.
2702 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
2703 'id', $paramsSet['title'], 'Check DB for created priceset'
2704 );
c91b1cc3 2705 $paramsField = array_merge(array(
73c0e107
PN
2706 'label' => 'Price Field',
2707 'name' => CRM_Utils_String::titleToVar('Price Field'),
2708 'html_type' => 'CheckBox',
2709 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2710 'option_value' => array('1' => 100, '2' => 200),
2711 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2712 'option_weight' => array('1' => 1, '2' => 2),
2713 'option_amount' => array('1' => 100, '2' => 200),
2714 'is_display_amounts' => 1,
2715 'weight' => 1,
2716 'options_per_line' => 1,
2717 'is_active' => array('1' => 1, '2' => 1),
2718 'price_set_id' => $priceSet['id'],
2719 'is_enter_qty' => 1,
8484a5f0 2720 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
c91b1cc3
E
2721 ), $priceFieldOptions);
2722
73c0e107
PN
2723 $priceField = CRM_Price_BAO_PriceField::create($paramsField);
2724 if ($componentId) {
2725 CRM_Price_BAO_PriceSet::addTo('civicrm_' . $component, $componentId, $priceSetId);
2726 }
2727 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id));
2728 }
2729
b80f2ad1
E
2730 /**
2731 * Replace the template with a test-oriented template designed to show all the variables.
2732 *
2733 * @param string $templateName
7a2ee417 2734 * @param string $type
b80f2ad1 2735 */
7a2ee417 2736 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt', $type = 'html') {
2737 $testTemplate = file_get_contents(__DIR__ . '/../../templates/message_templates/' . $templateName . '_' . $type . '.tpl');
b80f2ad1
E
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
7a2ee417 2742 SET m.msg_{$type} = %1
2743 WHERE og.name LIKE 'msg_tpl_workflow_%'
b80f2ad1 2744 AND ov.name = '{$templateName}'
7a2ee417 2745 AND m.is_default = 1", [1 => [$testTemplate, 'String']]
b80f2ad1
E
2746 );
2747 }
2748
2749 /**
2750 * Reinstate the default template.
2751 *
2752 * @param string $templateName
7a2ee417 2753 * @param string $type
b80f2ad1 2754 */
7a2ee417 2755 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt', $type = 'html') {
b80f2ad1
E
2756 CRM_Core_DAO::executeQuery(
2757 "UPDATE civicrm_option_group og
2758 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2759 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2760 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
7a2ee417 2761 SET m.msg_{$type} = m2.msg_{$type}
b80f2ad1
E
2762 WHERE og.name = 'msg_tpl_workflow_contribution'
2763 AND ov.name = '{$templateName}'
2764 AND m.is_default = 1"
2765 );
2766 }
2767
8d35246a
EM
2768 /**
2769 * Flush statics relating to financial type.
2770 */
2771 protected function flushFinancialTypeStatics() {
2772 if (isset(\Civi::$statics['CRM_Financial_BAO_FinancialType'])) {
2773 unset(\Civi::$statics['CRM_Financial_BAO_FinancialType']);
2774 }
4954339a
EM
2775 if (isset(\Civi::$statics['CRM_Contribute_PseudoConstant'])) {
2776 unset(\Civi::$statics['CRM_Contribute_PseudoConstant']);
2777 }
8d35246a 2778 CRM_Contribute_PseudoConstant::flush('financialType');
4954339a
EM
2779 CRM_Contribute_PseudoConstant::flush('membershipType');
2780 // Pseudoconstants may be saved to the cache table.
2781 CRM_Core_DAO::executeQuery("TRUNCATE civicrm_cache");
2782 CRM_Financial_BAO_FinancialType::$_statusACLFt = array();
8d35246a
EM
2783 CRM_Financial_BAO_FinancialType::$_availableFinancialTypes = NULL;
2784 }
2785
2786 /**
2787 * Set the permissions to the supplied array.
2788 *
2789 * @param array $permissions
2790 */
2791 protected function setPermissions($permissions) {
2792 CRM_Core_Config::singleton()->userPermissionClass->permissions = $permissions;
2793 $this->flushFinancialTypeStatics();
2794 }
2795
bf722049 2796 /**
2797 * @param array $params
2798 * @param $context
2799 */
2800 public function _checkFinancialRecords($params, $context) {
2801 $entityParams = array(
2802 'entity_id' => $params['id'],
2803 'entity_table' => 'civicrm_contribution',
2804 );
2805 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
2806 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2807 if ($context == 'pending') {
2808 $trxn = CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams);
2809 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2810 return;
2811 }
2812 $trxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
2813 $trxnParams = array(
2814 'id' => $trxn['financial_trxn_id'],
2815 );
2816 if ($context != 'online' && $context != 'payLater') {
2817 $compareParams = array(
2818 'to_financial_account_id' => 6,
2819 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
2820 'status_id' => 1,
2821 );
2822 }
2823 if ($context == 'feeAmount') {
2824 $compareParams['fee_amount'] = 50;
2825 }
2826 elseif ($context == 'online') {
2827 $compareParams = array(
2828 'to_financial_account_id' => 12,
2829 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
2830 'status_id' => 1,
f69a9ac3 2831 'payment_instrument_id' => CRM_Utils_Array::value('payment_instrument_id', $params, 1),
bf722049 2832 );
2833 }
2834 elseif ($context == 'payLater') {
2835 $compareParams = array(
2836 'to_financial_account_id' => 7,
2837 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
2838 'status_id' => 2,
2839 );
2840 }
2841 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2842 $entityParams = array(
2843 'financial_trxn_id' => $trxn['financial_trxn_id'],
2844 'entity_table' => 'civicrm_financial_item',
2845 );
2846 $entityTrxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
2847 $fitemParams = array(
2848 'id' => $entityTrxn['entity_id'],
2849 );
2850 $compareParams = array(
2851 'amount' => CRM_Utils_Array::value('total_amount', $params, 100),
2852 'status_id' => 1,
1a1a2f4f 2853 'financial_account_id' => CRM_Utils_Array::value('financial_account_id', $params, 1),
bf722049 2854 );
2855 if ($context == 'payLater') {
2856 $compareParams = array(
2857 'amount' => CRM_Utils_Array::value('total_amount', $params, 100),
2858 'status_id' => 3,
1a1a2f4f 2859 'financial_account_id' => CRM_Utils_Array::value('financial_account_id', $params, 1),
bf722049 2860 );
2861 }
2862 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2863 if ($context == 'feeAmount') {
2864 $maxParams = array(
2865 'entity_id' => $params['id'],
2866 'entity_table' => 'civicrm_contribution',
2867 );
2868 $maxTrxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($maxParams, TRUE));
2869 $trxnParams = array(
2870 'id' => $maxTrxn['financial_trxn_id'],
2871 );
2872 $compareParams = array(
2873 'to_financial_account_id' => 5,
2874 'from_financial_account_id' => 6,
2875 'total_amount' => 50,
2876 'status_id' => 1,
2877 );
2878 $trxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['id'], 'DESC');
2879 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2880 $fitemParams = array(
2881 'entity_id' => $trxnId['financialTrxnId'],
2882 'entity_table' => 'civicrm_financial_trxn',
2883 );
2884 $compareParams = array(
2885 'amount' => 50,
2886 'status_id' => 1,
2887 'financial_account_id' => 5,
2888 );
2889 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2890 }
2891 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2892 // line should be copied into all the functions that call this function & evaluated there
2893 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2894 // when calling completeTransaction or repeatTransaction.
2895 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
2896 }
2897
8484a5f0 2898 /**
2899 * Return financial type id on basis of name
2900 *
2901 * @param string $name Financial type m/c name
2902 *
2903 * @return int
2904 */
2905 public function getFinancialTypeId($name) {
2906 return CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2907 }
2908
204beda3 2909 /**
2910 * Cleanup function for contents of $this->ids.
2911 *
2912 * This is a best effort cleanup to use in tear downs etc.
2913 *
2914 * It will not fail if the data has already been removed (some tests may do
2915 * their own cleanup).
2916 */
2917 protected function cleanUpSetUpIDs() {
2918 foreach ($this->setupIDs as $entity => $id) {
2919 try {
2920 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
2921 }
2922 catch (CiviCRM_API3_Exception $e) {
2923 // This is a best-effort cleanup function, ignore.
2924 }
2925 }
2926 }
2927
adbc354b
PN
2928 /**
2929 * Create Financial Type.
2930 *
2931 * @param array $params
2932 *
2933 * @return array
2934 */
2935 protected function createFinancialType($params = array()) {
2936 $params = array_merge($params,
2937 array(
2938 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2939 'is_active' => 1,
2940 )
2941 );
2942 return $this->callAPISuccess('FinancialType', 'create', $params);
2943 }
2944
e1c5a855 2945 /**
2946 * Create Payment Instrument.
2947 *
2948 * @param array $params
2949 * @param string $financialAccountName
2950 *
2951 * @return int
2952 */
2953 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
2954 $params = array_merge(array(
2955 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2956 'option_group_id' => 'payment_instrument',
2957 'is_active' => 1,
39b959db 2958 ), $params);
897ff8c5 2959 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
e1c5a855 2960
2961 $relationTypeID = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2962
2963 $financialAccountParams = [
2964 'entity_table' => 'civicrm_option_value',
897ff8c5 2965 'entity_id' => $newPaymentInstrument,
e1c5a855 2966 'account_relationship' => $relationTypeID,
2967 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2968 ];
2969 CRM_Financial_BAO_FinancialTypeAccount::add($financialAccountParams);
2970
2971 return CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2972 }
2973
ec5da26a 2974 /**
2975 * Enable Tax and Invoicing
2976 */
2977 protected function enableTaxAndInvoicing($params = array()) {
2978 // Enable component contribute setting
2979 $contributeSetting = array_merge($params,
2980 array(
2981 'invoicing' => 1,
2982 'invoice_prefix' => 'INV_',
2983 'credit_notes_prefix' => 'CN_',
2984 'due_date' => 10,
2985 'due_date_period' => 'days',
2986 'notes' => '',
2987 'is_email_pdf' => 1,
2988 'tax_term' => 'Sales Tax',
2989 'tax_display_settings' => 'Inclusive',
2990 )
2991 );
2992 return Civi::settings()->set('contribution_invoice_settings', $contributeSetting);
2993 }
2994
9fbf312f 2995 /**
2996 * Enable Tax and Invoicing
2997 */
2998 protected function disableTaxAndInvoicing($params = array()) {
f436577a 2999 if (!empty(\Civi::$statics['CRM_Core_PseudoConstant']) && isset(\Civi::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
3000 unset(\Civi::$statics['CRM_Core_PseudoConstant']['taxRates']);
3001 }
9fbf312f 3002 // Enable component contribute setting
3003 $contributeSetting = array_merge($params,
3004 array(
3005 'invoicing' => 0,
3006 )
3007 );
3008 return Civi::settings()->set('contribution_invoice_settings', $contributeSetting);
3009 }
3010
7a1f3919
PN
3011 /**
3012 * Add Sales Tax relation for financial type with financial account.
3013 *
3014 * @param int $financialTypeId
3015 *
3016 * @return obj
3017 */
3018 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3019 $params = array(
3020 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3021 'financial_account_type_id' => key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3022 'is_deductible' => 1,
3023 'is_tax' => 1,
3024 'tax_rate' => 10,
3025 'is_active' => 1,
3026 );
3027 $account = CRM_Financial_BAO_FinancialAccount::add($params);
3028 $entityParams = array(
3029 'entity_table' => 'civicrm_financial_type',
7a1f3919 3030 'entity_id' => $financialTypeId,
5b3543ce 3031 'account_relationship' => key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
7a1f3919 3032 );
5b3543ce 3033
f436577a 3034 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3035 \Civi::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3036
5b3543ce
JM
3037 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3038 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3039 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3040 $dao->copyValues($entityParams);
3041 $dao->find();
3042 if ($dao->fetch()) {
3043 $entityParams['id'] = $dao->id;
3044 }
3045 $entityParams['financial_account_id'] = $account->id;
3046
7a1f3919
PN
3047 return CRM_Financial_BAO_FinancialTypeAccount::add($entityParams);
3048 }
3049
65e172a3 3050 /**
3051 * Create price set with contribution test for test setup.
3052 *
3053 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3054 * on parent class at some point (fn is not in 4.4).
3055 *
3056 * @param $entity
3057 * @param array $params
3058 */
3059 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3060 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3061 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3062 'title' => "Test Contribution Page",
3063 'financial_type_id' => 1,
3064 'currency' => 'NZD',
3065 'goal_amount' => 50,
3066 'is_pay_later' => 1,
3067 'is_monetary' => TRUE,
3068 'is_email_receipt' => FALSE,
3069 ));
3070 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3071 'is_quick_config' => 0,
3072 'extends' => 'CiviMember',
3073 'financial_type_id' => 1,
3074 'title' => 'my Page',
3075 ));
3076 $priceSetID = $priceSet['id'];
3077
3078 CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3079 $priceField = $this->callAPISuccess('price_field', 'create', array(
3080 'price_set_id' => $priceSetID,
3081 'label' => 'Goat Breed',
3082 'html_type' => 'Radio',
3083 ));
3084 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
39b959db
SL
3085 'price_set_id' => $priceSetID,
3086 'price_field_id' => $priceField['id'],
3087 'label' => 'Long Haired Goat',
3088 'amount' => 20,
3089 'financial_type_id' => 'Donation',
3090 'membership_type_id' => $membershipTypeID,
3091 'membership_num_terms' => 1,
3092 ));
65e172a3 3093 $this->_ids['price_field_value'] = array($priceFieldValue['id']);
3094 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
39b959db
SL
3095 'price_set_id' => $priceSetID,
3096 'price_field_id' => $priceField['id'],
3097 'label' => 'Shoe-eating Goat',
3098 'amount' => 10,
3099 'financial_type_id' => 'Donation',
3100 'membership_type_id' => $membershipTypeID,
3101 'membership_num_terms' => 2,
3102 ));
65e172a3 3103 $this->_ids['price_field_value'][] = $priceFieldValue['id'];
3104
3105 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
39b959db
SL
3106 'price_set_id' => $priceSetID,
3107 'price_field_id' => $priceField['id'],
3108 'label' => 'Shoe-eating Goat',
3109 'amount' => 10,
3110 'financial_type_id' => 'Donation',
3111 ));
65e172a3 3112 $this->_ids['price_field_value']['cont'] = $priceFieldValue['id'];
3113
3114 $this->_ids['price_set'] = $priceSetID;
3115 $this->_ids['contribution_page'] = $contributionPageResult['id'];
3116 $this->_ids['price_field'] = array($priceField['id']);
3117
3118 $this->_ids['membership_type'] = $membershipTypeID;
3119 }
3120
3c9d67b0 3121 /**
3122 * Only specified contact returned.
3123 * @implements CRM_Utils_Hook::aclWhereClause
3124 * @param $type
3125 * @param $tables
3126 * @param $whereTables
3127 * @param $contactID
3128 * @param $where
3129 */
3130 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3131 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts) . ")";
3132 }
3133
88ebed7c
JP
3134 /**
3135 * @implements CRM_Utils_Hook::selectWhereClause
3136 *
3137 * @param string $entity
3138 * @param array $clauses
3139 */
3140 public function selectWhereClauseHook($entity, &$clauses) {
3141 if ($entity == 'Event') {
3142 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3143 }
3144 }
3145
29a59599
JP
3146 /**
3147 * An implementation of hook_civicrm_post used with all our test cases.
3148 *
3149 * @param $op
3150 * @param string $objectName
3151 * @param int $objectId
3152 * @param $objectRef
3153 */
3154 public function onPost($op, $objectName, $objectId, &$objectRef) {
3155 if ($op == 'create' && $objectName == 'Individual') {
3156 CRM_Core_DAO::executeQuery(
3157 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3158 array(
3159 1 => array($objectId, 'Integer'),
3160 )
3161 );
3162 }
3163
3164 if ($op == 'edit' && $objectName == 'Participant') {
3165 $params = array(
3166 1 => array($objectId, 'Integer'),
3167 );
3168 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3169 CRM_Core_DAO::executeQuery($query, $params);
3170 }
3171 }
3172
f8df7165 3173 /**
3174 * Instantiate form object.
3175 *
3176 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3177 *
3178 * @param string $class
3179 * Name of form class.
3180 *
4715d267 3181 * @param array $formValues
3182 *
3183 * @param string $pageName
3184 *
f8df7165 3185 * @return \CRM_Core_Form
4715d267 3186 * @throws \CRM_Core_Exception
f8df7165 3187 */
4715d267 3188 public function getFormObject($class, $formValues = [], $pageName = '') {
f8df7165 3189 $form = new $class();
3190 $_SERVER['REQUEST_METHOD'] = 'GET';
3191 $form->controller = new CRM_Core_Controller();
4715d267 3192 $form->controller->setStateMachine(new CRM_Core_StateMachine($form->controller));
3193 $_SESSION['_' . $form->controller->_name . '_container']['values'][$pageName] = $formValues;
f8df7165 3194 return $form;
3195 }
3196
83644f47 3197 /**
3198 * Get possible thousand separators.
3199 *
3200 * @return array
3201 */
3202 public function getThousandSeparators() {
3203 return array(array('.'), array(','));
3204 }
3205
ebebd629 3206 /**
3207 * Get the boolean options as a provider.
3208 *
3209 * @return array
3210 */
3211 public function getBooleanDataProvider() {
3212 return [[TRUE], [FALSE]];
3213 }
3214
83644f47 3215 /**
3216 * Set the separators for thousands and decimal points.
3217 *
3218 * @param string $thousandSeparator
3219 */
3220 protected function setCurrencySeparators($thousandSeparator) {
3221 Civi::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3222 Civi::settings()
3223 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ? '.' : ','));
3224 }
3225
3226 /**
3227 * Format money as it would be input.
3228 *
3229 * @param string $amount
3230 *
3231 * @return string
3232 */
3233 protected function formatMoneyInput($amount) {
3234 return CRM_Utils_Money::format($amount, NULL, '%a');
3235 }
3236
3ca4bd1b 3237 /**
3238 * Get the contribution object.
3239 *
3240 * @param int $contributionID
3241 *
3242 * @return \CRM_Contribute_BAO_Contribution
3243 */
3244 protected function getContributionObject($contributionID) {
3245 $contributionObj = new CRM_Contribute_BAO_Contribution();
3246 $contributionObj->id = $contributionID;
3247 $contributionObj->find(TRUE);
3248 return $contributionObj;
3249 }
3250
df3320dc 3251 /**
3252 * Enable multilingual.
3253 */
3254 public function enableMultilingual() {
3255 $this->callAPISuccess('Setting', 'create', array(
3256 'lcMessages' => 'en_US',
3257 'languageLimit' => array(
3258 'en_US' => 1,
3259 ),
3260 ));
3261
3262 CRM_Core_I18n_Schema::makeMultilingual('en_US');
3263
3264 global $dbLocale;
3265 $dbLocale = '_en_US';
3266 }
3267
51c566a3
SL
3268 /**
3269 * Setup or clean up SMS tests
3270 * @param bool $teardown
3271 *
3272 * @throws \CiviCRM_API3_Exception
3273 */
3274 public function setupForSmsTests($teardown = FALSE) {
3275 require_once 'CiviTest/CiviTestSMSProvider.php';
3276
3277 // Option value params for CiviTestSMSProvider
3278 $groupID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'sms_provider_name', 'id', 'name');
3279 $params = array(
3280 'option_group_id' => $groupID,
3281 'label' => 'unittestSMS',
3282 'value' => 'unit.test.sms',
3283 'name' => 'CiviTestSMSProvider',
3284 'is_default' => 1,
3285 'is_active' => 1,
3286 'version' => 3,
3287 );
3288
3289 if ($teardown) {
3290 // Test completed, delete provider
3291 $providerOptionValueResult = civicrm_api3('option_value', 'get', $params);
3292 civicrm_api3('option_value', 'delete', array('id' => $providerOptionValueResult['id']));
3293 return;
3294 }
3295
3296 // Create an SMS provider "CiviTestSMSProvider". Civi handles "CiviTestSMSProvider" as a special case and allows it to be instantiated
3297 // in CRM/Sms/Provider.php even though it is not an extension.
3298 return civicrm_api3('option_value', 'create', $params);
3299 }
3300
68989e71 3301 /**
3302 * Start capturing browser output.
3303 *
3304 * The starts the process of browser output being captured, setting any variables needed for e-notice prevention.
3305 */
3306 protected function startCapturingOutput() {
3307 ob_start();
3308 $_SERVER['HTTP_USER_AGENT'] = 'unittest';
3309 }
3310
3311 /**
3312 * Stop capturing browser output and return as a csv.
3313 *
3314 * @param bool $isFirstRowHeaders
3315 *
3316 * @return \League\Csv\Reader
3317 *
3318 * @throws \League\Csv\Exception
3319 */
3320 protected function captureOutputToCSV($isFirstRowHeaders = TRUE) {
3321 $output = ob_get_flush();
3322 $stream = fopen('php://memory', 'r+');
3323 fwrite($stream, $output);
3324 rewind($stream);
3325 $csv = Reader::createFromString($output);
3326 if ($isFirstRowHeaders) {
3327 $csv->setHeaderOffset(0);
3328 }
3329 ob_clean();
3330 return $csv;
3331 }
3332
91786f44 3333 /**
3334 * Rename various labels to not match the names.
3335 *
3336 * Doing these mimics the fact the name != the label in international installs & triggers failures in
3337 * code that expects it to.
3338 */
3339 protected function renameLabels() {
3340 $replacements = ['Pending', 'Refunded'];
3341 foreach ($replacements as $name) {
3342 CRM_Core_DAO::executeQuery("UPDATE civicrm_option_value SET label = '{$name} Label**' where label = '{$name}' AND name = '{$name}'");
3343 }
3344 }
3345
3346 /**
3347 * Undo any label renaming.
3348 */
3349 protected function resetLabels() {
3350 CRM_Core_DAO::executeQuery("UPDATE civicrm_option_value SET label = REPLACE(name, ' Label**', '') WHERE label LIKE '% Label**'");
3351 }
3352
a86d27fc 3353}