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