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