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