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