Merge pull request #13550 from civicrm/5.10
[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 error_reporting(E_ALL);
340
341 $this->_sethtmlGlobals();
342 }
343
344 /**
345 * Read everything from the datasets directory and insert into the db.
346 */
347 public function loadAllFixtures() {
348 $fixturesDir = __DIR__ . '/../../fixtures';
349
350 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
351
352 $xmlFiles = glob($fixturesDir . '/*.xml');
353 foreach ($xmlFiles as $xmlFixture) {
354 $op = new PHPUnit_Extensions_Database_Operation_Insert();
355 $dataset = $this->createXMLDataSet($xmlFixture);
356 $this->_tablesToTruncate = array_merge($this->_tablesToTruncate, $dataset->getTableNames());
357 $op->execute($this->_dbconn, $dataset);
358 }
359
360 $yamlFiles = glob($fixturesDir . '/*.yaml');
361 foreach ($yamlFiles as $yamlFixture) {
362 $op = new PHPUnit_Extensions_Database_Operation_Insert();
363 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
364 $this->_tablesToTruncate = array_merge($this->_tablesToTruncate, $dataset->getTableNames());
365 $op->execute($this->_dbconn, $dataset);
366 }
367
368 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
369 }
370
371 /**
372 * Emulate a logged in user since certain functions use that.
373 * value to store a record in the DB (like activity)
374 * CRM-8180
375 *
376 * @return int
377 * Contact ID of the created user.
378 */
379 public function createLoggedInUser() {
380 $params = array(
381 'first_name' => 'Logged In',
382 'last_name' => 'User ' . rand(),
383 'contact_type' => 'Individual',
384 );
385 $contactID = $this->individualCreate($params);
386 $this->callAPISuccess('UFMatch', 'create', array(
387 'contact_id' => $contactID,
388 'uf_name' => 'superman',
389 'uf_id' => 6,
390 ));
391
392 $session = CRM_Core_Session::singleton();
393 $session->set('userID', $contactID);
394 return $contactID;
395 }
396
397 /**
398 * Create default domain contacts for the two domains added during test class.
399 * database population.
400 */
401 public function createDomainContacts() {
402 $this->organizationCreate();
403 $this->organizationCreate(array('organization_name' => 'Second Domain'));
404 }
405
406 /**
407 * Common teardown functions for all unit tests.
408 */
409 protected function tearDown() {
410 error_reporting(E_ALL & ~E_NOTICE);
411 CRM_Utils_Hook::singleton()->reset();
412 if ($this->hookClass) {
413 $this->hookClass->reset();
414 }
415 $session = CRM_Core_Session::singleton();
416 $session->set('userID', NULL);
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 ];
1985 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1986 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1987 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1988 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1989 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1990 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1991 foreach ($options as $option_value => $option_label) {
1992 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1993 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1994 }
1995
1996 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);
1997 }
1998
1999
2000 /**
2001 * Delete custom group.
2002 *
2003 * @param int $customGroupID
2004 *
2005 * @return array|int
2006 */
2007 public function customGroupDelete($customGroupID) {
2008 $params['id'] = $customGroupID;
2009 return $this->callAPISuccess('custom_group', 'delete', $params);
2010 }
2011
2012 /**
2013 * Create custom field.
2014 *
2015 * @param array $params
2016 * (custom_group_id) is required.
2017 * @return array
2018 */
2019 public function customFieldCreate($params) {
2020 $params = array_merge(array(
2021 'label' => 'Custom Field',
2022 'data_type' => 'String',
2023 'html_type' => 'Text',
2024 'is_searchable' => 1,
2025 'is_active' => 1,
2026 'default_value' => 'defaultValue',
2027 ), $params);
2028
2029 $result = $this->callAPISuccess('custom_field', 'create', $params);
2030 // these 2 functions are called with force to flush static caches
2031 CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
2032 CRM_Core_Component::getEnabledComponents(1);
2033 return $result;
2034 }
2035
2036 /**
2037 * Delete custom field.
2038 *
2039 * @param int $customFieldID
2040 *
2041 * @return array|int
2042 */
2043 public function customFieldDelete($customFieldID) {
2044
2045 $params['id'] = $customFieldID;
2046 return $this->callAPISuccess('custom_field', 'delete', $params);
2047 }
2048
2049 /**
2050 * Create note.
2051 *
2052 * @param int $cId
2053 * @return array
2054 */
2055 public function noteCreate($cId) {
2056 $params = array(
2057 'entity_table' => 'civicrm_contact',
2058 'entity_id' => $cId,
2059 'note' => 'hello I am testing Note',
2060 'contact_id' => $cId,
2061 'modified_date' => date('Ymd'),
2062 'subject' => 'Test Note',
2063 );
2064
2065 return $this->callAPISuccess('Note', 'create', $params);
2066 }
2067
2068 /**
2069 * Enable CiviCampaign Component.
2070 *
2071 * @param bool $reloadConfig
2072 * Force relaod config or not
2073 */
2074 public function enableCiviCampaign($reloadConfig = TRUE) {
2075 CRM_Core_BAO_ConfigSetting::enableComponent('CiviCampaign');
2076 if ($reloadConfig) {
2077 // force reload of config object
2078 $config = CRM_Core_Config::singleton(TRUE, TRUE);
2079 }
2080 //flush cache by calling with reset
2081 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2082 }
2083
2084 /**
2085 * Create custom field with Option Values.
2086 *
2087 * @param array $customGroup
2088 * @param string $name
2089 * Name of custom field.
2090 * @param array $extraParams
2091 * Additional parameters to pass through.
2092 *
2093 * @return array|int
2094 */
2095 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
2096 $fieldParams = array(
2097 'custom_group_id' => $customGroup['id'],
2098 'name' => 'test_custom_group',
2099 'label' => 'Country',
2100 'html_type' => 'Select',
2101 'data_type' => 'String',
2102 'weight' => 4,
2103 'is_required' => 1,
2104 'is_searchable' => 0,
2105 'is_active' => 1,
2106 );
2107
2108 $optionGroup = array(
2109 'domain_id' => 1,
2110 'name' => 'option_group1',
2111 'label' => 'option_group_label1',
2112 );
2113
2114 $optionValue = array(
2115 'option_label' => array('Label1', 'Label2'),
2116 'option_value' => array('value1', 'value2'),
2117 'option_name' => array($name . '_1', $name . '_2'),
2118 'option_weight' => array(1, 2),
2119 'option_status' => 1,
2120 );
2121
2122 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
2123
2124 return $this->callAPISuccess('custom_field', 'create', $params);
2125 }
2126
2127 /**
2128 * @param $entities
2129 *
2130 * @return bool
2131 */
2132 public function confirmEntitiesDeleted($entities) {
2133 foreach ($entities as $entity) {
2134
2135 $result = $this->callAPISuccess($entity, 'Get', array());
2136 if ($result['error'] == 1 || $result['count'] > 0) {
2137 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2138 return TRUE;
2139 }
2140 }
2141 return FALSE;
2142 }
2143
2144 /**
2145 * Quick clean by emptying tables created for the test.
2146 *
2147 * @param array $tablesToTruncate
2148 * @param bool $dropCustomValueTables
2149 * @throws \Exception
2150 */
2151 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2152 if ($this->tx) {
2153 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2154 }
2155 if ($dropCustomValueTables) {
2156 $optionGroupResult = CRM_Core_DAO::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2157 while ($optionGroupResult->fetch()) {
2158 if (!empty($optionGroupResult->option_group_id)) {
2159 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id);
2160 }
2161 }
2162 $tablesToTruncate[] = 'civicrm_custom_group';
2163 $tablesToTruncate[] = 'civicrm_custom_field';
2164 }
2165
2166 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate, $tablesToTruncate));
2167
2168 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2169 foreach ($tablesToTruncate as $table) {
2170 $sql = "TRUNCATE TABLE $table";
2171 CRM_Core_DAO::executeQuery($sql);
2172 }
2173 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2174
2175 if ($dropCustomValueTables) {
2176 $dbName = self::getDBName();
2177 $query = "
2178 SELECT TABLE_NAME as tableName
2179 FROM INFORMATION_SCHEMA.TABLES
2180 WHERE TABLE_SCHEMA = '{$dbName}'
2181 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2182 ";
2183
2184 $tableDAO = CRM_Core_DAO::executeQuery($query);
2185 while ($tableDAO->fetch()) {
2186 $sql = "DROP TABLE {$tableDAO->tableName}";
2187 CRM_Core_DAO::executeQuery($sql);
2188 }
2189 }
2190 }
2191
2192 /**
2193 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2194 */
2195 public function quickCleanUpFinancialEntities() {
2196 $tablesToTruncate = array(
2197 'civicrm_activity',
2198 'civicrm_activity_contact',
2199 'civicrm_contribution',
2200 'civicrm_contribution_soft',
2201 'civicrm_contribution_product',
2202 'civicrm_financial_trxn',
2203 'civicrm_financial_item',
2204 'civicrm_contribution_recur',
2205 'civicrm_line_item',
2206 'civicrm_contribution_page',
2207 'civicrm_payment_processor',
2208 'civicrm_entity_financial_trxn',
2209 'civicrm_membership',
2210 'civicrm_membership_type',
2211 'civicrm_membership_payment',
2212 'civicrm_membership_log',
2213 'civicrm_membership_block',
2214 'civicrm_event',
2215 'civicrm_participant',
2216 'civicrm_participant_payment',
2217 'civicrm_pledge',
2218 'civicrm_pledge_payment',
2219 'civicrm_price_set_entity',
2220 'civicrm_price_field_value',
2221 'civicrm_price_field',
2222 );
2223 $this->quickCleanup($tablesToTruncate);
2224 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2225 $this->restoreDefaultPriceSetConfig();
2226 $var = TRUE;
2227 CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE);
2228 $this->disableTaxAndInvoicing();
2229 $this->setCurrencySeparators(',');
2230 CRM_Core_PseudoConstant::flush('taxRates');
2231 System::singleton()->flushProcessors();
2232 }
2233
2234 public function restoreDefaultPriceSetConfig() {
2235 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
2236 CRM_Core_DAO::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
2237 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)");
2238 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)");
2239 }
2240 /*
2241 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2242 * Default behaviour is to also delete the entity
2243 * @param array $params
2244 * Params array to check against.
2245 * @param int $id
2246 * Id of the entity concerned.
2247 * @param string $entity
2248 * Name of entity concerned (e.g. membership).
2249 * @param bool $delete
2250 * Should the entity be deleted as part of this check.
2251 * @param string $errorText
2252 * Text to print on error.
2253 */
2254 /**
2255 * @param array $params
2256 * @param int $id
2257 * @param $entity
2258 * @param int $delete
2259 * @param string $errorText
2260 *
2261 * @throws Exception
2262 */
2263 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2264
2265 $result = $this->callAPISuccessGetSingle($entity, array(
2266 'id' => $id,
2267 ));
2268
2269 if ($delete) {
2270 $this->callAPISuccess($entity, 'Delete', array(
2271 'id' => $id,
2272 ));
2273 }
2274 $dateFields = $keys = $dateTimeFields = array();
2275 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2276 foreach ($fields['values'] as $field => $settings) {
2277 if (array_key_exists($field, $result)) {
2278 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = $field;
2279 }
2280 else {
2281 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = CRM_Utils_Array::value('name', $settings, $field);
2282 }
2283 $type = CRM_Utils_Array::value('type', $settings);
2284 if ($type == CRM_Utils_Type::T_DATE) {
2285 $dateFields[] = $settings['name'];
2286 // we should identify both real names & unique names as dates
2287 if ($field != $settings['name']) {
2288 $dateFields[] = $field;
2289 }
2290 }
2291 if ($type == CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) {
2292 $dateTimeFields[] = $settings['name'];
2293 // we should identify both real names & unique names as dates
2294 if ($field != $settings['name']) {
2295 $dateTimeFields[] = $field;
2296 }
2297 }
2298 }
2299
2300 if (strtolower($entity) == 'contribution') {
2301 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2302 // this is not returned in id format
2303 unset($params['payment_instrument_id']);
2304 $params['contribution_source'] = $params['source'];
2305 unset($params['source']);
2306 }
2307
2308 foreach ($params as $key => $value) {
2309 if ($key == 'version' || substr($key, 0, 3) == 'api' || !array_key_exists($keys[$key], $result)) {
2310 continue;
2311 }
2312 if (in_array($key, $dateFields)) {
2313 $value = date('Y-m-d', strtotime($value));
2314 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2315 }
2316 if (in_array($key, $dateTimeFields)) {
2317 $value = date('Y-m-d H:i:s', strtotime($value));
2318 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array::value($keys[$key], $result, CRM_Utils_Array::value($key, $result))));
2319 }
2320 $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);
2321 }
2322 }
2323
2324 /**
2325 * Get formatted values in the actual and expected result.
2326 * @param array $actual
2327 * Actual calculated values.
2328 * @param array $expected
2329 * Expected values.
2330 */
2331 public function checkArrayEquals(&$actual, &$expected) {
2332 self::unsetId($actual);
2333 self::unsetId($expected);
2334 $this->assertEquals($actual, $expected);
2335 }
2336
2337 /**
2338 * Unset the key 'id' from the array
2339 * @param array $unformattedArray
2340 * The array from which the 'id' has to be unset.
2341 */
2342 public static function unsetId(&$unformattedArray) {
2343 $formattedArray = array();
2344 if (array_key_exists('id', $unformattedArray)) {
2345 unset($unformattedArray['id']);
2346 }
2347 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2348 foreach ($unformattedArray['values'] as $key => $value) {
2349 if (is_array($value)) {
2350 foreach ($value as $k => $v) {
2351 if ($k == 'id') {
2352 unset($value[$k]);
2353 }
2354 }
2355 }
2356 elseif ($key == 'id') {
2357 $unformattedArray[$key];
2358 }
2359 $formattedArray = array($value);
2360 }
2361 $unformattedArray['values'] = $formattedArray;
2362 }
2363 }
2364
2365 /**
2366 * Helper to enable/disable custom directory support
2367 *
2368 * @param array $customDirs
2369 * With members:.
2370 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2371 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2372 */
2373 public function customDirectories($customDirs) {
2374 $config = CRM_Core_Config::singleton();
2375
2376 if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
2377 unset($config->customPHPPathDir);
2378 }
2379 elseif ($customDirs['php_path'] === TRUE) {
2380 $config->customPHPPathDir = dirname(dirname(__FILE__)) . '/custom_directories/php/';
2381 }
2382 else {
2383 $config->customPHPPathDir = $php_path;
2384 }
2385
2386 if (empty($customDirs['template_path']) || $customDirs['template_path'] === FALSE) {
2387 unset($config->customTemplateDir);
2388 }
2389 elseif ($customDirs['template_path'] === TRUE) {
2390 $config->customTemplateDir = dirname(dirname(__FILE__)) . '/custom_directories/templates/';
2391 }
2392 else {
2393 $config->customTemplateDir = $template_path;
2394 }
2395 }
2396
2397 /**
2398 * Generate a temporary folder.
2399 *
2400 * @param string $prefix
2401 * @return string
2402 */
2403 public function createTempDir($prefix = 'test-') {
2404 $tempDir = CRM_Utils_File::tempdir($prefix);
2405 $this->tempDirs[] = $tempDir;
2406 return $tempDir;
2407 }
2408
2409 public function cleanTempDirs() {
2410 if (!is_array($this->tempDirs)) {
2411 // fix test errors where this is not set
2412 return;
2413 }
2414 foreach ($this->tempDirs as $tempDir) {
2415 if (is_dir($tempDir)) {
2416 CRM_Utils_File::cleanDir($tempDir, TRUE, FALSE);
2417 }
2418 }
2419 }
2420
2421 /**
2422 * Temporarily replace the singleton extension with a different one.
2423 * @param \CRM_Extension_System $system
2424 */
2425 public function setExtensionSystem(CRM_Extension_System $system) {
2426 if ($this->origExtensionSystem == NULL) {
2427 $this->origExtensionSystem = CRM_Extension_System::singleton();
2428 }
2429 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2430 }
2431
2432 public function unsetExtensionSystem() {
2433 if ($this->origExtensionSystem !== NULL) {
2434 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2435 $this->origExtensionSystem = NULL;
2436 }
2437 }
2438
2439 /**
2440 * Temporarily alter the settings-metadata to add a mock setting.
2441 *
2442 * WARNING: The setting metadata will disappear on the next cache-clear.
2443 *
2444 * @param $extras
2445 * @return void
2446 */
2447 public function setMockSettingsMetaData($extras) {
2448 Civi::service('settings_manager')->flush();
2449
2450 CRM_Utils_Hook::singleton()
2451 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2452 $metadata = array_merge($metadata, $extras);
2453 });
2454
2455 $fields = $this->callAPISuccess('setting', 'getfields', array());
2456 foreach ($extras as $key => $spec) {
2457 $this->assertNotEmpty($spec['title']);
2458 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2459 }
2460 }
2461
2462 /**
2463 * @param string $name
2464 */
2465 public function financialAccountDelete($name) {
2466 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2467 $financialAccount->name = $name;
2468 if ($financialAccount->find(TRUE)) {
2469 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2470 $entityFinancialType->financial_account_id = $financialAccount->id;
2471 $entityFinancialType->delete();
2472 $financialAccount->delete();
2473 }
2474 }
2475
2476 /**
2477 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2478 * (NB unclear if this is still required)
2479 */
2480 public function _sethtmlGlobals() {
2481 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2482 'required' => array(
2483 'html_quickform_rule_required',
2484 'HTML/QuickForm/Rule/Required.php',
2485 ),
2486 'maxlength' => array(
2487 'html_quickform_rule_range',
2488 'HTML/QuickForm/Rule/Range.php',
2489 ),
2490 'minlength' => array(
2491 'html_quickform_rule_range',
2492 'HTML/QuickForm/Rule/Range.php',
2493 ),
2494 'rangelength' => array(
2495 'html_quickform_rule_range',
2496 'HTML/QuickForm/Rule/Range.php',
2497 ),
2498 'email' => array(
2499 'html_quickform_rule_email',
2500 'HTML/QuickForm/Rule/Email.php',
2501 ),
2502 'regex' => array(
2503 'html_quickform_rule_regex',
2504 'HTML/QuickForm/Rule/Regex.php',
2505 ),
2506 'lettersonly' => array(
2507 'html_quickform_rule_regex',
2508 'HTML/QuickForm/Rule/Regex.php',
2509 ),
2510 'alphanumeric' => array(
2511 'html_quickform_rule_regex',
2512 'HTML/QuickForm/Rule/Regex.php',
2513 ),
2514 'numeric' => array(
2515 'html_quickform_rule_regex',
2516 'HTML/QuickForm/Rule/Regex.php',
2517 ),
2518 'nopunctuation' => array(
2519 'html_quickform_rule_regex',
2520 'HTML/QuickForm/Rule/Regex.php',
2521 ),
2522 'nonzero' => array(
2523 'html_quickform_rule_regex',
2524 'HTML/QuickForm/Rule/Regex.php',
2525 ),
2526 'callback' => array(
2527 'html_quickform_rule_callback',
2528 'HTML/QuickForm/Rule/Callback.php',
2529 ),
2530 'compare' => array(
2531 'html_quickform_rule_compare',
2532 'HTML/QuickForm/Rule/Compare.php',
2533 ),
2534 );
2535 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2536 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2537 'group' => array(
2538 'HTML/QuickForm/group.php',
2539 'HTML_QuickForm_group',
2540 ),
2541 'hidden' => array(
2542 'HTML/QuickForm/hidden.php',
2543 'HTML_QuickForm_hidden',
2544 ),
2545 'reset' => array(
2546 'HTML/QuickForm/reset.php',
2547 'HTML_QuickForm_reset',
2548 ),
2549 'checkbox' => array(
2550 'HTML/QuickForm/checkbox.php',
2551 'HTML_QuickForm_checkbox',
2552 ),
2553 'file' => array(
2554 'HTML/QuickForm/file.php',
2555 'HTML_QuickForm_file',
2556 ),
2557 'image' => array(
2558 'HTML/QuickForm/image.php',
2559 'HTML_QuickForm_image',
2560 ),
2561 'password' => array(
2562 'HTML/QuickForm/password.php',
2563 'HTML_QuickForm_password',
2564 ),
2565 'radio' => array(
2566 'HTML/QuickForm/radio.php',
2567 'HTML_QuickForm_radio',
2568 ),
2569 'button' => array(
2570 'HTML/QuickForm/button.php',
2571 'HTML_QuickForm_button',
2572 ),
2573 'submit' => array(
2574 'HTML/QuickForm/submit.php',
2575 'HTML_QuickForm_submit',
2576 ),
2577 'select' => array(
2578 'HTML/QuickForm/select.php',
2579 'HTML_QuickForm_select',
2580 ),
2581 'hiddenselect' => array(
2582 'HTML/QuickForm/hiddenselect.php',
2583 'HTML_QuickForm_hiddenselect',
2584 ),
2585 'text' => array(
2586 'HTML/QuickForm/text.php',
2587 'HTML_QuickForm_text',
2588 ),
2589 'textarea' => array(
2590 'HTML/QuickForm/textarea.php',
2591 'HTML_QuickForm_textarea',
2592 ),
2593 'fckeditor' => array(
2594 'HTML/QuickForm/fckeditor.php',
2595 'HTML_QuickForm_FCKEditor',
2596 ),
2597 'tinymce' => array(
2598 'HTML/QuickForm/tinymce.php',
2599 'HTML_QuickForm_TinyMCE',
2600 ),
2601 'dojoeditor' => array(
2602 'HTML/QuickForm/dojoeditor.php',
2603 'HTML_QuickForm_dojoeditor',
2604 ),
2605 'link' => array(
2606 'HTML/QuickForm/link.php',
2607 'HTML_QuickForm_link',
2608 ),
2609 'advcheckbox' => array(
2610 'HTML/QuickForm/advcheckbox.php',
2611 'HTML_QuickForm_advcheckbox',
2612 ),
2613 'date' => array(
2614 'HTML/QuickForm/date.php',
2615 'HTML_QuickForm_date',
2616 ),
2617 'static' => array(
2618 'HTML/QuickForm/static.php',
2619 'HTML_QuickForm_static',
2620 ),
2621 'header' => array(
2622 'HTML/QuickForm/header.php',
2623 'HTML_QuickForm_header',
2624 ),
2625 'html' => array(
2626 'HTML/QuickForm/html.php',
2627 'HTML_QuickForm_html',
2628 ),
2629 'hierselect' => array(
2630 'HTML/QuickForm/hierselect.php',
2631 'HTML_QuickForm_hierselect',
2632 ),
2633 'autocomplete' => array(
2634 'HTML/QuickForm/autocomplete.php',
2635 'HTML_QuickForm_autocomplete',
2636 ),
2637 'xbutton' => array(
2638 'HTML/QuickForm/xbutton.php',
2639 'HTML_QuickForm_xbutton',
2640 ),
2641 'advmultiselect' => array(
2642 'HTML/QuickForm/advmultiselect.php',
2643 'HTML_QuickForm_advmultiselect',
2644 ),
2645 );
2646 }
2647
2648 /**
2649 * Set up an acl allowing contact to see 2 specified groups
2650 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2651 *
2652 * You need to have pre-created these groups & created the user e.g
2653 * $this->createLoggedInUser();
2654 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2655 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2656 *
2657 * @param bool $isProfile
2658 */
2659 public function setupACL($isProfile = FALSE) {
2660 global $_REQUEST;
2661 $_REQUEST = $this->_params;
2662
2663 CRM_Core_Config::singleton()->userPermissionClass->permissions = array('access CiviCRM');
2664 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2665 $ov = new CRM_Core_DAO_OptionValue();
2666 $ov->option_group_id = $optionGroupID;
2667 $ov->value = 55;
2668 if ($ov->find(TRUE)) {
2669 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2670 }
2671 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2672 'option_group_id' => $optionGroupID,
2673 'label' => 'pick me',
2674 'value' => 55,
2675 ));
2676
2677 CRM_Core_DAO::executeQuery("
2678 TRUNCATE civicrm_acl_cache
2679 ");
2680
2681 CRM_Core_DAO::executeQuery("
2682 TRUNCATE civicrm_acl_contact_cache
2683 ");
2684
2685 CRM_Core_DAO::executeQuery("
2686 INSERT INTO civicrm_acl_entity_role (
2687 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2688 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2689 ");
2690
2691 if ($isProfile) {
2692 CRM_Core_DAO::executeQuery("
2693 INSERT INTO civicrm_acl (
2694 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2695 )
2696 VALUES (
2697 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2698 );
2699 ");
2700 }
2701 else {
2702 CRM_Core_DAO::executeQuery("
2703 INSERT INTO civicrm_acl (
2704 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2705 )
2706 VALUES (
2707 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2708 );
2709 ");
2710
2711 CRM_Core_DAO::executeQuery("
2712 INSERT INTO civicrm_acl (
2713 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2714 )
2715 VALUES (
2716 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2717 );
2718 ");
2719 }
2720
2721 $this->_loggedInUser = CRM_Core_Session::singleton()->get('userID');
2722 $this->callAPISuccess('group_contact', 'create', array(
2723 'group_id' => $this->_permissionedGroup,
2724 'contact_id' => $this->_loggedInUser,
2725 ));
2726
2727 if (!$isProfile) {
2728 //flush cache
2729 CRM_ACL_BAO_Cache::resetCache();
2730 CRM_ACL_API::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2731 }
2732 }
2733
2734 /**
2735 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2736 */
2737 public function offsetDefaultPriceSet() {
2738 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2739 $firstID = $contributionPriceSet['id'];
2740 $this->callAPISuccess('price_set', 'create', array(
2741 'id' => $contributionPriceSet['id'],
2742 'is_active' => 0,
2743 'name' => 'old',
2744 ));
2745 unset($contributionPriceSet['id']);
2746 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2747 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2748 'price_set_id' => $firstID,
2749 'options' => array('limit' => 1),
2750 ));
2751 unset($priceField['id']);
2752 $priceField['price_set_id'] = $newPriceSet['id'];
2753 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2754 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2755 'price_set_id' => $firstID,
2756 'sequential' => 1,
2757 'options' => array('limit' => 1),
2758 ));
2759
2760 unset($priceFieldValue['id']);
2761 //create some padding to use up ids
2762 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2763 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2764 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2765 }
2766
2767 /**
2768 * Create an instance of the paypal processor.
2769 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2770 * this parent class & we don't have a structure for that yet
2771 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2772 * & the best protection against that is the functions this class affords
2773 * @param array $params
2774 * @return int $result['id'] payment processor id
2775 */
2776 public function paymentProcessorCreate($params = array()) {
2777 $params = array_merge(array(
2778 'name' => 'demo',
2779 'domain_id' => CRM_Core_Config::domainID(),
2780 'payment_processor_type_id' => 'PayPal',
2781 'is_active' => 1,
2782 'is_default' => 0,
2783 'is_test' => 1,
2784 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2785 'password' => '1183377788',
2786 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2787 'url_site' => 'https://www.sandbox.paypal.com/',
2788 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2789 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2790 'class_name' => 'Payment_PayPalImpl',
2791 'billing_mode' => 3,
2792 'financial_type_id' => 1,
2793 'financial_account_id' => 12,
2794 // Credit card = 1 so can pass 'by accident'.
2795 'payment_instrument_id' => 'Debit Card',
2796 ),
2797 $params);
2798 if (!is_numeric($params['payment_processor_type_id'])) {
2799 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2800 //here
2801 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2802 'name' => $params['payment_processor_type_id'],
2803 'return' => 'id',
2804 ), 'integer');
2805 }
2806 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2807 return $result['id'];
2808 }
2809
2810 /**
2811 * Set up initial recurring payment allowing subsequent IPN payments.
2812 *
2813 * @param array $recurParams (Optional)
2814 * @param array $contributionParams (Optional)
2815 */
2816 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2817 $contributionParams = array_merge([
2818 'total_amount' => '200',
2819 'invoice_id' => $this->_invoiceID,
2820 'financial_type_id' => 'Donation',
2821 'contribution_status_id' => 'Pending',
2822 'contact_id' => $this->_contactID,
2823 'contribution_page_id' => $this->_contributionPageID,
2824 'payment_processor_id' => $this->_paymentProcessorID,
2825 'is_test' => 0,
2826 'skipCleanMoney' => TRUE,
2827 ],
2828 $contributionParams
2829 );
2830 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2831 'contact_id' => $this->_contactID,
2832 'amount' => 1000,
2833 'sequential' => 1,
2834 'installments' => 5,
2835 'frequency_unit' => 'Month',
2836 'frequency_interval' => 1,
2837 'invoice_id' => $this->_invoiceID,
2838 'contribution_status_id' => 2,
2839 'payment_processor_id' => $this->_paymentProcessorID,
2840 // processor provided ID - use contact ID as proxy.
2841 'processor_id' => $this->_contactID,
2842 'api.contribution.create' => $contributionParams,
2843 ), $recurParams));
2844 $this->_contributionRecurID = $contributionRecur['id'];
2845 $this->_contributionID = $contributionRecur['values']['0']['api.contribution.create']['id'];
2846 }
2847
2848 /**
2849 * 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
2850 *
2851 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2852 */
2853 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2854 $membershipParams = $recurParams = array();
2855 if (!empty($params['duration_unit'])) {
2856 $membershipParams['duration_unit'] = $params['duration_unit'];
2857 }
2858 if (!empty($params['frequency_unit'])) {
2859 $recurParams['frequency_unit'] = $params['frequency_unit'];
2860 }
2861
2862 $this->ids['membership_type'] = $this->membershipTypeCreate($membershipParams);
2863 //create a contribution so our membership & contribution don't both have id = 1
2864 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2865 $this->contributionCreate(array(
2866 'contact_id' => $this->_contactID,
2867 'is_test' => 1,
2868 'financial_type_id' => 1,
2869 'invoice_id' => 'abcd',
2870 'trxn_id' => 345,
2871 ));
2872 }
2873 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2874
2875 $this->ids['membership'] = $this->callAPISuccess('membership', 'create', array(
2876 'contact_id' => $this->_contactID,
2877 'membership_type_id' => $this->ids['membership_type'],
2878 'contribution_recur_id' => $this->_contributionRecurID,
2879 'format.only_id' => TRUE,
2880 ));
2881 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2882 CRM_Core_DAO::executeQuery("TRUNCATE civicrm_line_item");
2883
2884 $this->callAPISuccess('line_item', 'create', array(
2885 'entity_table' => 'civicrm_membership',
2886 'entity_id' => $this->ids['membership'],
2887 'contribution_id' => $this->_contributionID,
2888 'label' => 'General',
2889 'qty' => 1,
2890 'unit_price' => 200,
2891 'line_total' => 200,
2892 'financial_type_id' => 1,
2893 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2894 'return' => 'id',
2895 'label' => 'Membership Amount',
2896 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2897 )),
2898 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2899 'return' => 'id',
2900 'label' => 'General',
2901 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2902 )),
2903 ));
2904 $this->callAPISuccess('membership_payment', 'create', array(
2905 'contribution_id' => $this->_contributionID,
2906 'membership_id' => $this->ids['membership'],
2907 ));
2908 }
2909
2910 /**
2911 * @param $message
2912 *
2913 * @throws Exception
2914 */
2915 public function CiviUnitTestCase_fatalErrorHandler($message) {
2916 throw new Exception("{$message['message']}: {$message['code']}");
2917 }
2918
2919 /**
2920 * Helper function to create new mailing.
2921 *
2922 * @param array $params
2923 *
2924 * @return int
2925 */
2926 public function createMailing($params = array()) {
2927 $params = array_merge(array(
2928 'subject' => 'maild' . rand(),
2929 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
2930 'name' => 'mailing name' . rand(),
2931 'created_id' => 1,
2932 ), $params);
2933
2934 $result = $this->callAPISuccess('Mailing', 'create', $params);
2935 return $result['id'];
2936 }
2937
2938 /**
2939 * Helper function to delete mailing.
2940 * @param $id
2941 */
2942 public function deleteMailing($id) {
2943 $params = array(
2944 'id' => $id,
2945 );
2946
2947 $this->callAPISuccess('Mailing', 'delete', $params);
2948 }
2949
2950 /**
2951 * Wrap the entire test case in a transaction.
2952 *
2953 * Only subsequent DB statements will be wrapped in TX -- this cannot
2954 * retroactively wrap old DB statements. Therefore, it makes sense to
2955 * call this at the beginning of setUp().
2956 *
2957 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2958 * this option does not work with, e.g., custom-data.
2959 *
2960 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2961 * if TRUNCATE or ALTER is called while using a transaction.
2962 *
2963 * @param bool $nest
2964 * Whether to use nesting or reference-counting.
2965 */
2966 public function useTransaction($nest = TRUE) {
2967 if (!$this->tx) {
2968 $this->tx = new CRM_Core_Transaction($nest);
2969 $this->tx->rollback();
2970 }
2971 }
2972
2973 /**
2974 * Assert the attachment exists.
2975 *
2976 * @param bool $exists
2977 * @param array $apiResult
2978 */
2979 protected function assertAttachmentExistence($exists, $apiResult) {
2980 $fileId = $apiResult['id'];
2981 $this->assertTrue(is_numeric($fileId));
2982 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2983 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2984 1 => array($fileId, 'Int'),
2985 ));
2986 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2987 1 => array($fileId, 'Int'),
2988 ));
2989 }
2990
2991 /**
2992 * Create a price set for an event.
2993 *
2994 * @param int $feeTotal
2995 * @param int $minAmt
2996 * @param string $type
2997 *
2998 * @return int
2999 * Price Set ID.
3000 */
3001 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
3002 // creating price set, price field
3003 $paramsSet['title'] = 'Price Set';
3004 $paramsSet['name'] = CRM_Utils_String::titleToVar('Price Set');
3005 $paramsSet['is_active'] = FALSE;
3006 $paramsSet['extends'] = 1;
3007 $paramsSet['min_amount'] = $minAmt;
3008
3009 $priceSet = CRM_Price_BAO_PriceSet::create($paramsSet);
3010 $this->_ids['price_set'] = $priceSet->id;
3011
3012 $paramsField = array(
3013 'label' => 'Price Field',
3014 'name' => CRM_Utils_String::titleToVar('Price Field'),
3015 'html_type' => $type,
3016 'price' => $feeTotal,
3017 'option_label' => array('1' => 'Price Field'),
3018 'option_value' => array('1' => $feeTotal),
3019 'option_name' => array('1' => $feeTotal),
3020 'option_weight' => array('1' => 1),
3021 'option_amount' => array('1' => 1),
3022 'is_display_amounts' => 1,
3023 'weight' => 1,
3024 'options_per_line' => 1,
3025 'is_active' => array('1' => 1),
3026 'price_set_id' => $this->_ids['price_set'],
3027 'is_enter_qty' => 1,
3028 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3029 );
3030 if ($type === 'Radio') {
3031 $paramsField['is_enter_qty'] = 0;
3032 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
3033 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
3034 }
3035 CRM_Price_BAO_PriceField::create($paramsField);
3036 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids['price_set']));
3037 $this->_ids['price_field'] = array_keys($fields['values']);
3038 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids['price_field'][0]));
3039 $this->_ids['price_field_value'] = array_keys($fieldValues['values']);
3040
3041 return $this->_ids['price_set'];
3042 }
3043
3044 /**
3045 * Add a profile to a contribution page.
3046 *
3047 * @param string $name
3048 * @param int $contributionPageID
3049 * @param string $module
3050 */
3051 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
3052 $params = [
3053 'uf_group_id' => $name,
3054 'module' => $module,
3055 'entity_table' => 'civicrm_contribution_page',
3056 'entity_id' => $contributionPageID,
3057 'weight' => 1,
3058 ];
3059 if ($module !== 'CiviContribute') {
3060 $params['module_data'] = [$module => []];
3061 }
3062 $this->callAPISuccess('UFJoin', 'create', $params);
3063 }
3064
3065 /**
3066 * Add participant with contribution
3067 *
3068 * @return array
3069 */
3070 protected function createParticipantWithContribution() {
3071 // creating price set, price field
3072 $this->_contactId = $this->individualCreate();
3073 $event = $this->eventCreate();
3074 $this->_eventId = $event['id'];
3075 $eventParams = array(
3076 'id' => $this->_eventId,
3077 'financial_type_id' => 4,
3078 'is_monetary' => 1,
3079 );
3080 $this->callAPISuccess('event', 'create', $eventParams);
3081 $priceFields = $this->createPriceSet('event', $this->_eventId);
3082 $participantParams = array(
3083 'financial_type_id' => 4,
3084 'event_id' => $this->_eventId,
3085 'role_id' => 1,
3086 'status_id' => 14,
3087 'fee_currency' => 'USD',
3088 'contact_id' => $this->_contactId,
3089 );
3090 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3091 $contributionParams = array(
3092 'total_amount' => 150,
3093 'currency' => 'USD',
3094 'contact_id' => $this->_contactId,
3095 'financial_type_id' => 4,
3096 'contribution_status_id' => 1,
3097 'partial_payment_total' => 300.00,
3098 'partial_amount_to_pay' => 150,
3099 'contribution_mode' => 'participant',
3100 'participant_id' => $participant['id'],
3101 );
3102 foreach ($priceFields['values'] as $key => $priceField) {
3103 $lineItems[1][$key] = array(
3104 'price_field_id' => $priceField['price_field_id'],
3105 'price_field_value_id' => $priceField['id'],
3106 'label' => $priceField['label'],
3107 'field_title' => $priceField['label'],
3108 'qty' => 1,
3109 'unit_price' => $priceField['amount'],
3110 'line_total' => $priceField['amount'],
3111 'financial_type_id' => $priceField['financial_type_id'],
3112 );
3113 }
3114 $contributionParams['line_item'] = $lineItems;
3115 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3116 $paymentParticipant = array(
3117 'participant_id' => $participant['id'],
3118 'contribution_id' => $contribution['id'],
3119 );
3120 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3121 return array($lineItems, $contribution);
3122 }
3123
3124 /**
3125 * Create price set
3126 *
3127 * @param string $component
3128 * @param int $componentId
3129 *
3130 * @return array
3131 */
3132 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
3133 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
3134 $paramsSet['name'] = CRM_Utils_String::titleToVar($paramsSet['title']);
3135 $paramsSet['is_active'] = TRUE;
3136 $paramsSet['financial_type_id'] = 4;
3137 $paramsSet['extends'] = 1;
3138 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3139 $priceSetId = $priceSet['id'];
3140 //Checking for priceset added in the table.
3141 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3142 'id', $paramsSet['title'], 'Check DB for created priceset'
3143 );
3144 $paramsField = array_merge(array(
3145 'label' => 'Price Field',
3146 'name' => CRM_Utils_String::titleToVar('Price Field'),
3147 'html_type' => 'CheckBox',
3148 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3149 'option_value' => array('1' => 100, '2' => 200),
3150 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3151 'option_weight' => array('1' => 1, '2' => 2),
3152 'option_amount' => array('1' => 100, '2' => 200),
3153 'is_display_amounts' => 1,
3154 'weight' => 1,
3155 'options_per_line' => 1,
3156 'is_active' => array('1' => 1, '2' => 1),
3157 'price_set_id' => $priceSet['id'],
3158 'is_enter_qty' => 1,
3159 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
3160 ), $priceFieldOptions);
3161
3162 $priceField = CRM_Price_BAO_PriceField::create($paramsField);
3163 if ($componentId) {
3164 CRM_Price_BAO_PriceSet::addTo('civicrm_' . $component, $componentId, $priceSetId);
3165 }
3166 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id));
3167 }
3168
3169 /**
3170 * Replace the template with a test-oriented template designed to show all the variables.
3171 *
3172 * @param string $templateName
3173 */
3174 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
3175 $testTemplate = file_get_contents(__DIR__ . '/../../templates/message_templates/' . $templateName . '_html.tpl');
3176 CRM_Core_DAO::executeQuery(
3177 "UPDATE civicrm_option_group og
3178 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3179 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3180 SET m.msg_html = '{$testTemplate}'
3181 WHERE og.name = 'msg_tpl_workflow_contribution'
3182 AND ov.name = '{$templateName}'
3183 AND m.is_default = 1"
3184 );
3185 }
3186
3187 /**
3188 * Reinstate the default template.
3189 *
3190 * @param string $templateName
3191 */
3192 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
3193 CRM_Core_DAO::executeQuery(
3194 "UPDATE civicrm_option_group og
3195 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3196 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3197 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
3198 SET m.msg_html = m2.msg_html
3199 WHERE og.name = 'msg_tpl_workflow_contribution'
3200 AND ov.name = '{$templateName}'
3201 AND m.is_default = 1"
3202 );
3203 }
3204
3205 /**
3206 * Flush statics relating to financial type.
3207 */
3208 protected function flushFinancialTypeStatics() {
3209 if (isset(\Civi::$statics['CRM_Financial_BAO_FinancialType'])) {
3210 unset(\Civi::$statics['CRM_Financial_BAO_FinancialType']);
3211 }
3212 if (isset(\Civi::$statics['CRM_Contribute_PseudoConstant'])) {
3213 unset(\Civi::$statics['CRM_Contribute_PseudoConstant']);
3214 }
3215 CRM_Contribute_PseudoConstant::flush('financialType');
3216 CRM_Contribute_PseudoConstant::flush('membershipType');
3217 // Pseudoconstants may be saved to the cache table.
3218 CRM_Core_DAO::executeQuery("TRUNCATE civicrm_cache");
3219 CRM_Financial_BAO_FinancialType::$_statusACLFt = array();
3220 CRM_Financial_BAO_FinancialType::$_availableFinancialTypes = NULL;
3221 }
3222
3223 /**
3224 * Set the permissions to the supplied array.
3225 *
3226 * @param array $permissions
3227 */
3228 protected function setPermissions($permissions) {
3229 CRM_Core_Config::singleton()->userPermissionClass->permissions = $permissions;
3230 $this->flushFinancialTypeStatics();
3231 }
3232
3233 /**
3234 * @param array $params
3235 * @param $context
3236 */
3237 public function _checkFinancialRecords($params, $context) {
3238 $entityParams = array(
3239 'entity_id' => $params['id'],
3240 'entity_table' => 'civicrm_contribution',
3241 );
3242 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3243 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3244 if ($context == 'pending') {
3245 $trxn = CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams);
3246 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3247 return;
3248 }
3249 $trxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
3250 $trxnParams = array(
3251 'id' => $trxn['financial_trxn_id'],
3252 );
3253 if ($context != 'online' && $context != 'payLater') {
3254 $compareParams = array(
3255 'to_financial_account_id' => 6,
3256 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3257 'status_id' => 1,
3258 );
3259 }
3260 if ($context == 'feeAmount') {
3261 $compareParams['fee_amount'] = 50;
3262 }
3263 elseif ($context == 'online') {
3264 $compareParams = array(
3265 'to_financial_account_id' => 12,
3266 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3267 'status_id' => 1,
3268 'payment_instrument_id' => CRM_Utils_Array::value('payment_instrument_id', $params, 1),
3269 );
3270 }
3271 elseif ($context == 'payLater') {
3272 $compareParams = array(
3273 'to_financial_account_id' => 7,
3274 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3275 'status_id' => 2,
3276 );
3277 }
3278 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3279 $entityParams = array(
3280 'financial_trxn_id' => $trxn['financial_trxn_id'],
3281 'entity_table' => 'civicrm_financial_item',
3282 );
3283 $entityTrxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
3284 $fitemParams = array(
3285 'id' => $entityTrxn['entity_id'],
3286 );
3287 $compareParams = array(
3288 'amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3289 'status_id' => 1,
3290 'financial_account_id' => CRM_Utils_Array::value('financial_account_id', $params, 1),
3291 );
3292 if ($context == 'payLater') {
3293 $compareParams = array(
3294 'amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3295 'status_id' => 3,
3296 'financial_account_id' => CRM_Utils_Array::value('financial_account_id', $params, 1),
3297 );
3298 }
3299 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3300 if ($context == 'feeAmount') {
3301 $maxParams = array(
3302 'entity_id' => $params['id'],
3303 'entity_table' => 'civicrm_contribution',
3304 );
3305 $maxTrxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($maxParams, TRUE));
3306 $trxnParams = array(
3307 'id' => $maxTrxn['financial_trxn_id'],
3308 );
3309 $compareParams = array(
3310 'to_financial_account_id' => 5,
3311 'from_financial_account_id' => 6,
3312 'total_amount' => 50,
3313 'status_id' => 1,
3314 );
3315 $trxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['id'], 'DESC');
3316 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3317 $fitemParams = array(
3318 'entity_id' => $trxnId['financialTrxnId'],
3319 'entity_table' => 'civicrm_financial_trxn',
3320 );
3321 $compareParams = array(
3322 'amount' => 50,
3323 'status_id' => 1,
3324 'financial_account_id' => 5,
3325 );
3326 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3327 }
3328 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3329 // line should be copied into all the functions that call this function & evaluated there
3330 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3331 // when calling completeTransaction or repeatTransaction.
3332 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
3333 }
3334
3335 /**
3336 * Return financial type id on basis of name
3337 *
3338 * @param string $name Financial type m/c name
3339 *
3340 * @return int
3341 */
3342 public function getFinancialTypeId($name) {
3343 return CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
3344 }
3345
3346 /**
3347 * Cleanup function for contents of $this->ids.
3348 *
3349 * This is a best effort cleanup to use in tear downs etc.
3350 *
3351 * It will not fail if the data has already been removed (some tests may do
3352 * their own cleanup).
3353 */
3354 protected function cleanUpSetUpIDs() {
3355 foreach ($this->setupIDs as $entity => $id) {
3356 try {
3357 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
3358 }
3359 catch (CiviCRM_API3_Exception $e) {
3360 // This is a best-effort cleanup function, ignore.
3361 }
3362 }
3363 }
3364
3365 /**
3366 * Create Financial Type.
3367 *
3368 * @param array $params
3369 *
3370 * @return array
3371 */
3372 protected function createFinancialType($params = array()) {
3373 $params = array_merge($params,
3374 array(
3375 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
3376 'is_active' => 1,
3377 )
3378 );
3379 return $this->callAPISuccess('FinancialType', 'create', $params);
3380 }
3381
3382 /**
3383 * Create Payment Instrument.
3384 *
3385 * @param array $params
3386 * @param string $financialAccountName
3387 *
3388 * @return int
3389 */
3390 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
3391 $params = array_merge(array(
3392 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
3393 'option_group_id' => 'payment_instrument',
3394 'is_active' => 1,
3395 ),
3396 $params
3397 );
3398 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params);
3399
3400 $relationTypeID = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
3401
3402 $financialAccountParams = [
3403 'entity_table' => 'civicrm_option_value',
3404 'entity_id' => key($newPaymentInstrument),
3405 'account_relationship' => $relationTypeID,
3406 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
3407 ];
3408 CRM_Financial_BAO_FinancialTypeAccount::add($financialAccountParams);
3409
3410 return CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
3411 }
3412
3413 /**
3414 * Enable Tax and Invoicing
3415 */
3416 protected function enableTaxAndInvoicing($params = array()) {
3417 // Enable component contribute setting
3418 $contributeSetting = array_merge($params,
3419 array(
3420 'invoicing' => 1,
3421 'invoice_prefix' => 'INV_',
3422 'credit_notes_prefix' => 'CN_',
3423 'due_date' => 10,
3424 'due_date_period' => 'days',
3425 'notes' => '',
3426 'is_email_pdf' => 1,
3427 'tax_term' => 'Sales Tax',
3428 'tax_display_settings' => 'Inclusive',
3429 )
3430 );
3431 return Civi::settings()->set('contribution_invoice_settings', $contributeSetting);
3432 }
3433
3434 /**
3435 * Enable Tax and Invoicing
3436 */
3437 protected function disableTaxAndInvoicing($params = array()) {
3438 if (!empty(\Civi::$statics['CRM_Core_PseudoConstant']) && isset(\Civi::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
3439 unset(\Civi::$statics['CRM_Core_PseudoConstant']['taxRates']);
3440 }
3441 // Enable component contribute setting
3442 $contributeSetting = array_merge($params,
3443 array(
3444 'invoicing' => 0,
3445 )
3446 );
3447 return Civi::settings()->set('contribution_invoice_settings', $contributeSetting);
3448 }
3449
3450 /**
3451 * Add Sales Tax relation for financial type with financial account.
3452 *
3453 * @param int $financialTypeId
3454 *
3455 * @return obj
3456 */
3457 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3458 $params = array(
3459 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3460 'financial_account_type_id' => key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3461 'is_deductible' => 1,
3462 'is_tax' => 1,
3463 'tax_rate' => 10,
3464 'is_active' => 1,
3465 );
3466 $account = CRM_Financial_BAO_FinancialAccount::add($params);
3467 $entityParams = array(
3468 'entity_table' => 'civicrm_financial_type',
3469 'entity_id' => $financialTypeId,
3470 'account_relationship' => key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
3471 );
3472
3473 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3474 \Civi::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3475
3476 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3477 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3478 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3479 $dao->copyValues($entityParams);
3480 $dao->find();
3481 if ($dao->fetch()) {
3482 $entityParams['id'] = $dao->id;
3483 }
3484 $entityParams['financial_account_id'] = $account->id;
3485
3486 return CRM_Financial_BAO_FinancialTypeAccount::add($entityParams);
3487 }
3488
3489 /**
3490 * Create price set with contribution test for test setup.
3491 *
3492 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3493 * on parent class at some point (fn is not in 4.4).
3494 *
3495 * @param $entity
3496 * @param array $params
3497 */
3498 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3499 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3500 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3501 'title' => "Test Contribution Page",
3502 'financial_type_id' => 1,
3503 'currency' => 'NZD',
3504 'goal_amount' => 50,
3505 'is_pay_later' => 1,
3506 'is_monetary' => TRUE,
3507 'is_email_receipt' => FALSE,
3508 ));
3509 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3510 'is_quick_config' => 0,
3511 'extends' => 'CiviMember',
3512 'financial_type_id' => 1,
3513 'title' => 'my Page',
3514 ));
3515 $priceSetID = $priceSet['id'];
3516
3517 CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3518 $priceField = $this->callAPISuccess('price_field', 'create', array(
3519 'price_set_id' => $priceSetID,
3520 'label' => 'Goat Breed',
3521 'html_type' => 'Radio',
3522 ));
3523 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3524 'price_set_id' => $priceSetID,
3525 'price_field_id' => $priceField['id'],
3526 'label' => 'Long Haired Goat',
3527 'amount' => 20,
3528 'financial_type_id' => 'Donation',
3529 'membership_type_id' => $membershipTypeID,
3530 'membership_num_terms' => 1,
3531 )
3532 );
3533 $this->_ids['price_field_value'] = array($priceFieldValue['id']);
3534 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3535 'price_set_id' => $priceSetID,
3536 'price_field_id' => $priceField['id'],
3537 'label' => 'Shoe-eating Goat',
3538 'amount' => 10,
3539 'financial_type_id' => 'Donation',
3540 'membership_type_id' => $membershipTypeID,
3541 'membership_num_terms' => 2,
3542 )
3543 );
3544 $this->_ids['price_field_value'][] = $priceFieldValue['id'];
3545
3546 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3547 'price_set_id' => $priceSetID,
3548 'price_field_id' => $priceField['id'],
3549 'label' => 'Shoe-eating Goat',
3550 'amount' => 10,
3551 'financial_type_id' => 'Donation',
3552 )
3553 );
3554 $this->_ids['price_field_value']['cont'] = $priceFieldValue['id'];
3555
3556 $this->_ids['price_set'] = $priceSetID;
3557 $this->_ids['contribution_page'] = $contributionPageResult['id'];
3558 $this->_ids['price_field'] = array($priceField['id']);
3559
3560 $this->_ids['membership_type'] = $membershipTypeID;
3561 }
3562
3563 /**
3564 * Only specified contact returned.
3565 * @implements CRM_Utils_Hook::aclWhereClause
3566 * @param $type
3567 * @param $tables
3568 * @param $whereTables
3569 * @param $contactID
3570 * @param $where
3571 */
3572 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3573 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts) . ")";
3574 }
3575
3576 /**
3577 * @implements CRM_Utils_Hook::selectWhereClause
3578 *
3579 * @param string $entity
3580 * @param array $clauses
3581 */
3582 public function selectWhereClauseHook($entity, &$clauses) {
3583 if ($entity == 'Event') {
3584 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3585 }
3586 }
3587
3588 /**
3589 * An implementation of hook_civicrm_post used with all our test cases.
3590 *
3591 * @param $op
3592 * @param string $objectName
3593 * @param int $objectId
3594 * @param $objectRef
3595 */
3596 public function onPost($op, $objectName, $objectId, &$objectRef) {
3597 if ($op == 'create' && $objectName == 'Individual') {
3598 CRM_Core_DAO::executeQuery(
3599 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3600 array(
3601 1 => array($objectId, 'Integer'),
3602 )
3603 );
3604 }
3605
3606 if ($op == 'edit' && $objectName == 'Participant') {
3607 $params = array(
3608 1 => array($objectId, 'Integer'),
3609 );
3610 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3611 CRM_Core_DAO::executeQuery($query, $params);
3612 }
3613 }
3614
3615
3616 /**
3617 * Instantiate form object.
3618 *
3619 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3620 *
3621 * @param string $class
3622 * Name of form class.
3623 *
3624 * @return \CRM_Core_Form
3625 */
3626 public function getFormObject($class) {
3627 $form = new $class();
3628 $_SERVER['REQUEST_METHOD'] = 'GET';
3629 $form->controller = new CRM_Core_Controller();
3630 return $form;
3631 }
3632
3633 /**
3634 * Get possible thousand separators.
3635 *
3636 * @return array
3637 */
3638 public function getThousandSeparators() {
3639 return array(array('.'), array(','));
3640 }
3641
3642 /**
3643 * Set the separators for thousands and decimal points.
3644 *
3645 * @param string $thousandSeparator
3646 */
3647 protected function setCurrencySeparators($thousandSeparator) {
3648 Civi::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3649 Civi::settings()
3650 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ? '.' : ','));
3651 }
3652
3653 /**
3654 * Format money as it would be input.
3655 *
3656 * @param string $amount
3657 *
3658 * @return string
3659 */
3660 protected function formatMoneyInput($amount) {
3661 return CRM_Utils_Money::format($amount, NULL, '%a');
3662 }
3663
3664
3665 /**
3666 * Get the contribution object.
3667 *
3668 * @param int $contributionID
3669 *
3670 * @return \CRM_Contribute_BAO_Contribution
3671 */
3672 protected function getContributionObject($contributionID) {
3673 $contributionObj = new CRM_Contribute_BAO_Contribution();
3674 $contributionObj->id = $contributionID;
3675 $contributionObj->find(TRUE);
3676 return $contributionObj;
3677 }
3678
3679 /**
3680 * Enable multilingual.
3681 */
3682 public function enableMultilingual() {
3683 $this->callAPISuccess('Setting', 'create', array(
3684 'lcMessages' => 'en_US',
3685 'languageLimit' => array(
3686 'en_US' => 1,
3687 ),
3688 ));
3689
3690 CRM_Core_I18n_Schema::makeMultilingual('en_US');
3691
3692 global $dbLocale;
3693 $dbLocale = '_en_US';
3694 }
3695
3696 }