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