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