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