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