CRM-17213 add tests for group search
[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) {
1391 $this->_pageParams = array(
1392 'title' => 'Test Contribution Page',
1393 'financial_type_id' => 1,
1394 'currency' => 'USD',
1395 'financial_account_id' => 1,
1396 'payment_processor' => $params['processor_id'],
1397 'is_active' => 1,
1398 'is_allow_other_amount' => 1,
1399 'min_amount' => 10,
1400 'max_amount' => 1000,
1401 );
1402 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
1403 return $contributionPage;
1404 }
1405
1406 /**
1407 * Create a sample batch.
1408 */
1409 public function batchCreate() {
1410 $params = $this->_params;
1411 $params['name'] = $params['title'] = 'Batch_433397';
1412 $params['status_id'] = 1;
1413 $result = $this->callAPISuccess('batch', 'create', $params);
1414 return $result['id'];
1415 }
1416
1417 /**
1418 * Create Tag.
1419 *
1420 * @param array $params
1421 * @return array
1422 * result of created tag
1423 */
1424 public function tagCreate($params = array()) {
1425 $defaults = array(
1426 'name' => 'New Tag3',
1427 'description' => 'This is description for Our New Tag ',
1428 'domain_id' => '1',
1429 );
1430 $params = array_merge($defaults, $params);
1431 $result = $this->callAPISuccess('Tag', 'create', $params);
1432 return $result['values'][$result['id']];
1433 }
1434
1435 /**
1436 * Delete Tag.
1437 *
1438 * @param int $tagId
1439 * Id of the tag to be deleted.
1440 *
1441 * @return int
1442 */
1443 public function tagDelete($tagId) {
1444 require_once 'api/api.php';
1445 $params = array(
1446 'tag_id' => $tagId,
1447 );
1448 $result = $this->callAPISuccess('Tag', 'delete', $params);
1449 return $result['id'];
1450 }
1451
1452 /**
1453 * Add entity(s) to the tag
1454 *
1455 * @param array $params
1456 *
1457 * @return bool
1458 */
1459 public function entityTagAdd($params) {
1460 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1461 return TRUE;
1462 }
1463
1464 /**
1465 * Create pledge.
1466 *
1467 * @param array $params
1468 * Parameters.
1469 *
1470 * @return int
1471 * id of created pledge
1472 */
1473 public function pledgeCreate($params) {
1474 $params = array_merge(array(
1475 'pledge_create_date' => date('Ymd'),
1476 'start_date' => date('Ymd'),
1477 'scheduled_date' => date('Ymd'),
1478 'amount' => 100.00,
1479 'pledge_status_id' => '2',
1480 'financial_type_id' => '1',
1481 'pledge_original_installment_amount' => 20,
1482 'frequency_interval' => 5,
1483 'frequency_unit' => 'year',
1484 'frequency_day' => 15,
1485 'installments' => 5,
1486 ),
1487 $params);
1488
1489 $result = $this->callAPISuccess('Pledge', 'create', $params);
1490 return $result['id'];
1491 }
1492
1493 /**
1494 * Delete contribution.
1495 *
1496 * @param int $pledgeId
1497 */
1498 public function pledgeDelete($pledgeId) {
1499 $params = array(
1500 'pledge_id' => $pledgeId,
1501 );
1502 $this->callAPISuccess('Pledge', 'delete', $params);
1503 }
1504
1505 /**
1506 * Create contribution.
1507 *
1508 * @param array $params
1509 * Array of parameters.
1510 *
1511 * @return int
1512 * id of created contribution
1513 */
1514 public function contributionCreate($params) {
1515
1516 $params = array_merge(array(
1517 'domain_id' => 1,
1518 'receive_date' => date('Ymd'),
1519 'total_amount' => 100.00,
1520 'fee_amount' => 5.00,
1521 'net_ammount' => 95.00,
1522 'financial_type_id' => 1,
1523 'payment_instrument_id' => 1,
1524 'non_deductible_amount' => 10.00,
1525 'trxn_id' => 12345,
1526 'invoice_id' => 67890,
1527 'source' => 'SSF',
1528 'contribution_status_id' => 1,
1529 ), $params);
1530
1531 $result = $this->callAPISuccess('contribution', 'create', $params);
1532 return $result['id'];
1533 }
1534
1535 /**
1536 * Delete contribution.
1537 *
1538 * @param int $contributionId
1539 *
1540 * @return array|int
1541 */
1542 public function contributionDelete($contributionId) {
1543 $params = array(
1544 'contribution_id' => $contributionId,
1545 );
1546 $result = $this->callAPISuccess('contribution', 'delete', $params);
1547 return $result;
1548 }
1549
1550 /**
1551 * Create an Event.
1552 *
1553 * @param array $params
1554 * Name-value pair for an event.
1555 *
1556 * @return array
1557 */
1558 public function eventCreate($params = array()) {
1559 // if no contact was passed, make up a dummy event creator
1560 if (!isset($params['contact_id'])) {
1561 $params['contact_id'] = $this->_contactCreate(array(
1562 'contact_type' => 'Individual',
1563 'first_name' => 'Event',
1564 'last_name' => 'Creator',
1565 ));
1566 }
1567
1568 // set defaults for missing params
1569 $params = array_merge(array(
1570 'title' => 'Annual CiviCRM meet',
1571 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1572 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1573 'event_type_id' => 1,
1574 'is_public' => 1,
1575 'start_date' => 20081021,
1576 'end_date' => 20081023,
1577 'is_online_registration' => 1,
1578 'registration_start_date' => 20080601,
1579 'registration_end_date' => 20081015,
1580 'max_participants' => 100,
1581 'event_full_text' => 'Sorry! We are already full',
1582 'is_monetary' => 0,
1583 'is_active' => 1,
1584 'is_show_location' => 0,
1585 ), $params);
1586
1587 return $this->callAPISuccess('Event', 'create', $params);
1588 }
1589
1590 /**
1591 * Delete event.
1592 *
1593 * @param int $id
1594 * ID of the event.
1595 *
1596 * @return array|int
1597 */
1598 public function eventDelete($id) {
1599 $params = array(
1600 'event_id' => $id,
1601 );
1602 return $this->callAPISuccess('event', 'delete', $params);
1603 }
1604
1605 /**
1606 * Delete participant.
1607 *
1608 * @param int $participantID
1609 *
1610 * @return array|int
1611 */
1612 public function participantDelete($participantID) {
1613 $params = array(
1614 'id' => $participantID,
1615 );
1616 return $this->callAPISuccess('Participant', 'delete', $params);
1617 }
1618
1619 /**
1620 * Create participant payment.
1621 *
1622 * @param int $participantID
1623 * @param int $contributionID
1624 * @return int
1625 * $id of created payment
1626 */
1627 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1628 //Create Participant Payment record With Values
1629 $params = array(
1630 'participant_id' => $participantID,
1631 'contribution_id' => $contributionID,
1632 );
1633
1634 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1635 return $result['id'];
1636 }
1637
1638 /**
1639 * Delete participant payment.
1640 *
1641 * @param int $paymentID
1642 */
1643 public function participantPaymentDelete($paymentID) {
1644 $params = array(
1645 'id' => $paymentID,
1646 );
1647 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1648 }
1649
1650 /**
1651 * Add a Location.
1652 *
1653 * @param int $contactID
1654 * @return int
1655 * location id of created location
1656 */
1657 public function locationAdd($contactID) {
1658 $address = array(
1659 1 => array(
1660 'location_type' => 'New Location Type',
1661 'is_primary' => 1,
1662 'name' => 'Saint Helier St',
1663 'county' => 'Marin',
1664 'country' => 'UNITED STATES',
1665 'state_province' => 'Michigan',
1666 'supplemental_address_1' => 'Hallmark Ct',
1667 'supplemental_address_2' => 'Jersey Village',
1668 ),
1669 );
1670
1671 $params = array(
1672 'contact_id' => $contactID,
1673 'address' => $address,
1674 'location_format' => '2.0',
1675 'location_type' => 'New Location Type',
1676 );
1677
1678 $result = $this->callAPISuccess('Location', 'create', $params);
1679 return $result;
1680 }
1681
1682 /**
1683 * Delete Locations of contact.
1684 *
1685 * @param array $params
1686 * Parameters.
1687 */
1688 public function locationDelete($params) {
1689 $this->callAPISuccess('Location', 'delete', $params);
1690 }
1691
1692 /**
1693 * Add a Location Type.
1694 *
1695 * @param array $params
1696 * @return CRM_Core_DAO_LocationType
1697 * location id of created location
1698 */
1699 public function locationTypeCreate($params = NULL) {
1700 if ($params === NULL) {
1701 $params = array(
1702 'name' => 'New Location Type',
1703 'vcard_name' => 'New Location Type',
1704 'description' => 'Location Type for Delete',
1705 'is_active' => 1,
1706 );
1707 }
1708
1709 $locationType = new CRM_Core_DAO_LocationType();
1710 $locationType->copyValues($params);
1711 $locationType->save();
1712 // clear getfields cache
1713 CRM_Core_PseudoConstant::flush();
1714 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1715 return $locationType;
1716 }
1717
1718 /**
1719 * Delete a Location Type.
1720 *
1721 * @param int $locationTypeId
1722 */
1723 public function locationTypeDelete($locationTypeId) {
1724 $locationType = new CRM_Core_DAO_LocationType();
1725 $locationType->id = $locationTypeId;
1726 $locationType->delete();
1727 }
1728
1729 /**
1730 * Add a Mapping.
1731 *
1732 * @param array $params
1733 * @return CRM_Core_DAO_Mapping
1734 * Mapping id of created mapping
1735 */
1736 public function mappingCreate($params = NULL) {
1737 if ($params === NULL) {
1738 $params = array(
1739 'name' => 'Mapping name',
1740 'description' => 'Mapping description',
1741 // 'Export Contact' mapping.
1742 'mapping_type_id' => 7,
1743 );
1744 }
1745
1746 $mapping = new CRM_Core_DAO_Mapping();
1747 $mapping->copyValues($params);
1748 $mapping->save();
1749 // clear getfields cache
1750 CRM_Core_PseudoConstant::flush();
1751 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1752 return $mapping;
1753 }
1754
1755 /**
1756 * Delete a Mapping
1757 *
1758 * @param int $mappingId
1759 */
1760 public function mappingDelete($mappingId) {
1761 $mapping = new CRM_Core_DAO_Mapping();
1762 $mapping->id = $mappingId;
1763 $mapping->delete();
1764 }
1765
1766 /**
1767 * Add a Group.
1768 *
1769 * @param array $params
1770 * @return int
1771 * groupId of created group
1772 */
1773 public function groupCreate($params = array()) {
1774 $params = array_merge(array(
1775 'name' => 'Test Group 1',
1776 'domain_id' => 1,
1777 'title' => 'New Test Group Created',
1778 'description' => 'New Test Group Created',
1779 'is_active' => 1,
1780 'visibility' => 'Public Pages',
1781 'group_type' => array(
1782 '1' => 1,
1783 '2' => 1,
1784 ),
1785 ), $params);
1786
1787 $result = $this->callAPISuccess('Group', 'create', $params);
1788 return $result['id'];
1789 }
1790
1791 /**
1792 * Create a smart group.
1793 *
1794 * By default it will be a group of households.
1795 *
1796 * @param array $smartGroupParams
1797 * @param array $groupParams
1798 * @return int
1799 */
1800 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1801 $smartGroupParams = array_merge(array(
1802 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1803 ),
1804 $smartGroupParams);
1805 $savedSearch = CRM_Contact_BAO_SavedSearch::create($smartGroupParams);
1806
1807 $groupParams['saved_search_id'] = $savedSearch->id;
1808 return $this->groupCreate($groupParams);
1809 }
1810
1811 /**
1812 * Function to add a Group.
1813 *
1814 * @params array to add group
1815 *
1816 * @param int $groupID
1817 * @param int $totalCount
1818 * @return int
1819 * groupId of created group
1820 */
1821 public function groupContactCreate($groupID, $totalCount = 10) {
1822 $params = array('group_id' => $groupID);
1823 for ($i = 1; $i <= $totalCount; $i++) {
1824 $contactID = $this->individualCreate();
1825 if ($i == 1) {
1826 $params += array('contact_id' => $contactID);
1827 }
1828 else {
1829 $params += array("contact_id.$i" => $contactID);
1830 }
1831 }
1832 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1833
1834 return $result;
1835 }
1836
1837 /**
1838 * Delete a Group.
1839 *
1840 * @param int $gid
1841 */
1842 public function groupDelete($gid) {
1843
1844 $params = array(
1845 'id' => $gid,
1846 );
1847
1848 $this->callAPISuccess('Group', 'delete', $params);
1849 }
1850
1851 /**
1852 * Create a UFField.
1853 * @param array $params
1854 */
1855 public function uFFieldCreate($params = array()) {
1856 $params = array_merge(array(
1857 'uf_group_id' => 1,
1858 'field_name' => 'first_name',
1859 'is_active' => 1,
1860 'is_required' => 1,
1861 'visibility' => 'Public Pages and Listings',
1862 'is_searchable' => '1',
1863 'label' => 'first_name',
1864 'field_type' => 'Individual',
1865 'weight' => 1,
1866 ), $params);
1867 $this->callAPISuccess('uf_field', 'create', $params);
1868 }
1869
1870 /**
1871 * Add a UF Join Entry.
1872 *
1873 * @param array $params
1874 * @return int
1875 * $id of created UF Join
1876 */
1877 public function ufjoinCreate($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' => 1,
1886 );
1887 }
1888 $result = $this->callAPISuccess('uf_join', 'create', $params);
1889 return $result;
1890 }
1891
1892 /**
1893 * Delete a UF Join Entry.
1894 *
1895 * @param array $params
1896 * with missing uf_group_id
1897 */
1898 public function ufjoinDelete($params = NULL) {
1899 if ($params === NULL) {
1900 $params = array(
1901 'is_active' => 1,
1902 'module' => 'CiviEvent',
1903 'entity_table' => 'civicrm_event',
1904 'entity_id' => 3,
1905 'weight' => 1,
1906 'uf_group_id' => '',
1907 );
1908 }
1909
1910 crm_add_uf_join($params);
1911 }
1912
1913 /**
1914 * @param array $params
1915 * Optional parameters.
1916 *
1917 * @return int
1918 * Campaign ID.
1919 */
1920 public function campaignCreate($params = array()) {
1921 $this->enableCiviCampaign();
1922 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1923 'name' => 'big_campaign',
1924 'title' => 'Campaign',
1925 ), $params));
1926 return $campaign['id'];
1927 }
1928
1929 /**
1930 * Create Group for a contact.
1931 *
1932 * @param int $contactId
1933 */
1934 public function contactGroupCreate($contactId) {
1935 $params = array(
1936 'contact_id.1' => $contactId,
1937 'group_id' => 1,
1938 );
1939
1940 $this->callAPISuccess('GroupContact', 'Create', $params);
1941 }
1942
1943 /**
1944 * Delete Group for a contact.
1945 *
1946 * @param int $contactId
1947 */
1948 public function contactGroupDelete($contactId) {
1949 $params = array(
1950 'contact_id.1' => $contactId,
1951 'group_id' => 1,
1952 );
1953 $this->civicrm_api('GroupContact', 'Delete', $params);
1954 }
1955
1956 /**
1957 * Create Activity.
1958 *
1959 * @param array $params
1960 * @return array|int
1961 */
1962 public function activityCreate($params = NULL) {
1963
1964 if ($params === NULL) {
1965 $individualSourceID = $this->individualCreate();
1966
1967 $contactParams = array(
1968 'first_name' => 'Julia',
1969 'Last_name' => 'Anderson',
1970 'prefix' => 'Ms.',
1971 'email' => 'julia_anderson@civicrm.org',
1972 'contact_type' => 'Individual',
1973 );
1974
1975 $individualTargetID = $this->individualCreate($contactParams);
1976
1977 $params = array(
1978 'source_contact_id' => $individualSourceID,
1979 'target_contact_id' => array($individualTargetID),
1980 'assignee_contact_id' => array($individualTargetID),
1981 'subject' => 'Discussion on warm beer',
1982 'activity_date_time' => date('Ymd'),
1983 'duration_hours' => 30,
1984 'duration_minutes' => 20,
1985 'location' => 'Baker Street',
1986 'details' => 'Lets schedule a meeting',
1987 'status_id' => 1,
1988 'activity_name' => 'Meeting',
1989 );
1990 }
1991
1992 $result = $this->callAPISuccess('Activity', 'create', $params);
1993
1994 $result['target_contact_id'] = $individualTargetID;
1995 $result['assignee_contact_id'] = $individualTargetID;
1996 return $result;
1997 }
1998
1999 /**
2000 * Create an activity type.
2001 *
2002 * @param array $params
2003 * Parameters.
2004 * @return array
2005 */
2006 public function activityTypeCreate($params) {
2007 return $this->callAPISuccess('ActivityType', 'create', $params);
2008 }
2009
2010 /**
2011 * Delete activity type.
2012 *
2013 * @param int $activityTypeId
2014 * Id of the activity type.
2015 * @return array
2016 */
2017 public function activityTypeDelete($activityTypeId) {
2018 $params['activity_type_id'] = $activityTypeId;
2019 return $this->callAPISuccess('ActivityType', 'delete', $params);
2020 }
2021
2022 /**
2023 * Create custom group.
2024 *
2025 * @param array $params
2026 * @return array
2027 */
2028 public function customGroupCreate($params = array()) {
2029 $defaults = array(
2030 'title' => 'new custom group',
2031 'extends' => 'Contact',
2032 'domain_id' => 1,
2033 'style' => 'Inline',
2034 'is_active' => 1,
2035 );
2036
2037 $params = array_merge($defaults, $params);
2038
2039 if (strlen($params['title']) > 13) {
2040 $params['title'] = substr($params['title'], 0, 13);
2041 }
2042
2043 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2044 $this->callAPISuccess('custom_group', 'get', array(
2045 'title' => $params['title'],
2046 array('api.custom_group.delete' => 1),
2047 ));
2048
2049 return $this->callAPISuccess('custom_group', 'create', $params);
2050 }
2051
2052 /**
2053 * Existing function doesn't allow params to be over-ridden so need a new one
2054 * this one allows you to only pass in the params you want to change
2055 * @param array $params
2056 * @return array|int
2057 */
2058 public function CustomGroupCreateByParams($params = array()) {
2059 $defaults = array(
2060 'title' => "API Custom Group",
2061 'extends' => 'Contact',
2062 'domain_id' => 1,
2063 'style' => 'Inline',
2064 'is_active' => 1,
2065 );
2066 $params = array_merge($defaults, $params);
2067 return $this->callAPISuccess('custom_group', 'create', $params);
2068 }
2069
2070 /**
2071 * Create custom group with multi fields.
2072 * @param array $params
2073 * @return array|int
2074 */
2075 public function CustomGroupMultipleCreateByParams($params = array()) {
2076 $defaults = array(
2077 'style' => 'Tab',
2078 'is_multiple' => 1,
2079 );
2080 $params = array_merge($defaults, $params);
2081 return $this->CustomGroupCreateByParams($params);
2082 }
2083
2084 /**
2085 * Create custom group with multi fields.
2086 * @param array $params
2087 * @return array
2088 */
2089 public function CustomGroupMultipleCreateWithFields($params = array()) {
2090 // also need to pass on $params['custom_field'] if not set but not in place yet
2091 $ids = array();
2092 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2093 $ids['custom_group_id'] = $customGroup['id'];
2094
2095 $customField = $this->customFieldCreate(array(
2096 'custom_group_id' => $ids['custom_group_id'],
2097 'label' => 'field_1' . $ids['custom_group_id'],
2098 ));
2099
2100 $ids['custom_field_id'][] = $customField['id'];
2101
2102 $customField = $this->customFieldCreate(array(
2103 'custom_group_id' => $ids['custom_group_id'],
2104 'default_value' => '',
2105 'label' => 'field_2' . $ids['custom_group_id'],
2106 ));
2107 $ids['custom_field_id'][] = $customField['id'];
2108
2109 $customField = $this->customFieldCreate(array(
2110 'custom_group_id' => $ids['custom_group_id'],
2111 'default_value' => '',
2112 'label' => 'field_3' . $ids['custom_group_id'],
2113 ));
2114 $ids['custom_field_id'][] = $customField['id'];
2115
2116 return $ids;
2117 }
2118
2119 /**
2120 * Create a custom group with a single text custom field. See
2121 * participant:testCreateWithCustom for how to use this
2122 *
2123 * @param string $function
2124 * __FUNCTION__.
2125 * @param string $filename
2126 * $file __FILE__.
2127 *
2128 * @return array
2129 * ids of created objects
2130 */
2131 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2132 $params = array('title' => $function);
2133 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2134 $params['extends'] = $entity ? $entity : 'Contact';
2135 $customGroup = $this->CustomGroupCreate($params);
2136 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2137 CRM_Core_PseudoConstant::flush();
2138
2139 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2140 }
2141
2142 /**
2143 * Delete custom group.
2144 *
2145 * @param int $customGroupID
2146 *
2147 * @return array|int
2148 */
2149 public function customGroupDelete($customGroupID) {
2150 $params['id'] = $customGroupID;
2151 return $this->callAPISuccess('custom_group', 'delete', $params);
2152 }
2153
2154 /**
2155 * Create custom field.
2156 *
2157 * @param array $params
2158 * (custom_group_id) is required.
2159 * @return array
2160 */
2161 public function customFieldCreate($params) {
2162 $params = array_merge(array(
2163 'label' => 'Custom Field',
2164 'data_type' => 'String',
2165 'html_type' => 'Text',
2166 'is_searchable' => 1,
2167 'is_active' => 1,
2168 'default_value' => 'defaultValue',
2169 ), $params);
2170
2171 $result = $this->callAPISuccess('custom_field', 'create', $params);
2172 // these 2 functions are called with force to flush static caches
2173 CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
2174 CRM_Core_Component::getEnabledComponents(1);
2175 return $result;
2176 }
2177
2178 /**
2179 * Delete custom field.
2180 *
2181 * @param int $customFieldID
2182 *
2183 * @return array|int
2184 */
2185 public function customFieldDelete($customFieldID) {
2186
2187 $params['id'] = $customFieldID;
2188 return $this->callAPISuccess('custom_field', 'delete', $params);
2189 }
2190
2191 /**
2192 * Create note.
2193 *
2194 * @param int $cId
2195 * @return array
2196 */
2197 public function noteCreate($cId) {
2198 $params = array(
2199 'entity_table' => 'civicrm_contact',
2200 'entity_id' => $cId,
2201 'note' => 'hello I am testing Note',
2202 'contact_id' => $cId,
2203 'modified_date' => date('Ymd'),
2204 'subject' => 'Test Note',
2205 );
2206
2207 return $this->callAPISuccess('Note', 'create', $params);
2208 }
2209
2210 /**
2211 * Enable CiviCampaign Component.
2212 */
2213 public function enableCiviCampaign() {
2214 CRM_Core_BAO_ConfigSetting::enableComponent('CiviCampaign');
2215 // force reload of config object
2216 $config = CRM_Core_Config::singleton(TRUE, TRUE);
2217 //flush cache by calling with reset
2218 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2219 }
2220
2221 /**
2222 * Create test generated example in api/v3/examples.
2223 *
2224 * To turn this off (e.g. on the server) set
2225 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2226 * in your settings file
2227 *
2228 * @param string $entity
2229 * @param string $action
2230 * @param array $params
2231 * Array as passed to civicrm_api function.
2232 * @param array $result
2233 * Array as received from the civicrm_api function.
2234 * @param string $testFunction
2235 * Calling function - generally __FUNCTION__.
2236 * @param string $testFile
2237 * Called from file - generally __FILE__.
2238 * @param string $description
2239 * Descriptive text for the example file.
2240 * @param string $exampleName
2241 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
2242 */
2243 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
2244 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG) {
2245 return;
2246 }
2247 $entity = _civicrm_api_get_camel_name($entity);
2248 $action = strtolower($action);
2249
2250 if (empty($exampleName)) {
2251 // Attempt to convert lowercase action name to CamelCase.
2252 // This is clunky/imperfect due to the convention of all lowercase actions.
2253 $exampleName = CRM_Utils_String::convertStringToCamel($action);
2254 $knownPrefixes = array(
2255 'Get',
2256 'Set',
2257 'Create',
2258 'Update',
2259 'Send',
2260 );
2261 foreach ($knownPrefixes as $prefix) {
2262 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2263 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2264 }
2265 }
2266 }
2267
2268 $this->tidyExampleResult($result);
2269 if (isset($params['version'])) {
2270 unset($params['version']);
2271 }
2272 // Format multiline description as array
2273 $desc = array();
2274 if (is_string($description) && strlen($description)) {
2275 foreach (explode("\n", $description) as $line) {
2276 $desc[] = trim($line);
2277 }
2278 }
2279 $smarty = CRM_Core_Smarty::singleton();
2280 $smarty->assign('testFunction', $testFunction);
2281 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
2282 $smarty->assign('params', $params);
2283 $smarty->assign('entity', $entity);
2284 $smarty->assign('testFile', basename($testFile));
2285 $smarty->assign('description', $desc);
2286 $smarty->assign('result', $result);
2287 $smarty->assign('action', $action);
2288
2289 global $civicrm_root;
2290 if (file_exists($civicrm_root . '/tests/templates/documentFunction.tpl')) {
2291 if (!is_dir($civicrm_root . "/api/v3/examples/$entity")) {
2292 mkdir($civicrm_root . "/api/v3/examples/$entity");
2293 }
2294 $f = fopen($civicrm_root . "/api/v3/examples/$entity/$exampleName.php", "w+b");
2295 fwrite($f, $smarty->fetch($civicrm_root . '/tests/templates/documentFunction.tpl'));
2296 fclose($f);
2297 }
2298 }
2299
2300 /**
2301 * Tidy up examples array so that fields that change often ..don't
2302 * and debug related fields are unset
2303 *
2304 * @param array $result
2305 */
2306 public function tidyExampleResult(&$result) {
2307 if (!is_array($result)) {
2308 return;
2309 }
2310 $fieldsToChange = array(
2311 'hash' => '67eac7789eaee00',
2312 'modified_date' => '2012-11-14 16:02:35',
2313 'created_date' => '2013-07-28 08:49:19',
2314 'create_date' => '20120130621222105',
2315 'application_received_date' => '20130728084957',
2316 'in_date' => '2013-07-28 08:50:19',
2317 'scheduled_date' => '20130728085413',
2318 'approval_date' => '20130728085413',
2319 'pledge_start_date_high' => '20130726090416',
2320 'start_date' => '2013-07-29 00:00:00',
2321 'event_start_date' => '2013-07-29 00:00:00',
2322 'end_date' => '2013-08-04 00:00:00',
2323 'event_end_date' => '2013-08-04 00:00:00',
2324 'decision_date' => '20130805000000',
2325 );
2326
2327 $keysToUnset = array('xdebug', 'undefined_fields');
2328 foreach ($keysToUnset as $unwantedKey) {
2329 if (isset($result[$unwantedKey])) {
2330 unset($result[$unwantedKey]);
2331 }
2332 }
2333 if (isset($result['values'])) {
2334 if (!is_array($result['values'])) {
2335 return;
2336 }
2337 $resultArray = &$result['values'];
2338 }
2339 elseif (is_array($result)) {
2340 $resultArray = &$result;
2341 }
2342 else {
2343 return;
2344 }
2345
2346 foreach ($resultArray as $index => &$values) {
2347 if (!is_array($values)) {
2348 continue;
2349 }
2350 foreach ($values as $key => &$value) {
2351 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2352 if (isset($value['is_error'])) {
2353 // we have a std nested result format
2354 $this->tidyExampleResult($value);
2355 }
2356 else {
2357 foreach ($value as &$nestedResult) {
2358 // this is an alternative syntax for nested results a keyed array of results
2359 $this->tidyExampleResult($nestedResult);
2360 }
2361 }
2362 }
2363 if (in_array($key, $keysToUnset)) {
2364 unset($values[$key]);
2365 break;
2366 }
2367 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2368 $value = $fieldsToChange[$key];
2369 }
2370 if (is_string($value)) {
2371 $value = addslashes($value);
2372 }
2373 }
2374 }
2375 }
2376
2377 /**
2378 * Delete note.
2379 *
2380 * @param array $params
2381 *
2382 * @return array|int
2383 */
2384 public function noteDelete($params) {
2385 return $this->callAPISuccess('Note', 'delete', $params);
2386 }
2387
2388 /**
2389 * Create custom field with Option Values.
2390 *
2391 * @param array $customGroup
2392 * @param string $name
2393 * Name of custom field.
2394 *
2395 * @return array|int
2396 */
2397 public function customFieldOptionValueCreate($customGroup, $name) {
2398 $fieldParams = array(
2399 'custom_group_id' => $customGroup['id'],
2400 'name' => 'test_custom_group',
2401 'label' => 'Country',
2402 'html_type' => 'Select',
2403 'data_type' => 'String',
2404 'weight' => 4,
2405 'is_required' => 1,
2406 'is_searchable' => 0,
2407 'is_active' => 1,
2408 );
2409
2410 $optionGroup = array(
2411 'domain_id' => 1,
2412 'name' => 'option_group1',
2413 'label' => 'option_group_label1',
2414 );
2415
2416 $optionValue = array(
2417 'option_label' => array('Label1', 'Label2'),
2418 'option_value' => array('value1', 'value2'),
2419 'option_name' => array($name . '_1', $name . '_2'),
2420 'option_weight' => array(1, 2),
2421 'option_status' => 1,
2422 );
2423
2424 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2425
2426 return $this->callAPISuccess('custom_field', 'create', $params);
2427 }
2428
2429 /**
2430 * @param $entities
2431 *
2432 * @return bool
2433 */
2434 public function confirmEntitiesDeleted($entities) {
2435 foreach ($entities as $entity) {
2436
2437 $result = $this->callAPISuccess($entity, 'Get', array());
2438 if ($result['error'] == 1 || $result['count'] > 0) {
2439 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2440 return TRUE;
2441 }
2442 }
2443 return FALSE;
2444 }
2445
2446 /**
2447 * Quick clean by emptying tables created for the test.
2448 *
2449 * @param array $tablesToTruncate
2450 * @param bool $dropCustomValueTables
2451 * @throws \Exception
2452 */
2453 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2454 if ($this->tx) {
2455 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2456 }
2457 if ($dropCustomValueTables) {
2458 $optionGroupResult = CRM_Core_DAO::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2459 while ($optionGroupResult->fetch()) {
2460 if (!empty($optionGroupResult->option_group_id)) {
2461 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id);
2462 }
2463 }
2464 $tablesToTruncate[] = 'civicrm_custom_group';
2465 $tablesToTruncate[] = 'civicrm_custom_field';
2466 }
2467
2468 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate, $tablesToTruncate));
2469
2470 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2471 foreach ($tablesToTruncate as $table) {
2472 $sql = "TRUNCATE TABLE $table";
2473 CRM_Core_DAO::executeQuery($sql);
2474 }
2475 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2476
2477 if ($dropCustomValueTables) {
2478 $dbName = self::getDBName();
2479 $query = "
2480 SELECT TABLE_NAME as tableName
2481 FROM INFORMATION_SCHEMA.TABLES
2482 WHERE TABLE_SCHEMA = '{$dbName}'
2483 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2484 ";
2485
2486 $tableDAO = CRM_Core_DAO::executeQuery($query);
2487 while ($tableDAO->fetch()) {
2488 $sql = "DROP TABLE {$tableDAO->tableName}";
2489 CRM_Core_DAO::executeQuery($sql);
2490 }
2491 }
2492 }
2493
2494 /**
2495 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2496 */
2497 public function quickCleanUpFinancialEntities() {
2498 $tablesToTruncate = array(
2499 'civicrm_activity',
2500 'civicrm_activity_contact',
2501 'civicrm_contribution',
2502 'civicrm_contribution_soft',
2503 'civicrm_contribution_product',
2504 'civicrm_financial_trxn',
2505 'civicrm_financial_item',
2506 'civicrm_contribution_recur',
2507 'civicrm_line_item',
2508 'civicrm_contribution_page',
2509 'civicrm_payment_processor',
2510 'civicrm_entity_financial_trxn',
2511 'civicrm_membership',
2512 'civicrm_membership_type',
2513 'civicrm_membership_payment',
2514 'civicrm_membership_log',
2515 'civicrm_membership_block',
2516 'civicrm_event',
2517 'civicrm_participant',
2518 'civicrm_participant_payment',
2519 'civicrm_pledge',
2520 'civicrm_pledge_payment',
2521 'civicrm_price_set_entity',
2522 'civicrm_price_field_value',
2523 'civicrm_price_field',
2524 );
2525 $this->quickCleanup($tablesToTruncate);
2526 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2527 $this->restoreDefaultPriceSetConfig();
2528 $var = TRUE;
2529 CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE);
2530 System::singleton()->flushProcessors();
2531 }
2532
2533 public function restoreDefaultPriceSetConfig() {
2534 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_price_set WHERE id > 2');
2535 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)");
2536 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)");
2537 }
2538 /*
2539 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2540 * Default behaviour is to also delete the entity
2541 * @param array $params
2542 * Params array to check against.
2543 * @param int $id
2544 * Id of the entity concerned.
2545 * @param string $entity
2546 * Name of entity concerned (e.g. membership).
2547 * @param bool $delete
2548 * Should the entity be deleted as part of this check.
2549 * @param string $errorText
2550 * Text to print on error.
2551 */
2552 /**
2553 * @param array $params
2554 * @param int $id
2555 * @param $entity
2556 * @param int $delete
2557 * @param string $errorText
2558 *
2559 * @throws Exception
2560 */
2561 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2562
2563 $result = $this->callAPISuccessGetSingle($entity, array(
2564 'id' => $id,
2565 ));
2566
2567 if ($delete) {
2568 $this->callAPISuccess($entity, 'Delete', array(
2569 'id' => $id,
2570 ));
2571 }
2572 $dateFields = $keys = $dateTimeFields = array();
2573 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2574 foreach ($fields['values'] as $field => $settings) {
2575 if (array_key_exists($field, $result)) {
2576 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = $field;
2577 }
2578 else {
2579 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = CRM_Utils_Array::value('name', $settings, $field);
2580 }
2581 $type = CRM_Utils_Array::value('type', $settings);
2582 if ($type == CRM_Utils_Type::T_DATE) {
2583 $dateFields[] = $settings['name'];
2584 // we should identify both real names & unique names as dates
2585 if ($field != $settings['name']) {
2586 $dateFields[] = $field;
2587 }
2588 }
2589 if ($type == CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) {
2590 $dateTimeFields[] = $settings['name'];
2591 // we should identify both real names & unique names as dates
2592 if ($field != $settings['name']) {
2593 $dateTimeFields[] = $field;
2594 }
2595 }
2596 }
2597
2598 if (strtolower($entity) == 'contribution') {
2599 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2600 // this is not returned in id format
2601 unset($params['payment_instrument_id']);
2602 $params['contribution_source'] = $params['source'];
2603 unset($params['source']);
2604 }
2605
2606 foreach ($params as $key => $value) {
2607 if ($key == 'version' || substr($key, 0, 3) == 'api' || !array_key_exists($keys[$key], $result)) {
2608 continue;
2609 }
2610 if (in_array($key, $dateFields)) {
2611 $value = date('Y-m-d', strtotime($value));
2612 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2613 }
2614 if (in_array($key, $dateTimeFields)) {
2615 $value = date('Y-m-d H:i:s', strtotime($value));
2616 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array::value($keys[$key], $result, CRM_Utils_Array::value($key, $result))));
2617 }
2618 $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);
2619 }
2620 }
2621
2622 /**
2623 * Get formatted values in the actual and expected result.
2624 * @param array $actual
2625 * Actual calculated values.
2626 * @param array $expected
2627 * Expected values.
2628 */
2629 public function checkArrayEquals(&$actual, &$expected) {
2630 self::unsetId($actual);
2631 self::unsetId($expected);
2632 $this->assertEquals($actual, $expected);
2633 }
2634
2635 /**
2636 * Unset the key 'id' from the array
2637 * @param array $unformattedArray
2638 * The array from which the 'id' has to be unset.
2639 */
2640 public static function unsetId(&$unformattedArray) {
2641 $formattedArray = array();
2642 if (array_key_exists('id', $unformattedArray)) {
2643 unset($unformattedArray['id']);
2644 }
2645 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2646 foreach ($unformattedArray['values'] as $key => $value) {
2647 if (is_array($value)) {
2648 foreach ($value as $k => $v) {
2649 if ($k == 'id') {
2650 unset($value[$k]);
2651 }
2652 }
2653 }
2654 elseif ($key == 'id') {
2655 $unformattedArray[$key];
2656 }
2657 $formattedArray = array($value);
2658 }
2659 $unformattedArray['values'] = $formattedArray;
2660 }
2661 }
2662
2663 /**
2664 * Helper to enable/disable custom directory support
2665 *
2666 * @param array $customDirs
2667 * With members:.
2668 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2669 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2670 */
2671 public function customDirectories($customDirs) {
2672 $config = CRM_Core_Config::singleton();
2673
2674 if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
2675 unset($config->customPHPPathDir);
2676 }
2677 elseif ($customDirs['php_path'] === TRUE) {
2678 $config->customPHPPathDir = dirname(dirname(__FILE__)) . '/custom_directories/php/';
2679 }
2680 else {
2681 $config->customPHPPathDir = $php_path;
2682 }
2683
2684 if (empty($customDirs['template_path']) || $customDirs['template_path'] === FALSE) {
2685 unset($config->customTemplateDir);
2686 }
2687 elseif ($customDirs['template_path'] === TRUE) {
2688 $config->customTemplateDir = dirname(dirname(__FILE__)) . '/custom_directories/templates/';
2689 }
2690 else {
2691 $config->customTemplateDir = $template_path;
2692 }
2693 }
2694
2695 /**
2696 * Generate a temporary folder.
2697 *
2698 * @param string $prefix
2699 * @return string
2700 */
2701 public function createTempDir($prefix = 'test-') {
2702 $tempDir = CRM_Utils_File::tempdir($prefix);
2703 $this->tempDirs[] = $tempDir;
2704 return $tempDir;
2705 }
2706
2707 public function cleanTempDirs() {
2708 if (!is_array($this->tempDirs)) {
2709 // fix test errors where this is not set
2710 return;
2711 }
2712 foreach ($this->tempDirs as $tempDir) {
2713 if (is_dir($tempDir)) {
2714 CRM_Utils_File::cleanDir($tempDir, TRUE, FALSE);
2715 }
2716 }
2717 }
2718
2719 /**
2720 * Temporarily replace the singleton extension with a different one.
2721 * @param \CRM_Extension_System $system
2722 */
2723 public function setExtensionSystem(CRM_Extension_System $system) {
2724 if ($this->origExtensionSystem == NULL) {
2725 $this->origExtensionSystem = CRM_Extension_System::singleton();
2726 }
2727 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2728 }
2729
2730 public function unsetExtensionSystem() {
2731 if ($this->origExtensionSystem !== NULL) {
2732 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2733 $this->origExtensionSystem = NULL;
2734 }
2735 }
2736
2737 /**
2738 * Temporarily alter the settings-metadata to add a mock setting.
2739 *
2740 * WARNING: The setting metadata will disappear on the next cache-clear.
2741 *
2742 * @param $extras
2743 * @return void
2744 */
2745 public function setMockSettingsMetaData($extras) {
2746 Civi::service('settings_manager')->flush();
2747
2748 CRM_Utils_Hook::singleton()
2749 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2750 $metadata = array_merge($metadata, $extras);
2751 });
2752
2753 $fields = $this->callAPISuccess('setting', 'getfields', array());
2754 foreach ($extras as $key => $spec) {
2755 $this->assertNotEmpty($spec['title']);
2756 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2757 }
2758 }
2759
2760 /**
2761 * @param string $name
2762 */
2763 public function financialAccountDelete($name) {
2764 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2765 $financialAccount->name = $name;
2766 if ($financialAccount->find(TRUE)) {
2767 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2768 $entityFinancialType->financial_account_id = $financialAccount->id;
2769 $entityFinancialType->delete();
2770 $financialAccount->delete();
2771 }
2772 }
2773
2774 /**
2775 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2776 * (NB unclear if this is still required)
2777 */
2778 public function _sethtmlGlobals() {
2779 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2780 'required' => array(
2781 'html_quickform_rule_required',
2782 'HTML/QuickForm/Rule/Required.php',
2783 ),
2784 'maxlength' => array(
2785 'html_quickform_rule_range',
2786 'HTML/QuickForm/Rule/Range.php',
2787 ),
2788 'minlength' => array(
2789 'html_quickform_rule_range',
2790 'HTML/QuickForm/Rule/Range.php',
2791 ),
2792 'rangelength' => array(
2793 'html_quickform_rule_range',
2794 'HTML/QuickForm/Rule/Range.php',
2795 ),
2796 'email' => array(
2797 'html_quickform_rule_email',
2798 'HTML/QuickForm/Rule/Email.php',
2799 ),
2800 'regex' => array(
2801 'html_quickform_rule_regex',
2802 'HTML/QuickForm/Rule/Regex.php',
2803 ),
2804 'lettersonly' => array(
2805 'html_quickform_rule_regex',
2806 'HTML/QuickForm/Rule/Regex.php',
2807 ),
2808 'alphanumeric' => array(
2809 'html_quickform_rule_regex',
2810 'HTML/QuickForm/Rule/Regex.php',
2811 ),
2812 'numeric' => array(
2813 'html_quickform_rule_regex',
2814 'HTML/QuickForm/Rule/Regex.php',
2815 ),
2816 'nopunctuation' => array(
2817 'html_quickform_rule_regex',
2818 'HTML/QuickForm/Rule/Regex.php',
2819 ),
2820 'nonzero' => array(
2821 'html_quickform_rule_regex',
2822 'HTML/QuickForm/Rule/Regex.php',
2823 ),
2824 'callback' => array(
2825 'html_quickform_rule_callback',
2826 'HTML/QuickForm/Rule/Callback.php',
2827 ),
2828 'compare' => array(
2829 'html_quickform_rule_compare',
2830 'HTML/QuickForm/Rule/Compare.php',
2831 ),
2832 );
2833 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2834 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2835 'group' => array(
2836 'HTML/QuickForm/group.php',
2837 'HTML_QuickForm_group',
2838 ),
2839 'hidden' => array(
2840 'HTML/QuickForm/hidden.php',
2841 'HTML_QuickForm_hidden',
2842 ),
2843 'reset' => array(
2844 'HTML/QuickForm/reset.php',
2845 'HTML_QuickForm_reset',
2846 ),
2847 'checkbox' => array(
2848 'HTML/QuickForm/checkbox.php',
2849 'HTML_QuickForm_checkbox',
2850 ),
2851 'file' => array(
2852 'HTML/QuickForm/file.php',
2853 'HTML_QuickForm_file',
2854 ),
2855 'image' => array(
2856 'HTML/QuickForm/image.php',
2857 'HTML_QuickForm_image',
2858 ),
2859 'password' => array(
2860 'HTML/QuickForm/password.php',
2861 'HTML_QuickForm_password',
2862 ),
2863 'radio' => array(
2864 'HTML/QuickForm/radio.php',
2865 'HTML_QuickForm_radio',
2866 ),
2867 'button' => array(
2868 'HTML/QuickForm/button.php',
2869 'HTML_QuickForm_button',
2870 ),
2871 'submit' => array(
2872 'HTML/QuickForm/submit.php',
2873 'HTML_QuickForm_submit',
2874 ),
2875 'select' => array(
2876 'HTML/QuickForm/select.php',
2877 'HTML_QuickForm_select',
2878 ),
2879 'hiddenselect' => array(
2880 'HTML/QuickForm/hiddenselect.php',
2881 'HTML_QuickForm_hiddenselect',
2882 ),
2883 'text' => array(
2884 'HTML/QuickForm/text.php',
2885 'HTML_QuickForm_text',
2886 ),
2887 'textarea' => array(
2888 'HTML/QuickForm/textarea.php',
2889 'HTML_QuickForm_textarea',
2890 ),
2891 'fckeditor' => array(
2892 'HTML/QuickForm/fckeditor.php',
2893 'HTML_QuickForm_FCKEditor',
2894 ),
2895 'tinymce' => array(
2896 'HTML/QuickForm/tinymce.php',
2897 'HTML_QuickForm_TinyMCE',
2898 ),
2899 'dojoeditor' => array(
2900 'HTML/QuickForm/dojoeditor.php',
2901 'HTML_QuickForm_dojoeditor',
2902 ),
2903 'link' => array(
2904 'HTML/QuickForm/link.php',
2905 'HTML_QuickForm_link',
2906 ),
2907 'advcheckbox' => array(
2908 'HTML/QuickForm/advcheckbox.php',
2909 'HTML_QuickForm_advcheckbox',
2910 ),
2911 'date' => array(
2912 'HTML/QuickForm/date.php',
2913 'HTML_QuickForm_date',
2914 ),
2915 'static' => array(
2916 'HTML/QuickForm/static.php',
2917 'HTML_QuickForm_static',
2918 ),
2919 'header' => array(
2920 'HTML/QuickForm/header.php',
2921 'HTML_QuickForm_header',
2922 ),
2923 'html' => array(
2924 'HTML/QuickForm/html.php',
2925 'HTML_QuickForm_html',
2926 ),
2927 'hierselect' => array(
2928 'HTML/QuickForm/hierselect.php',
2929 'HTML_QuickForm_hierselect',
2930 ),
2931 'autocomplete' => array(
2932 'HTML/QuickForm/autocomplete.php',
2933 'HTML_QuickForm_autocomplete',
2934 ),
2935 'xbutton' => array(
2936 'HTML/QuickForm/xbutton.php',
2937 'HTML_QuickForm_xbutton',
2938 ),
2939 'advmultiselect' => array(
2940 'HTML/QuickForm/advmultiselect.php',
2941 'HTML_QuickForm_advmultiselect',
2942 ),
2943 );
2944 }
2945
2946 /**
2947 * Set up an acl allowing contact to see 2 specified groups
2948 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2949 *
2950 * You need to have pre-created these groups & created the user e.g
2951 * $this->createLoggedInUser();
2952 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2953 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2954 *
2955 * @param bool $isProfile
2956 */
2957 public function setupACL($isProfile = FALSE) {
2958 global $_REQUEST;
2959 $_REQUEST = $this->_params;
2960
2961 CRM_Core_Config::singleton()->userPermissionClass->permissions = array('access CiviCRM');
2962 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2963 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2964 'option_group_id' => $optionGroupID,
2965 'label' => 'pick me',
2966 'value' => 55,
2967 ));
2968
2969 CRM_Core_DAO::executeQuery("
2970 TRUNCATE civicrm_acl_cache
2971 ");
2972
2973 CRM_Core_DAO::executeQuery("
2974 TRUNCATE civicrm_acl_contact_cache
2975 ");
2976
2977 CRM_Core_DAO::executeQuery("
2978 INSERT INTO civicrm_acl_entity_role (
2979 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2980 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2981 ");
2982
2983 if ($isProfile) {
2984 CRM_Core_DAO::executeQuery("
2985 INSERT INTO civicrm_acl (
2986 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2987 )
2988 VALUES (
2989 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2990 );
2991 ");
2992 }
2993 else {
2994 CRM_Core_DAO::executeQuery("
2995 INSERT INTO civicrm_acl (
2996 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2997 )
2998 VALUES (
2999 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3000 );
3001 ");
3002
3003 CRM_Core_DAO::executeQuery("
3004 INSERT INTO civicrm_acl (
3005 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3006 )
3007 VALUES (
3008 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3009 );
3010 ");
3011 }
3012
3013 $this->_loggedInUser = CRM_Core_Session::singleton()->get('userID');
3014 $this->callAPISuccess('group_contact', 'create', array(
3015 'group_id' => $this->_permissionedGroup,
3016 'contact_id' => $this->_loggedInUser,
3017 ));
3018
3019 if (!$isProfile) {
3020 //flush cache
3021 CRM_ACL_BAO_Cache::resetCache();
3022 CRM_Contact_BAO_Group::getPermissionClause(TRUE);
3023 CRM_ACL_API::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3024 }
3025 }
3026
3027 /**
3028 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3029 */
3030 public function offsetDefaultPriceSet() {
3031 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3032 $firstID = $contributionPriceSet['id'];
3033 $this->callAPISuccess('price_set', 'create', array(
3034 'id' => $contributionPriceSet['id'],
3035 'is_active' => 0,
3036 'name' => 'old',
3037 ));
3038 unset($contributionPriceSet['id']);
3039 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3040 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3041 'price_set_id' => $firstID,
3042 'options' => array('limit' => 1),
3043 ));
3044 unset($priceField['id']);
3045 $priceField['price_set_id'] = $newPriceSet['id'];
3046 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3047 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3048 'price_set_id' => $firstID,
3049 'sequential' => 1,
3050 'options' => array('limit' => 1),
3051 ));
3052
3053 unset($priceFieldValue['id']);
3054 //create some padding to use up ids
3055 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3056 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3057 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3058 }
3059
3060 /**
3061 * Create an instance of the paypal processor.
3062 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3063 * this parent class & we don't have a structure for that yet
3064 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3065 * & the best protection against that is the functions this class affords
3066 * @param array $params
3067 * @return int $result['id'] payment processor id
3068 */
3069 public function paymentProcessorCreate($params = array()) {
3070 $params = array_merge(array(
3071 'name' => 'demo',
3072 'domain_id' => CRM_Core_Config::domainID(),
3073 'payment_processor_type_id' => 'PayPal',
3074 'is_active' => 1,
3075 'is_default' => 0,
3076 'is_test' => 1,
3077 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3078 'password' => '1183377788',
3079 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3080 'url_site' => 'https://www.sandbox.paypal.com/',
3081 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3082 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3083 'class_name' => 'Payment_PayPalImpl',
3084 'billing_mode' => 3,
3085 'financial_type_id' => 1,
3086 'financial_account_id' => 12,
3087 ),
3088 $params);
3089 if (!is_numeric($params['payment_processor_type_id'])) {
3090 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3091 //here
3092 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3093 'name' => $params['payment_processor_type_id'],
3094 'return' => 'id',
3095 ), 'integer');
3096 }
3097 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3098 return $result['id'];
3099 }
3100
3101 /**
3102 * Set up initial recurring payment allowing subsequent IPN payments.
3103 */
3104 public function setupRecurringPaymentProcessorTransaction($params = array()) {
3105 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
3106 'contact_id' => $this->_contactID,
3107 'amount' => 1000,
3108 'sequential' => 1,
3109 'installments' => 5,
3110 'frequency_unit' => 'Month',
3111 'frequency_interval' => 1,
3112 'invoice_id' => $this->_invoiceID,
3113 'contribution_status_id' => 2,
3114 'payment_processor_id' => $this->_paymentProcessorID,
3115 // processor provided ID - use contact ID as proxy.
3116 'processor_id' => $this->_contactID,
3117 'api.contribution.create' => array(
3118 'total_amount' => '200',
3119 'invoice_id' => $this->_invoiceID,
3120 'financial_type_id' => 1,
3121 'contribution_status_id' => 'Pending',
3122 'contact_id' => $this->_contactID,
3123 'contribution_page_id' => $this->_contributionPageID,
3124 'payment_processor_id' => $this->_paymentProcessorID,
3125 'is_test' => 0,
3126 ),
3127 ), $params));
3128 $this->_contributionRecurID = $contributionRecur['id'];
3129 $this->_contributionID = $contributionRecur['values']['0']['api.contribution.create']['id'];
3130 }
3131
3132 /**
3133 * 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
3134 */
3135 public function setupMembershipRecurringPaymentProcessorTransaction() {
3136 $this->ids['membership_type'] = $this->membershipTypeCreate();
3137 //create a contribution so our membership & contribution don't both have id = 1
3138 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
3139 $this->contributionCreate(array(
3140 'contact_id' => $this->_contactID,
3141 'is_test' => 1,
3142 'financial_type_id' => 1,
3143 'invoice_id' => 'abcd',
3144 'trxn_id' => 345,
3145 ));
3146 }
3147 $this->setupRecurringPaymentProcessorTransaction();
3148
3149 $this->ids['membership'] = $this->callAPISuccess('membership', 'create', array(
3150 'contact_id' => $this->_contactID,
3151 'membership_type_id' => $this->ids['membership_type'],
3152 'contribution_recur_id' => $this->_contributionRecurID,
3153 'format.only_id' => TRUE,
3154 ));
3155 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3156 CRM_Core_DAO::executeQuery("TRUNCATE civicrm_line_item");
3157
3158 $this->callAPISuccess('line_item', 'create', array(
3159 'entity_table' => 'civicrm_membership',
3160 'entity_id' => $this->ids['membership'],
3161 'contribution_id' => $this->_contributionID,
3162 'label' => 'General',
3163 'qty' => 1,
3164 'unit_price' => 200,
3165 'line_total' => 200,
3166 'financial_type_id' => 1,
3167 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3168 'return' => 'id',
3169 'label' => 'Membership Amount',
3170 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3171 )),
3172 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3173 'return' => 'id',
3174 'label' => 'General',
3175 'options' => array('limit' => 1, 'sort' => 'id DESC'),
3176 )),
3177 ));
3178 $this->callAPISuccess('membership_payment', 'create', array(
3179 'contribution_id' => $this->_contributionID,
3180 'membership_id' => $this->ids['membership'],
3181 ));
3182 }
3183
3184 /**
3185 * @param $message
3186 *
3187 * @throws Exception
3188 */
3189 public function CiviUnitTestCase_fatalErrorHandler($message) {
3190 throw new Exception("{$message['message']}: {$message['code']}");
3191 }
3192
3193 /**
3194 * Helper function to create new mailing.
3195 * @return mixed
3196 */
3197 public function createMailing() {
3198 $params = array(
3199 'subject' => 'maild' . rand(),
3200 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
3201 'name' => 'mailing name' . rand(),
3202 'created_id' => 1,
3203 );
3204
3205 $result = $this->callAPISuccess('Mailing', 'create', $params);
3206 return $result['id'];
3207 }
3208
3209 /**
3210 * Helper function to delete mailing.
3211 * @param $id
3212 */
3213 public function deleteMailing($id) {
3214 $params = array(
3215 'id' => $id,
3216 );
3217
3218 $this->callAPISuccess('Mailing', 'delete', $params);
3219 }
3220
3221 /**
3222 * Wrap the entire test case in a transaction.
3223 *
3224 * Only subsequent DB statements will be wrapped in TX -- this cannot
3225 * retroactively wrap old DB statements. Therefore, it makes sense to
3226 * call this at the beginning of setUp().
3227 *
3228 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3229 * this option does not work with, e.g., custom-data.
3230 *
3231 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3232 * if TRUNCATE or ALTER is called while using a transaction.
3233 *
3234 * @param bool $nest
3235 * Whether to use nesting or reference-counting.
3236 */
3237 public function useTransaction($nest = TRUE) {
3238 if (!$this->tx) {
3239 $this->tx = new CRM_Core_Transaction($nest);
3240 $this->tx->rollback();
3241 }
3242 }
3243
3244 /**
3245 * Assert the attachment exists.
3246 *
3247 * @param bool $exists
3248 * @param array $apiResult
3249 */
3250 protected function assertAttachmentExistence($exists, $apiResult) {
3251 $fileId = $apiResult['id'];
3252 $this->assertTrue(is_numeric($fileId));
3253 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3254 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3255 1 => array($fileId, 'Int'),
3256 ));
3257 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3258 1 => array($fileId, 'Int'),
3259 ));
3260 }
3261
3262 /**
3263 * Create a price set for an event.
3264 *
3265 * @param int $feeTotal
3266 *
3267 * @return int
3268 * Price Set ID.
3269 */
3270 protected function eventPriceSetCreate($feeTotal) {
3271 // creating price set, price field
3272 $paramsSet['title'] = 'Price Set';
3273 $paramsSet['name'] = CRM_Utils_String::titleToVar('Price Set');
3274 $paramsSet['is_active'] = FALSE;
3275 $paramsSet['extends'] = 1;
3276
3277 $priceset = CRM_Price_BAO_PriceSet::create($paramsSet);
3278 $priceSetId = $priceset->id;
3279
3280 //Checking for priceset added in the table.
3281 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3282 'id', $paramsSet['title'], 'Check DB for created priceset'
3283 );
3284 $paramsField = array(
3285 'label' => 'Price Field',
3286 'name' => CRM_Utils_String::titleToVar('Price Field'),
3287 'html_type' => 'Text',
3288 'price' => $feeTotal,
3289 'option_label' => array('1' => 'Price Field'),
3290 'option_value' => array('1' => $feeTotal),
3291 'option_name' => array('1' => $feeTotal),
3292 'option_weight' => array('1' => 1),
3293 'option_amount' => array('1' => 1),
3294 'is_display_amounts' => 1,
3295 'weight' => 1,
3296 'options_per_line' => 1,
3297 'is_active' => array('1' => 1),
3298 'price_set_id' => $priceset->id,
3299 'is_enter_qty' => 1,
3300 'financial_type_id' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
3301 );
3302 CRM_Price_BAO_PriceField::create($paramsField);
3303
3304 return $priceSetId;
3305 }
3306
3307 /**
3308 * Add a profile to a contribution page.
3309 *
3310 * @param string $name
3311 * @param int $contributionPageID
3312 */
3313 protected function addProfile($name, $contributionPageID) {
3314 $this->callAPISuccess('UFJoin', 'create', array(
3315 'uf_group_id' => $name,
3316 'module' => 'CiviContribute',
3317 'entity_table' => 'civicrm_contribution_page',
3318 'entity_id' => $contributionPageID,
3319 'weight' => 1,
3320 ));
3321 }
3322
3323 /**
3324 * Add participant with contribution
3325 *
3326 * @return array
3327 */
3328 protected function createParticipantWithContribution() {
3329 // creating price set, price field
3330 $this->_contactId = Contact::createIndividual();
3331 $this->_eventId = Event::create($this->_contactId);
3332 $eventParams = array(
3333 'id' => $this->_eventId,
3334 'financial_type_id' => 4,
3335 'is_monetary' => 1,
3336 );
3337 $this->callAPISuccess('event', 'create', $eventParams);
3338 $priceFields = $this->createPriceSet('event', $this->_eventId);
3339 $participantParams = array(
3340 'financial_type_id' => 4,
3341 'event_id' => $this->_eventId,
3342 'role_id' => 1,
3343 'status_id' => 14,
3344 'fee_currency' => 'USD',
3345 'contact_id' => $this->_contactId,
3346 );
3347 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3348 $contributionParams = array(
3349 'total_amount' => 150,
3350 'currency' => 'USD',
3351 'contact_id' => $this->_contactId,
3352 'financial_type_id' => 4,
3353 'contribution_status_id' => 1,
3354 'partial_payment_total' => 300.00,
3355 'partial_amount_pay' => 150,
3356 'contribution_mode' => 'participant',
3357 'participant_id' => $participant['id'],
3358 );
3359 foreach ($priceFields['values'] as $key => $priceField) {
3360 $lineItems[1][$key] = array(
3361 'price_field_id' => $priceField['price_field_id'],
3362 'price_field_value_id' => $priceField['id'],
3363 'label' => $priceField['label'],
3364 'field_title' => $priceField['label'],
3365 'qty' => 1,
3366 'unit_price' => $priceField['amount'],
3367 'line_total' => $priceField['amount'],
3368 'financial_type_id' => $priceField['financial_type_id'],
3369 );
3370 }
3371 $contributionParams['line_item'] = $lineItems;
3372 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3373 $paymentParticipant = array(
3374 'participant_id' => $participant['id'],
3375 'contribution_id' => $contribution['id'],
3376 );
3377 $ids = array();
3378 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3379 return array($lineItems, $contribution);
3380 }
3381
3382 /**
3383 * Create price set
3384 *
3385 * @param string $component
3386 * @param int $componentId
3387 *
3388 * @return array
3389 */
3390 protected function createPriceSet($component = 'contribution_page', $componentId = NULL) {
3391 $paramsSet['title'] = 'Price Set';
3392 $paramsSet['name'] = CRM_Utils_String::titleToVar('Price Set');
3393 $paramsSet['is_active'] = TRUE;
3394 $paramsSet['financial_type_id'] = 4;
3395 $paramsSet['extends'] = 1;
3396 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3397 $priceSetId = $priceSet['id'];
3398 //Checking for priceset added in the table.
3399 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3400 'id', $paramsSet['title'], 'Check DB for created priceset'
3401 );
3402 $paramsField = array(
3403 'label' => 'Price Field',
3404 'name' => CRM_Utils_String::titleToVar('Price Field'),
3405 'html_type' => 'CheckBox',
3406 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3407 'option_value' => array('1' => 100, '2' => 200),
3408 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3409 'option_weight' => array('1' => 1, '2' => 2),
3410 'option_amount' => array('1' => 100, '2' => 200),
3411 'is_display_amounts' => 1,
3412 'weight' => 1,
3413 'options_per_line' => 1,
3414 'is_active' => array('1' => 1, '2' => 1),
3415 'price_set_id' => $priceSet['id'],
3416 'is_enter_qty' => 1,
3417 'financial_type_id' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
3418 );
3419 $priceField = CRM_Price_BAO_PriceField::create($paramsField);
3420 if ($componentId) {
3421 CRM_Price_BAO_PriceSet::addTo('civicrm_' . $component, $componentId, $priceSetId);
3422 }
3423 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id));
3424 }
3425
3426 /**
3427 * Replace the template with a test-oriented template designed to show all the variables.
3428 *
3429 * @param string $templateName
3430 */
3431 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
3432 $testTemplate = file_get_contents(__DIR__ . '/../../templates/message_templates/' . $templateName . '_html.tpl');
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 SET m.msg_html = '{$testTemplate}'
3438 WHERE og.name = 'msg_tpl_workflow_contribution'
3439 AND ov.name = '{$templateName}'
3440 AND m.is_default = 1"
3441 );
3442 }
3443
3444 /**
3445 * Reinstate the default template.
3446 *
3447 * @param string $templateName
3448 */
3449 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
3450 CRM_Core_DAO::executeQuery(
3451 "UPDATE civicrm_option_group og
3452 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3453 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3454 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
3455 SET m.msg_html = m2.msg_html
3456 WHERE og.name = 'msg_tpl_workflow_contribution'
3457 AND ov.name = '{$templateName}'
3458 AND m.is_default = 1"
3459 );
3460 }
3461
3462 /**
3463 * Flush statics relating to financial type.
3464 */
3465 protected function flushFinancialTypeStatics() {
3466 if (isset(\Civi::$statics['CRM_Financial_BAO_FinancialType'])) {
3467 unset(\Civi::$statics['CRM_Financial_BAO_FinancialType']);
3468 }
3469 if (isset(\Civi::$statics['CRM_Contribute_PseudoConstant'])) {
3470 unset(\Civi::$statics['CRM_Contribute_PseudoConstant']);
3471 }
3472 CRM_Contribute_PseudoConstant::flush('financialType');
3473 CRM_Contribute_PseudoConstant::flush('membershipType');
3474 // Pseudoconstants may be saved to the cache table.
3475 CRM_Core_DAO::executeQuery("TRUNCATE civicrm_cache");
3476 CRM_Financial_BAO_FinancialType::$_statusACLFt = array();
3477 CRM_Financial_BAO_FinancialType::$_availableFinancialTypes = NULL;
3478 }
3479
3480 /**
3481 * Set the permissions to the supplied array.
3482 *
3483 * @param array $permissions
3484 */
3485 protected function setPermissions($permissions) {
3486 CRM_Core_Config::singleton()->userPermissionClass->permissions = $permissions;
3487 $this->flushFinancialTypeStatics();
3488 CRM_Contact_BAO_Group::getPermissionClause(TRUE);
3489 }
3490
3491 /**
3492 * @param array $params
3493 * @param $context
3494 */
3495 public function _checkFinancialRecords($params, $context) {
3496 $entityParams = array(
3497 'entity_id' => $params['id'],
3498 'entity_table' => 'civicrm_contribution',
3499 );
3500 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3501 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3502 if ($context == 'pending') {
3503 $trxn = CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams);
3504 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3505 return;
3506 }
3507 $trxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
3508 $trxnParams = array(
3509 'id' => $trxn['financial_trxn_id'],
3510 );
3511 if ($context != 'online' && $context != 'payLater') {
3512 $compareParams = array(
3513 'to_financial_account_id' => 6,
3514 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3515 'status_id' => 1,
3516 );
3517 }
3518 if ($context == 'feeAmount') {
3519 $compareParams['fee_amount'] = 50;
3520 }
3521 elseif ($context == 'online') {
3522 $compareParams = array(
3523 'to_financial_account_id' => 12,
3524 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3525 'status_id' => 1,
3526 'payment_instrument_id' => 1,
3527 );
3528 }
3529 elseif ($context == 'payLater') {
3530 $compareParams = array(
3531 'to_financial_account_id' => 7,
3532 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3533 'status_id' => 2,
3534 );
3535 }
3536 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3537 $entityParams = array(
3538 'financial_trxn_id' => $trxn['financial_trxn_id'],
3539 'entity_table' => 'civicrm_financial_item',
3540 );
3541 $entityTrxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
3542 $fitemParams = array(
3543 'id' => $entityTrxn['entity_id'],
3544 );
3545 $compareParams = array(
3546 'amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3547 'status_id' => 1,
3548 'financial_account_id' => CRM_Utils_Array::value('financial_account_id', $params, 1),
3549 );
3550 if ($context == 'payLater') {
3551 $compareParams = array(
3552 'amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3553 'status_id' => 3,
3554 'financial_account_id' => CRM_Utils_Array::value('financial_account_id', $params, 1),
3555 );
3556 }
3557 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3558 if ($context == 'feeAmount') {
3559 $maxParams = array(
3560 'entity_id' => $params['id'],
3561 'entity_table' => 'civicrm_contribution',
3562 );
3563 $maxTrxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($maxParams, TRUE));
3564 $trxnParams = array(
3565 'id' => $maxTrxn['financial_trxn_id'],
3566 );
3567 $compareParams = array(
3568 'to_financial_account_id' => 5,
3569 'from_financial_account_id' => 6,
3570 'total_amount' => 50,
3571 'status_id' => 1,
3572 );
3573 $trxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['id'], 'DESC');
3574 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3575 $fitemParams = array(
3576 'entity_id' => $trxnId['financialTrxnId'],
3577 'entity_table' => 'civicrm_financial_trxn',
3578 );
3579 $compareParams = array(
3580 'amount' => 50,
3581 'status_id' => 1,
3582 'financial_account_id' => 5,
3583 );
3584 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3585 }
3586 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3587 // line should be copied into all the functions that call this function & evaluated there
3588 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3589 // when calling completeTransaction or repeatTransaction.
3590 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
3591 }
3592
3593 }