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