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