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