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