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