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