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