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