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