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