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