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