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