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