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