Merge pull request #11638 from ixiam/CRM-21343
[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 class definitions
33 */
6a488035 34require_once 'api/api.php';
6a488035
TO
35define('API_LATEST_VERSION', 3);
36
37/**
38 * Base class for CiviCRM unit tests
39 *
d67f1f28
TO
40 * This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
41 * may opt for one or neither:
42 *
43 * 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
44 * as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
45 * be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
46 * 2. useTransaction() executes the test inside a transaction. It's easier to use
47 * (because you don't need to identify specific tables), but it doesn't work for tests
48 * which manipulate schema or truncate data -- and could behave inconsistently
49 * for tests which specifically examine DB transactions.
50 *
6a488035
TO
51 * Common functions for unit tests
52 * @package CiviCRM
53 */
54class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
55
f6722559 56 /**
100fef9d 57 * Api version - easier to override than just a define
f6722559 58 */
59 protected $_apiversion = API_LATEST_VERSION;
6a488035 60 /**
eceb18cc 61 * Database has been initialized.
6a488035
TO
62 *
63 * @var boolean
64 */
65 private static $dbInit = FALSE;
66
67 /**
eceb18cc 68 * Database connection.
6a488035
TO
69 *
70 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
71 */
72 protected $_dbconn;
73
74 /**
eceb18cc 75 * The database name.
6a488035
TO
76 *
77 * @var string
78 */
79 static protected $_dbName;
80
0b6f58fa 81 /**
eceb18cc 82 * Track tables we have modified during a test.
0b6f58fa
ARW
83 */
84 protected $_tablesToTruncate = array();
85
6a488035
TO
86 /**
87 * @var array of temporary directory names
88 */
89 protected $tempDirs;
90
6a488035
TO
91 /**
92 * @var boolean populateOnce allows to skip db resets in setUp
93 *
94 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
95 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
96 * "CHECK RUNS" ONLY!
97 *
98 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
99 *
100 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
101 */
102 public static $populateOnce = FALSE;
103
6a488035
TO
104 /**
105 * @var boolean DBResetRequired allows skipping DB reset
106 * in specific test case. If you still need
107 * to reset single test (method) of such case, call
108 * $this->cleanDB() in the first line of this
109 * test (method).
110 */
111 public $DBResetRequired = TRUE;
112
d67f1f28
TO
113 /**
114 * @var CRM_Core_Transaction|NULL
115 */
116 private $tx = NULL;
117
6c466b51
EM
118 /**
119 * @var CRM_Utils_Hook_UnitTests hookClass
120 * example of setting a method for a hook
121 * $this->hookClass->setHook('civicrm_aclWhereClause', array($this, 'aclWhereHookAllResults'));
122 */
123 public $hookClass = NULL;
124
125 /**
126 * @var array common values to be re-used multiple times within a class - usually to create the relevant entity
127 */
128 protected $_params = array();
129
130 /**
131 * @var CRM_Extension_System
132 */
133 protected $origExtensionSystem;
134
204beda3 135 /**
136 * Array of IDs created during test setup routine.
137 *
138 * The cleanUpSetUpIds method can be used to clear these at the end of the test.
139 *
140 * @var array
141 */
142 public $setupIDs = array();
143
6a488035 144 /**
eceb18cc 145 * Constructor.
6a488035
TO
146 *
147 * Because we are overriding the parent class constructor, we
148 * need to show the same arguments as exist in the constructor of
149 * PHPUnit_Framework_TestCase, since
150 * PHPUnit_Framework_TestSuite::createTest() creates a
151 * ReflectionClass of the Test class and checks the constructor
152 * of that class to decide how to set up the test.
153 *
e16033b4
TO
154 * @param string $name
155 * @param array $data
156 * @param string $dataName
6a488035 157 */
00be9182 158 public function __construct($name = NULL, array$data = array(), $dataName = '') {
6a488035
TO
159 parent::__construct($name, $data, $dataName);
160
161 // we need full error reporting
162 error_reporting(E_ALL & ~E_NOTICE);
163
f3e16511 164 self::$_dbName = self::getDBName();
6a488035 165
6a488035
TO
166 // also load the class loader
167 require_once 'CRM/Core/ClassLoader.php';
168 CRM_Core_ClassLoader::singleton()->register();
a130e045
DG
169 if (function_exists('_civix_phpunit_setUp')) {
170 // FIXME: loosen coupling
6a488035
TO
171 _civix_phpunit_setUp();
172 }
173 }
174
f0be539a
EM
175 /**
176 * Override to run the test and assert its state.
177 * @return mixed
178 * @throws \Exception
179 * @throws \PHPUnit_Framework_IncompleteTest
180 * @throws \PHPUnit_Framework_SkippedTest
181 */
2e90bf37
TO
182 protected function runTest() {
183 try {
184 return parent::runTest();
5896d037
TO
185 }
186 catch (PEAR_Exception $e) {
2e90bf37
TO
187 // PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
188 throw new Exception(\CRM_Core_Error::formatTextException($e), $e->getCode());
189 }
190 }
191
4cbe18b8
EM
192 /**
193 * @return bool
194 */
00be9182 195 public function requireDBReset() {
6a488035
TO
196 return $this->DBResetRequired;
197 }
198
4cbe18b8
EM
199 /**
200 * @return string
201 */
00be9182 202 public static function getDBName() {
f3e16511 203 static $dbName = NULL;
649d6dd0 204 if ($dbName === NULL) {
f3e16511
TO
205 require_once "DB.php";
206 $dsninfo = DB::parseDSN(CIVICRM_DSN);
207 $dbName = $dsninfo['database'];
208 }
6a488035
TO
209 return $dbName;
210 }
211
212 /**
eceb18cc 213 * Create database connection for this instance.
6a488035
TO
214 *
215 * Initialize the test database if it hasn't been initialized
216 *
217 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
218 */
219 protected function getConnection() {
220 $dbName = self::$_dbName;
221 if (!self::$dbInit) {
222 $dbName = self::getDBName();
223
224 // install test database
225 echo PHP_EOL . "Installing {$dbName} database" . PHP_EOL;
226
99117745 227 static::_populateDB(FALSE, $this);
6a488035
TO
228
229 self::$dbInit = TRUE;
230 }
bc560b0a 231
728bbd5b 232 return $this->createDefaultDBConnection(Civi\Test::pdo(), $dbName);
6a488035
TO
233 }
234
235 /**
eceb18cc 236 * Required implementation of abstract method.
6a488035
TO
237 */
238 protected function getDataSet() {
239 }
240
99117745
TO
241 /**
242 * @param bool $perClass
243 * @param null $object
a6c01b45
CW
244 * @return bool
245 * TRUE if the populate logic runs; FALSE if it is skipped
99117745
TO
246 */
247 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
8582a9fc 248 if (CIVICRM_UF !== 'UnitTests') {
cdc44255 249 throw new \RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
8582a9fc 250 }
6a488035
TO
251
252 if ($perClass || $object == NULL) {
253 $dbreset = TRUE;
254 }
255 else {
256 $dbreset = $object->requireDBReset();
257 }
258
259 if (self::$populateOnce || !$dbreset) {
99117745 260 return FALSE;
6a488035
TO
261 }
262 self::$populateOnce = NULL;
263
728bbd5b 264 Civi\Test::data()->populate();
be709432
TO
265
266 return TRUE;
6a488035
TO
267 }
268
269 public static function setUpBeforeClass() {
99117745 270 static::_populateDB(TRUE);
6a488035
TO
271
272 // also set this global hack
273 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
274 }
275
276 /**
eceb18cc 277 * Common setup functions for all unit tests.
6a488035
TO
278 */
279 protected function setUp() {
4db17da0
TO
280 $session = CRM_Core_Session::singleton();
281 $session->set('userID', NULL);
282
6a488035
TO
283 $this->errorScope = CRM_Core_TemporaryErrorScope::useException(); // REVERT
284 // Use a temporary file for STDIN
285 $GLOBALS['stdin'] = tmpfile();
286 if ($GLOBALS['stdin'] === FALSE) {
287 echo "Couldn't open temporary file\n";
288 exit(1);
289 }
290
291 // Get and save a connection to the database
292 $this->_dbconn = $this->getConnection();
293
294 // reload database before each test
295 // $this->_populateDB();
296
297 // "initialize" CiviCRM to avoid problems when running single tests
298 // FIXME: look at it closer in second stage
299
c0a1f187
TO
300 $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
301 $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
6a488035
TO
302
303 // disable any left-over test extensions
304 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
305
306 // reset all the caches
307 CRM_Utils_System::flushCache();
308
c0a1f187
TO
309 // initialize the object once db is loaded
310 \Civi::reset();
311 $config = CRM_Core_Config::singleton(TRUE, TRUE); // ugh, performance
312
313 // when running unit tests, use mockup user framework
edbcbd96 314 $this->hookClass = CRM_Utils_Hook::singleton();
c0a1f187 315
26684821
TO
316 // Make sure the DB connection is setup properly
317 $config->userSystem->setMySQLTimeZone();
a8de1c22 318 $env = new CRM_Utils_Check_Component_Env();
26684821
TO
319 CRM_Utils_Check::singleton()->assertValid($env->checkMysqlTime());
320
6a488035 321 // clear permissions stub to not check permissions
6a488035
TO
322 $config->userPermissionClass->permissions = NULL;
323
324 //flush component settings
325 CRM_Core_Component::getEnabledComponents(TRUE);
326
c3d574fc
EM
327 error_reporting(E_ALL);
328
d58b453e 329 $this->_sethtmlGlobals();
6a488035
TO
330 }
331
0b6f58fa 332 /**
eceb18cc 333 * Read everything from the datasets directory and insert into the db.
0b6f58fa
ARW
334 */
335 public function loadAllFixtures() {
336 $fixturesDir = __DIR__ . '/../../fixtures';
337
338 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
339
340 $xmlFiles = glob($fixturesDir . '/*.xml');
341 foreach ($xmlFiles as $xmlFixture) {
342 $op = new PHPUnit_Extensions_Database_Operation_Insert();
bbfd46a5 343 $dataset = $this->createXMLDataSet($xmlFixture);
0b6f58fa
ARW
344 $this->_tablesToTruncate = array_merge($this->_tablesToTruncate, $dataset->getTableNames());
345 $op->execute($this->_dbconn, $dataset);
346 }
347
348 $yamlFiles = glob($fixturesDir . '/*.yaml');
349 foreach ($yamlFiles as $yamlFixture) {
350 $op = new PHPUnit_Extensions_Database_Operation_Insert();
351 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
352 $this->_tablesToTruncate = array_merge($this->_tablesToTruncate, $dataset->getTableNames());
353 $op->execute($this->_dbconn, $dataset);
354 }
355
356 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
357 }
358
6a488035 359 /**
eceb18cc 360 * Emulate a logged in user since certain functions use that.
6a488035
TO
361 * value to store a record in the DB (like activity)
362 * CRM-8180
5fc991dd
EM
363 *
364 * @return int
365 * Contact ID of the created user.
6a488035
TO
366 */
367 public function createLoggedInUser() {
368 $params = array(
369 'first_name' => 'Logged In',
370 'last_name' => 'User ' . rand(),
371 'contact_type' => 'Individual',
372 );
373 $contactID = $this->individualCreate($params);
5fc991dd
EM
374 $this->callAPISuccess('UFMatch', 'create', array(
375 'contact_id' => $contactID,
376 'uf_name' => 'superman',
377 'uf_id' => 6,
378 ));
6a488035
TO
379
380 $session = CRM_Core_Session::singleton();
381 $session->set('userID', $contactID);
5fc991dd 382 return $contactID;
6a488035
TO
383 }
384
5767aa07 385 /**
eceb18cc 386 * Create default domain contacts for the two domains added during test class.
5767aa07
AN
387 * database population.
388 */
389 public function createDomainContacts() {
1ca22999 390 $this->organizationCreate();
391 $this->organizationCreate(array('organization_name' => 'Second Domain'));
5767aa07
AN
392 }
393
6a488035 394 /**
eceb18cc 395 * Common teardown functions for all unit tests.
6a488035
TO
396 */
397 protected function tearDown() {
398 error_reporting(E_ALL & ~E_NOTICE);
6c466b51
EM
399 CRM_Utils_Hook::singleton()->reset();
400 $this->hookClass->reset();
9ce07588
TO
401 $session = CRM_Core_Session::singleton();
402 $session->set('userID', NULL);
d67f1f28
TO
403
404 if ($this->tx) {
405 $this->tx->rollback()->commit();
406 $this->tx = NULL;
407
408 CRM_Core_Transaction::forceRollbackIfEnabled();
409 \Civi\Core\Transaction\Manager::singleton(TRUE);
5896d037
TO
410 }
411 else {
d67f1f28
TO
412 CRM_Core_Transaction::forceRollbackIfEnabled();
413 \Civi\Core\Transaction\Manager::singleton(TRUE);
414
225d474b 415 $tablesToTruncate = array('civicrm_contact', 'civicrm_uf_match');
d67f1f28 416 $this->quickCleanup($tablesToTruncate);
a335f6b2 417 $this->createDomainContacts();
d67f1f28
TO
418 }
419
6a488035
TO
420 $this->cleanTempDirs();
421 $this->unsetExtensionSystem();
422 }
423
6a488035 424 /**
eceb18cc 425 * Generic function to compare expected values after an api call to retrieved.
6a488035
TO
426 * DB values.
427 *
428 * @daoName string DAO Name of object we're evaluating.
429 * @id int Id of object
430 * @match array Associative array of field name => expected value. Empty if asserting
431 * that a DELETE occurred
432 * @delete boolean True if we're checking that a DELETE action occurred.
1e1fdcf6
EM
433 * @param $daoName
434 * @param $id
435 * @param $match
436 * @param bool $delete
437 * @throws \PHPUnit_Framework_AssertionFailedError
6a488035 438 */
00be9182 439 public function assertDBState($daoName, $id, $match, $delete = FALSE) {
6a488035
TO
440 if (empty($id)) {
441 // adding this here since developers forget to check for an id
442 // and hence we get the first value in the db
443 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
444 }
445
4d5c2eb5 446 $object = new $daoName();
6a488035
TO
447 $object->id = $id;
448 $verifiedCount = 0;
449
450 // If we're asserting successful record deletion, make sure object is NOT found.
451 if ($delete) {
452 if ($object->find(TRUE)) {
453 $this->fail("Object not deleted by delete operation: $daoName, $id");
454 }
455 return;
456 }
457
458 // Otherwise check matches of DAO field values against expected values in $match.
459 if ($object->find(TRUE)) {
5896d037 460 $fields = &$object->fields();
6a488035
TO
461 foreach ($fields as $name => $value) {
462 $dbName = $value['name'];
463 if (isset($match[$name])) {
464 $verifiedCount++;
465 $this->assertEquals($object->$dbName, $match[$name]);
466 }
467 elseif (isset($match[$dbName])) {
468 $verifiedCount++;
469 $this->assertEquals($object->$dbName, $match[$dbName]);
470 }
471 }
472 }
473 else {
474 $this->fail("Could not retrieve object: $daoName, $id");
475 }
476 $object->free();
477 $matchSize = count($match);
478 if ($verifiedCount != $matchSize) {
479 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
480 }
481 }
482
4cbe18b8 483 /**
4f1f1f2a 484 * Request a record from the DB by seachColumn+searchValue. Success if a record is found.
c490a46a 485 * @param string $daoName
4cbe18b8
EM
486 * @param $searchValue
487 * @param $returnColumn
488 * @param $searchColumn
489 * @param $message
490 *
491 * @return null|string
492 * @throws PHPUnit_Framework_AssertionFailedError
493 */
00be9182 494 public function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
6a488035
TO
495 if (empty($searchValue)) {
496 $this->fail("empty value passed to assertDBNotNull");
497 }
498 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
499 $this->assertNotNull($value, $message);
500
501 return $value;
502 }
503
4cbe18b8 504 /**
4f1f1f2a 505 * Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
c490a46a 506 * @param string $daoName
4cbe18b8
EM
507 * @param $searchValue
508 * @param $returnColumn
509 * @param $searchColumn
510 * @param $message
511 */
00be9182 512 public function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
6a488035
TO
513 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
514 $this->assertNull($value, $message);
515 }
516
4cbe18b8 517 /**
4f1f1f2a 518 * Request a record from the DB by id. Success if row not found.
c490a46a 519 * @param string $daoName
100fef9d 520 * @param int $id
4cbe18b8
EM
521 * @param null $message
522 */
00be9182 523 public function assertDBRowNotExist($daoName, $id, $message = NULL) {
6a488035
TO
524 $message = $message ? $message : "$daoName (#$id) should not exist";
525 $value = CRM_Core_DAO::getFieldValue($daoName, $id, 'id', 'id', TRUE);
526 $this->assertNull($value, $message);
527 }
528
4cbe18b8 529 /**
4f1f1f2a 530 * Request a record from the DB by id. Success if row not found.
c490a46a 531 * @param string $daoName
100fef9d 532 * @param int $id
4cbe18b8
EM
533 * @param null $message
534 */
00be9182 535 public function assertDBRowExist($daoName, $id, $message = NULL) {
6a488035
TO
536 $message = $message ? $message : "$daoName (#$id) should exist";
537 $value = CRM_Core_DAO::getFieldValue($daoName, $id, 'id', 'id', TRUE);
538 $this->assertEquals($id, $value, $message);
539 }
540
4cbe18b8 541 /**
eceb18cc 542 * Compare a single column value in a retrieved DB record to an expected value.
c490a46a 543 * @param string $daoName
4cbe18b8
EM
544 * @param $searchValue
545 * @param $returnColumn
546 * @param $searchColumn
547 * @param $expectedValue
548 * @param $message
549 */
a130e045 550 public function assertDBCompareValue(
5896d037
TO
551 $daoName, $searchValue, $returnColumn, $searchColumn,
552 $expectedValue, $message
6a488035
TO
553 ) {
554 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
6dde7f04 555 $this->assertEquals($expectedValue, $value, $message);
6a488035
TO
556 }
557
4cbe18b8 558 /**
eceb18cc 559 * Compare all values in a single retrieved DB record to an array of expected values.
c490a46a 560 * @param string $daoName
100fef9d 561 * @param array $searchParams
4cbe18b8
EM
562 * @param $expectedValues
563 */
00be9182 564 public function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
6a488035
TO
565 //get the values from db
566 $dbValues = array();
567 CRM_Core_DAO::commonRetrieve($daoName, $searchParams, $dbValues);
568
569 // compare db values with expected values
570 self::assertAttributesEquals($expectedValues, $dbValues);
571 }
572
573 /**
eceb18cc 574 * Assert that a SQL query returns a given value.
6a488035
TO
575 *
576 * The first argument is an expected value. The remaining arguments are passed
577 * to CRM_Core_DAO::singleValueQuery
578 *
579 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
580 * array(1 => array("Whiz", "String")));
1e1fdcf6
EM
581 * @param $expected
582 * @param $query
583 * @param array $params
584 * @param string $message
6a488035 585 */
00be9182 586 public function assertDBQuery($expected, $query, $params = array(), $message = '') {
5896d037
TO
587 if ($message) {
588 $message .= ': ';
6c6e6187 589 }
6a488035
TO
590 $actual = CRM_Core_DAO::singleValueQuery($query, $params);
591 $this->assertEquals($expected, $actual,
5bb8417a
TO
592 sprintf('%sexpected=[%s] actual=[%s] query=[%s]',
593 $message, $expected, $actual, CRM_Core_DAO::composeQuery($query, $params, FALSE)
6a488035
TO
594 )
595 );
596 }
597
598 /**
599 * Assert that two array-trees are exactly equal, notwithstanding
600 * the sorting of keys
601 *
602 * @param array $expected
603 * @param array $actual
604 */
00be9182 605 public function assertTreeEquals($expected, $actual) {
6a488035
TO
606 $e = array();
607 $a = array();
608 CRM_Utils_Array::flatten($expected, $e, '', ':::');
609 CRM_Utils_Array::flatten($actual, $a, '', ':::');
610 ksort($e);
611 ksort($a);
612
613 $this->assertEquals($e, $a);
614 }
615
dc92f2f8 616 /**
78373706 617 * Assert that two numbers are approximately equal.
dc92f2f8
TO
618 *
619 * @param int|float $expected
620 * @param int|float $actual
621 * @param int|float $tolerance
622 * @param string $message
623 */
00be9182 624 public function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
dc92f2f8
TO
625 if ($message === NULL) {
626 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
627 }
628 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
629 }
630
4cbe18b8 631 /**
78373706
EM
632 * Assert attributes are equal.
633 *
4cbe18b8
EM
634 * @param $expectedValues
635 * @param $actualValues
78373706 636 * @param string $message
4cbe18b8
EM
637 *
638 * @throws PHPUnit_Framework_AssertionFailedError
639 */
00be9182 640 public function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
6a488035
TO
641 foreach ($expectedValues as $paramName => $paramValue) {
642 if (isset($actualValues[$paramName])) {
5896d037 643 $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
644 }
645 else {
797d4c52 646 $this->assertNull($expectedValues[$paramName], "Attribute '$paramName' not present in actual array and we expected it to be " . $expectedValues[$paramName]);
6a488035
TO
647 }
648 }
649 }
650
4cbe18b8
EM
651 /**
652 * @param $key
653 * @param $list
654 */
00be9182 655 public function assertArrayKeyExists($key, &$list) {
6a488035
TO
656 $result = isset($list[$key]) ? TRUE : FALSE;
657 $this->assertTrue($result, ts("%1 element exists?",
658 array(1 => $key)
659 ));
660 }
661
4cbe18b8
EM
662 /**
663 * @param $key
664 * @param $list
665 */
00be9182 666 public function assertArrayValueNotNull($key, &$list) {
6a488035
TO
667 $this->assertArrayKeyExists($key, $list);
668
669 $value = isset($list[$key]) ? $list[$key] : NULL;
670 $this->assertTrue($value,
671 ts("%1 element not null?",
672 array(1 => $key)
673 )
674 );
675 }
676
c8950569 677 /**
78373706
EM
678 * Check that api returned 'is_error' => 0.
679 *
e16033b4
TO
680 * @param array $apiResult
681 * Api result.
682 * @param string $prefix
683 * Extra test to add to message.
c8950569 684 */
00be9182 685 public function assertAPISuccess($apiResult, $prefix = '') {
6a488035
TO
686 if (!empty($prefix)) {
687 $prefix .= ': ';
688 }
7681ca91 689 $errorMessage = empty($apiResult['error_message']) ? '' : " " . $apiResult['error_message'];
f6722559 690
5896d037 691 if (!empty($apiResult['debug_information'])) {
f6722559 692 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
693 }
5896d037 694 if (!empty($apiResult['trace'])) {
7681ca91 695 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
696 }
697 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
6a488035
TO
698 }
699
feb2a730 700 /**
78373706 701 * Check that api returned 'is_error' => 1.
2a6da8d7 702 *
e16033b4
TO
703 * @param array $apiResult
704 * Api result.
705 * @param string $prefix
706 * Extra test to add to message.
2a6da8d7 707 * @param null $expectedError
feb2a730 708 */
00be9182 709 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
feb2a730 710 if (!empty($prefix)) {
711 $prefix .= ': ';
712 }
5896d037
TO
713 if ($expectedError && !empty($apiResult['is_error'])) {
714 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
64fe97da 715 }
feb2a730 716 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
f6722559 717 $this->assertNotEmpty($apiResult['error_message']);
feb2a730 718 }
719
4cbe18b8
EM
720 /**
721 * @param $expected
722 * @param $actual
723 * @param string $message
724 */
00be9182 725 public function assertType($expected, $actual, $message = '') {
6a488035
TO
726 return $this->assertInternalType($expected, $actual, $message);
727 }
54bd1003 728
c43d01f3 729 /**
78373706
EM
730 * Check that a deleted item has been deleted.
731 *
1e1fdcf6
EM
732 * @param $entity
733 * @param $id
c43d01f3 734 */
00be9182 735 public function assertAPIDeleted($entity, $id) {
c43d01f3 736 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
737 }
738
739
f6722559 740 /**
100fef9d 741 * Check that api returned 'is_error' => 1
f6722559 742 * else provide full message
c490a46a 743 * @param array $result
2a6da8d7
EM
744 * @param $expected
745 * @param array $valuesToExclude
e16033b4
TO
746 * @param string $prefix
747 * Extra test to add to message.
f6722559 748 */
00be9182 749 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
f6722559 750 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
751 foreach ($valuesToExclude as $value) {
5896d037 752 if (isset($result[$value])) {
f6722559 753 unset($result[$value]);
754 }
5896d037 755 if (isset($expected[$value])) {
f6722559 756 unset($expected[$value]);
757 }
758 }
759 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
760 }
761
0f643fb2
TO
762 /**
763 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
764 *
765 * @param $entity
766 * @param $action
c490a46a 767 * @param array $params
0f643fb2
TO
768 * @return array|int
769 */
00be9182 770 public function civicrm_api($entity, $action, $params) {
0f643fb2
TO
771 return civicrm_api($entity, $action, $params);
772 }
773
888dab1e
TO
774 /**
775 * Create a batch of external API calls which can
776 * be executed concurrently.
777 *
778 * @code
779 * $calls = $this->createExternalAPI()
780 * ->addCall('Contact', 'get', ...)
781 * ->addCall('Contact', 'get', ...)
782 * ...
783 * ->run()
784 * ->getResults();
785 * @endcode
786 *
787 * @return \Civi\API\ExternalBatch
788 * @throws PHPUnit_Framework_SkippedTestError
789 */
790 public function createExternalAPI() {
791 global $civicrm_root;
792 $defaultParams = array(
793 'version' => $this->_apiversion,
794 'debug' => 1,
795 );
796
797 $calls = new \Civi\API\ExternalBatch($defaultParams);
888dab1e
TO
798
799 if (!$calls->isSupported()) {
800 $this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
801 }
802
803 return $calls;
804 }
805
54bd1003 806 /**
eceb18cc 807 * wrap api functions.
791c263c 808 * so we can ensure they succeed & throw exceptions without litterering the test with checks
77b97be7 809 *
791c263c 810 * @param string $entity
811 * @param string $action
812 * @param array $params
e16033b4
TO
813 * @param mixed $checkAgainst
814 * Optional value to check result against, implemented for getvalue,.
a86d27fc 815 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
816 * for getsingle the array is compared against an array passed in - the id is not compared (for
817 * better or worse )
77b97be7
EM
818 *
819 * @return array|int
791c263c 820 */
00be9182 821 public function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
fbda92d3 822 $params = array_merge(array(
f6722559 823 'version' => $this->_apiversion,
fbda92d3 824 'debug' => 1,
825 ),
826 $params
9443c775 827 );
f6722559 828 switch (strtolower($action)) {
6c6e6187 829 case 'getvalue':
f6722559 830 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
6c6e6187
TO
831
832 case 'getsingle':
f6722559 833 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
6c6e6187
TO
834
835 case 'getcount':
836 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
f6722559 837 }
0f643fb2 838 $result = $this->civicrm_api($entity, $action, $params);
54bd1003 839 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
840 return $result;
841 }
842
fbda92d3 843 /**
844 * This function exists to wrap api getValue function & check the result
845 * so we can ensure they succeed & throw exceptions without litterering the test with checks
846 * There is a type check in this
77b97be7 847 *
fbda92d3 848 * @param string $entity
849 * @param array $params
e16033b4
TO
850 * @param string $type
851 * Per http://php.net/manual/en/function.gettype.php possible types.
16b10e64
CW
852 * - boolean
853 * - integer
854 * - double
855 * - string
856 * - array
857 * - object
77b97be7
EM
858 *
859 * @return array|int
fbda92d3 860 */
00be9182 861 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
fbda92d3 862 $params += array(
f6722559 863 'version' => $this->_apiversion,
fbda92d3 864 'debug' => 1,
865 );
0f643fb2 866 $result = $this->civicrm_api($entity, 'getvalue', $params);
5896d037
TO
867 if ($type) {
868 if ($type == 'integer') {
fbda92d3 869 // api seems to return integers as strings
870 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
871 }
5896d037
TO
872 else {
873 $this->assertType($type, $result, "returned result should have been of type $type but was ");
fbda92d3 874 }
875 }
876 return $result;
877 }
c8950569 878
f6722559 879 /**
880 * This function exists to wrap api getsingle function & check the result
881 * so we can ensure they succeed & throw exceptions without litterering the test with checks
8deefe64 882 *
f6722559 883 * @param string $entity
884 * @param array $params
e16033b4
TO
885 * @param array $checkAgainst
886 * Array to compare result against.
16b10e64
CW
887 * - boolean
888 * - integer
889 * - double
890 * - string
891 * - array
892 * - object
8deefe64 893 *
cbdcc634 894 * @throws Exception
8deefe64 895 * @return array|int
f6722559 896 */
00be9182 897 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
f6722559 898 $params += array(
899 'version' => $this->_apiversion,
f6722559 900 );
0f643fb2 901 $result = $this->civicrm_api($entity, 'getsingle', $params);
5896d037 902 if (!is_array($result) || !empty($result['is_error']) || isset($result['values'])) {
f6722559 903 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
904 }
5896d037 905 if ($checkAgainst) {
f6722559 906 // @todo - have gone with the fn that unsets id? should we check id?
907 $this->checkArrayEquals($result, $checkAgainst);
908 }
909 return $result;
910 }
2a6da8d7 911
f6722559 912 /**
913 * This function exists to wrap api getValue function & check the result
914 * so we can ensure they succeed & throw exceptions without litterering the test with checks
915 * There is a type check in this
916 * @param string $entity
917 * @param array $params
2a6da8d7
EM
918 * @param null $count
919 * @throws Exception
920 * @return array|int
f6722559 921 */
00be9182 922 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
f6722559 923 $params += array(
924 'version' => $this->_apiversion,
925 'debug' => 1,
926 );
0f643fb2 927 $result = $this->civicrm_api($entity, 'getcount', $params);
a130e045 928 if (!is_int($result) || !empty($result['is_error']) || isset($result['values'])) {
f6722559 929 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
930 }
5896d037 931 if (is_int($count)) {
fd843187 932 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
f6722559 933 }
934 return $result;
935 }
69f028bc 936
54bd1003 937 /**
eceb18cc 938 * This function exists to wrap api functions.
54bd1003 939 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
940 *
941 * @param string $entity
942 * @param string $action
943 * @param array $params
e16033b4
TO
944 * @param string $function
945 * Pass this in to create a generated example.
946 * @param string $file
947 * Pass this in to create a generated example.
69f028bc 948 * @param string $description
a828d7b8
CW
949 * @param string|null $exampleName
950 *
69f028bc 951 * @return array|int
54bd1003 952 */
a828d7b8 953 public function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $exampleName = NULL) {
f6722559 954 $params['version'] = $this->_apiversion;
17400ace 955 $result = $this->callAPISuccess($entity, $action, $params);
a828d7b8 956 $this->documentMe($entity, $action, $params, $result, $function, $file, $description, $exampleName);
54bd1003 957 return $result;
958 }
959
960 /**
eceb18cc 961 * This function exists to wrap api functions.
54bd1003 962 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
963 * @param string $entity
964 * @param string $action
965 * @param array $params
e16033b4
TO
966 * @param string $expectedErrorMessage
967 * Error.
2a6da8d7
EM
968 * @param null $extraOutput
969 * @return array|int
54bd1003 970 */
00be9182 971 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
9443c775
CW
972 if (is_array($params)) {
973 $params += array(
f6722559 974 'version' => $this->_apiversion,
9443c775
CW
975 );
976 }
0f643fb2 977 $result = $this->civicrm_api($entity, $action, $params);
d1d13125 978 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success", $expectedErrorMessage);
791c263c 979 return $result;
980 }
9443c775 981
fbda92d3 982 /**
983 * Create required data based on $this->entity & $this->params
984 * This is just a way to set up the test data for delete & get functions
985 * so the distinction between set
986 * up & tested functions is clearer
987 *
a6c01b45
CW
988 * @return array
989 * api Result
fbda92d3 990 */
5896d037 991 public function createTestEntity() {
fbda92d3 992 return $entity = $this->callAPISuccess($this->entity, 'create', $this->params);
993 }
994
6a488035
TO
995 /**
996 * Generic function to create Organisation, to be used in test cases
997 *
16b10e64
CW
998 * @param array $params
999 * parameters for civicrm_contact_add api function call
1000 * @param int $seq
1001 * sequence number if creating multiple organizations
6a488035 1002 *
a6c01b45
CW
1003 * @return int
1004 * id of Organisation created
6a488035 1005 */
00be9182 1006 public function organizationCreate($params = array(), $seq = 0) {
6a488035
TO
1007 if (!$params) {
1008 $params = array();
1009 }
4cc99d00 1010 $params = array_merge($this->sampleContact('Organization', $seq), $params);
1011 return $this->_contactCreate($params);
6a488035
TO
1012 }
1013
1014 /**
1015 * Generic function to create Individual, to be used in test cases
1016 *
16b10e64
CW
1017 * @param array $params
1018 * parameters for civicrm_contact_add api function call
1019 * @param int $seq
1020 * sequence number if creating multiple individuals
6ec61f19 1021 * @param bool $random
6a488035 1022 *
a6c01b45
CW
1023 * @return int
1024 * id of Individual created
6a488035 1025 */
6ec61f19 1026 public function individualCreate($params = array(), $seq = 0, $random = FALSE) {
1027 $params = array_merge($this->sampleContact('Individual', $seq, $random), $params);
6a488035
TO
1028 return $this->_contactCreate($params);
1029 }
1030
1031 /**
1032 * Generic function to create Household, to be used in test cases
1033 *
16b10e64
CW
1034 * @param array $params
1035 * parameters for civicrm_contact_add api function call
1036 * @param int $seq
1037 * sequence number if creating multiple households
6a488035 1038 *
a6c01b45
CW
1039 * @return int
1040 * id of Household created
6a488035 1041 */
00be9182 1042 public function householdCreate($params = array(), $seq = 0) {
dc8624c6 1043 $params = array_merge($this->sampleContact('Household', $seq), $params);
6a488035
TO
1044 return $this->_contactCreate($params);
1045 }
1046
4cc99d00 1047 /**
eceb18cc 1048 * Helper function for getting sample contact properties.
4cc99d00 1049 *
16b10e64
CW
1050 * @param string $contact_type
1051 * enum contact type: Individual, Organization
1052 * @param int $seq
1053 * sequence number for the values of this type
4cc99d00 1054 *
a6c01b45
CW
1055 * @return array
1056 * properties of sample contact (ie. $params for API call)
4cc99d00 1057 */
6ec61f19 1058 public function sampleContact($contact_type, $seq = 0, $random = FALSE) {
4cc99d00 1059 $samples = array(
1060 'Individual' => array(
1061 // The number of values in each list need to be coprime numbers to not have duplicates
1062 'first_name' => array('Anthony', 'Joe', 'Terrence', 'Lucie', 'Albert', 'Bill', 'Kim'),
1063 'middle_name' => array('J.', 'M.', 'P', 'L.', 'K.', 'A.', 'B.', 'C.', 'D', 'E.', 'Z.'),
1064 'last_name' => array('Anderson', 'Miller', 'Smith', 'Collins', 'Peterson'),
1065 ),
1066 'Organization' => array(
5896d037
TO
1067 'organization_name' => array(
1068 'Unit Test Organization',
1069 'Acme',
1070 'Roberts and Sons',
1071 'Cryo Space Labs',
21dfd5f5 1072 'Sharper Pens',
5896d037 1073 ),
4cc99d00 1074 ),
1075 'Household' => array(
1076 'household_name' => array('Unit Test household'),
1077 ),
1078 );
1079 $params = array('contact_type' => $contact_type);
1080 foreach ($samples[$contact_type] as $key => $values) {
a130e045 1081 $params[$key] = $values[$seq % count($values)];
6ec61f19 1082 if ($random) {
1083 $params[$key] .= substr(sha1(rand()), 0, 5);
1084 }
4cc99d00 1085 }
5896d037 1086 if ($contact_type == 'Individual') {
6c6e6187 1087 $params['email'] = strtolower(
5896d037
TO
1088 $params['first_name'] . '_' . $params['last_name'] . '@civicrm.org'
1089 );
6c6e6187
TO
1090 $params['prefix_id'] = 3;
1091 $params['suffix_id'] = 3;
4cc99d00 1092 }
1093 return $params;
1094 }
1095
6a488035 1096 /**
fe482240 1097 * Private helper function for calling civicrm_contact_add.
6a488035 1098 *
e16033b4
TO
1099 * @param array $params
1100 * For civicrm_contact_add api function call.
9da2e77c
E
1101 *
1102 * @throws Exception
6a488035 1103 *
a6c01b45
CW
1104 * @return int
1105 * id of Household created
6a488035
TO
1106 */
1107 private function _contactCreate($params) {
4732bb2f 1108 $result = $this->callAPISuccess('contact', 'create', $params);
8cc574cf 1109 if (!empty($result['is_error']) || empty($result['id'])) {
ace01fda 1110 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
1111 }
1112 return $result['id'];
1113 }
1114
4cbe18b8 1115 /**
507d3b64 1116 * Delete contact, ensuring it is not the domain contact
4cbe18b8 1117 *
507d3b64
EM
1118 * @param int $contactID
1119 * Contact ID to delete
4cbe18b8 1120 */
00be9182 1121 public function contactDelete($contactID) {
a130e045 1122 $domain = new CRM_Core_BAO_Domain();
6a488035 1123 $domain->contact_id = $contactID;
507d3b64
EM
1124 if (!$domain->find(TRUE)) {
1125 $this->callAPISuccess('contact', 'delete', array(
1126 'id' => $contactID,
1127 'skip_undelete' => 1,
1128 ));
6a488035 1129 }
6a488035
TO
1130 }
1131
4cbe18b8 1132 /**
100fef9d 1133 * @param int $contactTypeId
4cbe18b8
EM
1134 *
1135 * @throws Exception
1136 */
00be9182 1137 public function contactTypeDelete($contactTypeId) {
6a488035
TO
1138 $result = CRM_Contact_BAO_ContactType::del($contactTypeId);
1139 if (!$result) {
1140 throw new Exception('Could not delete contact type');
1141 }
1142 }
1143
4cbe18b8
EM
1144 /**
1145 * @param array $params
1146 *
1147 * @return mixed
1148 */
00be9182 1149 public function membershipTypeCreate($params = array()) {
6a488035
TO
1150 CRM_Member_PseudoConstant::flush('membershipType');
1151 CRM_Core_Config::clearDBCache();
204beda3 1152 $this->setupIDs['contact'] = $memberOfOrganization = $this->organizationCreate();
75638074 1153 $params = array_merge(array(
6a488035
TO
1154 'name' => 'General',
1155 'duration_unit' => 'year',
1156 'duration_interval' => 1,
1157 'period_type' => 'rolling',
0090e3d2 1158 'member_of_contact_id' => $memberOfOrganization,
6a488035 1159 'domain_id' => 1,
4303ea89 1160 'financial_type_id' => 2,
6a488035 1161 'is_active' => 1,
6a488035 1162 'sequential' => 1,
eacf220c 1163 'visibility' => 'Public',
75638074 1164 ), $params);
1165
1166 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
6a488035 1167
6a488035
TO
1168 CRM_Member_PseudoConstant::flush('membershipType');
1169 CRM_Utils_Cache::singleton()->flush();
6a488035
TO
1170
1171 return $result['id'];
1172 }
1173
4cbe18b8 1174 /**
c490a46a 1175 * @param array $params
4cbe18b8
EM
1176 *
1177 * @return mixed
1178 */
00be9182 1179 public function contactMembershipCreate($params) {
5d8b37be 1180 $params = array_merge(array(
6a488035
TO
1181 'join_date' => '2007-01-21',
1182 'start_date' => '2007-01-21',
1183 'end_date' => '2007-12-21',
1184 'source' => 'Payment',
5d8b37be 1185 'membership_type_id' => 'General',
1186 ), $params);
1187 if (!is_numeric($params['membership_type_id'])) {
1188 $membershipTypes = $this->callAPISuccess('Membership', 'getoptions', array('action' => 'create', 'field' => 'membership_type_id'));
1189 if (!in_array($params['membership_type_id'], $membershipTypes['values'])) {
1190 $this->membershipTypeCreate(array('name' => $params['membership_type_id']));
6a488035
TO
1191 }
1192 }
1193
f6722559 1194 $result = $this->callAPISuccess('Membership', 'create', $params);
6a488035
TO
1195 return $result['id'];
1196 }
1197
1198 /**
eceb18cc 1199 * Delete Membership Type.
6a488035 1200 *
c490a46a 1201 * @param array $params
6a488035 1202 */
00be9182 1203 public function membershipTypeDelete($params) {
cab024d4 1204 $this->callAPISuccess('MembershipType', 'Delete', $params);
6a488035
TO
1205 }
1206
4cbe18b8 1207 /**
100fef9d 1208 * @param int $membershipID
4cbe18b8 1209 */
00be9182 1210 public function membershipDelete($membershipID) {
f6722559 1211 $deleteParams = array('id' => $membershipID);
1212 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
6a488035
TO
1213 }
1214
4cbe18b8
EM
1215 /**
1216 * @param string $name
1217 *
1218 * @return mixed
1219 */
00be9182 1220 public function membershipStatusCreate($name = 'test member status') {
6a488035
TO
1221 $params['name'] = $name;
1222 $params['start_event'] = 'start_date';
1223 $params['end_event'] = 'end_date';
1224 $params['is_current_member'] = 1;
1225 $params['is_active'] = 1;
6a488035 1226
f6722559 1227 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
6a488035 1228 CRM_Member_PseudoConstant::flush('membershipStatus');
6a488035
TO
1229 return $result['id'];
1230 }
1231
4cbe18b8 1232 /**
100fef9d 1233 * @param int $membershipStatusID
4cbe18b8 1234 */
00be9182 1235 public function membershipStatusDelete($membershipStatusID) {
6a488035
TO
1236 if (!$membershipStatusID) {
1237 return;
1238 }
4732bb2f 1239 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
6a488035
TO
1240 }
1241
4cbe18b8
EM
1242 /**
1243 * @param array $params
1244 *
1245 * @return mixed
1246 */
00be9182 1247 public function relationshipTypeCreate($params = array()) {
75638074 1248 $params = array_merge(array(
6a488035
TO
1249 'name_a_b' => 'Relation 1 for relationship type create',
1250 'name_b_a' => 'Relation 2 for relationship type create',
1251 'contact_type_a' => 'Individual',
1252 'contact_type_b' => 'Organization',
1253 'is_reserved' => 1,
1254 'is_active' => 1,
75638074 1255 ),
5896d037 1256 $params
75638074 1257 );
6a488035 1258
f6722559 1259 $result = $this->callAPISuccess('relationship_type', 'create', $params);
6a488035
TO
1260 CRM_Core_PseudoConstant::flush('relationshipType');
1261
1262 return $result['id'];
1263 }
1264
1265 /**
eceb18cc 1266 * Delete Relatinship Type.
6a488035
TO
1267 *
1268 * @param int $relationshipTypeID
1269 */
00be9182 1270 public function relationshipTypeDelete($relationshipTypeID) {
6a488035 1271 $params['id'] = $relationshipTypeID;
a60c0bc8
SL
1272 $check = $this->callAPISuccess('relationship_type', 'get', $params);
1273 if (!empty($check['count'])) {
1274 $this->callAPISuccess('relationship_type', 'delete', $params);
1275 }
6a488035
TO
1276 }
1277
4cbe18b8 1278 /**
100fef9d 1279 * @param array $params
4cbe18b8
EM
1280 *
1281 * @return mixed
1282 */
00be9182 1283 public function paymentProcessorTypeCreate($params = NULL) {
6a488035
TO
1284 if (is_null($params)) {
1285 $params = array(
1286 'name' => 'API_Test_PP',
1287 'title' => 'API Test Payment Processor',
1288 'class_name' => 'CRM_Core_Payment_APITest',
1289 'billing_mode' => 'form',
1290 'is_recur' => 0,
1291 'is_reserved' => 1,
1292 'is_active' => 1,
1293 );
1294 }
f6722559 1295 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
6a488035 1296
6a488035
TO
1297 CRM_Core_PseudoConstant::flush('paymentProcessorType');
1298
1299 return $result['id'];
1300 }
1301
d6944518
EM
1302 /**
1303 * Create test Authorize.net instance.
1304 *
1305 * @param array $params
1306 *
1307 * @return mixed
1308 */
1309 public function paymentProcessorAuthorizeNetCreate($params = array()) {
1310 $params = array_merge(array(
1311 'name' => 'Authorize',
1312 'domain_id' => CRM_Core_Config::domainID(),
1313 'payment_processor_type_id' => 'AuthNet',
1314 'title' => 'AuthNet',
1315 'is_active' => 1,
1316 'is_default' => 0,
1317 'is_test' => 1,
1318 'is_recur' => 1,
1319 'user_name' => '4y5BfuW7jm',
1320 'password' => '4cAmW927n8uLf5J8',
1321 'url_site' => 'https://test.authorize.net/gateway/transact.dll',
1322 'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
1323 'class_name' => 'Payment_AuthorizeNet',
1324 'billing_mode' => 1,
1325 ), $params);
1326
4ecbf127 1327 $result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
d6944518
EM
1328 return $result['id'];
1329 }
1330
6a488035 1331 /**
eceb18cc 1332 * Create Participant.
6a488035 1333 *
e16033b4
TO
1334 * @param array $params
1335 * Array of contact id and event id values.
6a488035 1336 *
a6c01b45
CW
1337 * @return int
1338 * $id of participant created
6a488035 1339 */
00be9182 1340 public function participantCreate($params) {
5896d037 1341 if (empty($params['contact_id'])) {
94692f2d 1342 $params['contact_id'] = $this->individualCreate();
1343 }
5896d037 1344 if (empty($params['event_id'])) {
94692f2d 1345 $event = $this->eventCreate();
1346 $params['event_id'] = $event['id'];
1347 }
6a488035 1348 $defaults = array(
6a488035
TO
1349 'status_id' => 2,
1350 'role_id' => 1,
1351 'register_date' => 20070219,
1352 'source' => 'Wimbeldon',
1353 'event_level' => 'Payment',
94692f2d 1354 'debug' => 1,
6a488035
TO
1355 );
1356
1357 $params = array_merge($defaults, $params);
f6722559 1358 $result = $this->callAPISuccess('Participant', 'create', $params);
6a488035
TO
1359 return $result['id'];
1360 }
1361
1362 /**
eceb18cc 1363 * Create Payment Processor.
6a488035 1364 *
8950ecdc 1365 * @return int
1366 * Id Payment Processor
6a488035 1367 */
0f07bb06 1368 public function processorCreate($params = array()) {
6a488035
TO
1369 $processorParams = array(
1370 'domain_id' => 1,
1371 'name' => 'Dummy',
8950ecdc 1372 'payment_processor_type_id' => 'Dummy',
6a488035 1373 'financial_account_id' => 12,
a8215a8d 1374 'is_test' => TRUE,
6a488035
TO
1375 'is_active' => 1,
1376 'user_name' => '',
1377 'url_site' => 'http://dummy.com',
1378 'url_recur' => 'http://dummy.com',
1379 'billing_mode' => 1,
8950ecdc 1380 'sequential' => 1,
204efedd 1381 'payment_instrument_id' => 'Debit Card',
6a488035 1382 );
0f07bb06 1383 $processorParams = array_merge($processorParams, $params);
8950ecdc 1384 $processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
1385 return $processor['id'];
22e39333 1386 }
1387
1388 /**
1389 * Create Payment Processor.
1390 *
1391 * @param array $processorParams
1392 *
0193ebdb 1393 * @return \CRM_Core_Payment_Dummy
1394 * Instance of Dummy Payment Processor
22e39333 1395 */
1396 public function dummyProcessorCreate($processorParams = array()) {
8950ecdc 1397 $paymentProcessorID = $this->processorCreate($processorParams);
7a3b0ca3 1398 return System::singleton()->getById($paymentProcessorID);
6a488035
TO
1399 }
1400
1401 /**
eceb18cc 1402 * Create contribution page.
6a488035 1403 *
c490a46a 1404 * @param array $params
16b10e64
CW
1405 * @return array
1406 * Array of contribution page
6a488035 1407 */
23ead872 1408 public function contributionPageCreate($params = array()) {
1409 $this->_pageParams = array_merge(array(
6a488035
TO
1410 'title' => 'Test Contribution Page',
1411 'financial_type_id' => 1,
1412 'currency' => 'USD',
1413 'financial_account_id' => 1,
6a488035
TO
1414 'is_active' => 1,
1415 'is_allow_other_amount' => 1,
1416 'min_amount' => 10,
1417 'max_amount' => 1000,
23ead872 1418 ), $params);
1419 return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
6a488035
TO
1420 }
1421
a646bdd2
SB
1422 /**
1423 * Create a sample batch.
1424 */
1425 public function batchCreate() {
1426 $params = $this->_params;
1427 $params['name'] = $params['title'] = 'Batch_433397';
1428 $params['status_id'] = 1;
1429 $result = $this->callAPISuccess('batch', 'create', $params);
1430 return $result['id'];
1431 }
1432
6a488035 1433 /**
eceb18cc 1434 * Create Tag.
6a488035 1435 *
2a6da8d7 1436 * @param array $params
a6c01b45
CW
1437 * @return array
1438 * result of created tag
6a488035 1439 */
00be9182 1440 public function tagCreate($params = array()) {
fb32de45 1441 $defaults = array(
1442 'name' => 'New Tag3',
1443 'description' => 'This is description for Our New Tag ',
1444 'domain_id' => '1',
1445 );
1446 $params = array_merge($defaults, $params);
6c6e6187 1447 $result = $this->callAPISuccess('Tag', 'create', $params);
fb32de45 1448 return $result['values'][$result['id']];
6a488035
TO
1449 }
1450
1451 /**
eceb18cc 1452 * Delete Tag.
6a488035 1453 *
e16033b4
TO
1454 * @param int $tagId
1455 * Id of the tag to be deleted.
16b10e64
CW
1456 *
1457 * @return int
6a488035 1458 */
00be9182 1459 public function tagDelete($tagId) {
6a488035
TO
1460 require_once 'api/api.php';
1461 $params = array(
1462 'tag_id' => $tagId,
6a488035 1463 );
f6722559 1464 $result = $this->callAPISuccess('Tag', 'delete', $params);
6a488035
TO
1465 return $result['id'];
1466 }
1467
1468 /**
1469 * Add entity(s) to the tag
1470 *
e16033b4 1471 * @param array $params
77b97be7
EM
1472 *
1473 * @return bool
6a488035 1474 */
00be9182 1475 public function entityTagAdd($params) {
f6722559 1476 $result = $this->callAPISuccess('entity_tag', 'create', $params);
6a488035
TO
1477 return TRUE;
1478 }
1479
1480 /**
5210fa35 1481 * Create pledge.
6a488035 1482 *
5210fa35 1483 * @param array $params
1484 * Parameters.
77b97be7 1485 *
a6c01b45 1486 * @return int
5210fa35 1487 * id of created pledge
6a488035 1488 */
5210fa35 1489 public function pledgeCreate($params) {
1490 $params = array_merge(array(
6a488035
TO
1491 'pledge_create_date' => date('Ymd'),
1492 'start_date' => date('Ymd'),
1493 'scheduled_date' => date('Ymd'),
1494 'amount' => 100.00,
1495 'pledge_status_id' => '2',
1496 'financial_type_id' => '1',
1497 'pledge_original_installment_amount' => 20,
1498 'frequency_interval' => 5,
1499 'frequency_unit' => 'year',
1500 'frequency_day' => 15,
1501 'installments' => 5,
5210fa35 1502 ),
1503 $params);
6a488035 1504
f6722559 1505 $result = $this->callAPISuccess('Pledge', 'create', $params);
6a488035
TO
1506 return $result['id'];
1507 }
1508
1509 /**
eceb18cc 1510 * Delete contribution.
6a488035 1511 *
c490a46a 1512 * @param int $pledgeId
6a488035 1513 */
00be9182 1514 public function pledgeDelete($pledgeId) {
6a488035
TO
1515 $params = array(
1516 'pledge_id' => $pledgeId,
6a488035 1517 );
f6722559 1518 $this->callAPISuccess('Pledge', 'delete', $params);
6a488035
TO
1519 }
1520
1521 /**
eceb18cc 1522 * Create contribution.
6a488035 1523 *
c3a3074f 1524 * @param array $params
1525 * Array of parameters.
16b10e64 1526 *
a6c01b45
CW
1527 * @return int
1528 * id of created contribution
6a488035 1529 */
78ab0ca4 1530 public function contributionCreate($params) {
69fccd8f 1531
d6944518 1532 $params = array_merge(array(
6a488035 1533 'domain_id' => 1,
6a488035
TO
1534 'receive_date' => date('Ymd'),
1535 'total_amount' => 100.00,
69fccd8f 1536 'fee_amount' => 5.00,
78ab0ca4 1537 'financial_type_id' => 1,
1538 'payment_instrument_id' => 1,
6a488035 1539 'non_deductible_amount' => 10.00,
78ab0ca4 1540 'trxn_id' => 12345,
1541 'invoice_id' => 67890,
6a488035 1542 'source' => 'SSF',
6a488035 1543 'contribution_status_id' => 1,
d6944518 1544 ), $params);
6a488035 1545
f6722559 1546 $result = $this->callAPISuccess('contribution', 'create', $params);
6a488035
TO
1547 return $result['id'];
1548 }
1549
6a488035 1550 /**
eceb18cc 1551 * Delete contribution.
6a488035
TO
1552 *
1553 * @param int $contributionId
8deefe64
EM
1554 *
1555 * @return array|int
6a488035 1556 */
00be9182 1557 public function contributionDelete($contributionId) {
6a488035
TO
1558 $params = array(
1559 'contribution_id' => $contributionId,
6a488035 1560 );
f6722559 1561 $result = $this->callAPISuccess('contribution', 'delete', $params);
6a488035
TO
1562 return $result;
1563 }
1564
1565 /**
eceb18cc 1566 * Create an Event.
6a488035 1567 *
e16033b4
TO
1568 * @param array $params
1569 * Name-value pair for an event.
6a488035 1570 *
a6c01b45 1571 * @return array
6a488035 1572 */
00be9182 1573 public function eventCreate($params = array()) {
6a488035
TO
1574 // if no contact was passed, make up a dummy event creator
1575 if (!isset($params['contact_id'])) {
1576 $params['contact_id'] = $this->_contactCreate(array(
1577 'contact_type' => 'Individual',
1578 'first_name' => 'Event',
1579 'last_name' => 'Creator',
6a488035
TO
1580 ));
1581 }
1582
1583 // set defaults for missing params
1584 $params = array_merge(array(
1585 'title' => 'Annual CiviCRM meet',
1586 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1587 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1588 'event_type_id' => 1,
1589 'is_public' => 1,
1590 'start_date' => 20081021,
1591 'end_date' => 20081023,
1592 'is_online_registration' => 1,
1593 'registration_start_date' => 20080601,
1594 'registration_end_date' => 20081015,
1595 'max_participants' => 100,
1596 'event_full_text' => 'Sorry! We are already full',
c039f658 1597 'is_monetary' => 0,
6a488035 1598 'is_active' => 1,
6a488035
TO
1599 'is_show_location' => 0,
1600 ), $params);
1601
8cba5814 1602 return $this->callAPISuccess('Event', 'create', $params);
6a488035
TO
1603 }
1604
f660d2ad 1605 /**
1606 * Create a paid event.
1607 *
1608 * @param array $params
1609 *
1610 * @return array
1611 */
1612 protected function eventCreatePaid($params) {
1613 $event = $this->eventCreate($params);
1614 $this->priceSetID = $this->eventPriceSetCreate(55, 0, 'Radio');
1615 CRM_Price_BAO_PriceSet::addTo('civicrm_event', $event['id'], $this->priceSetID);
1616 $priceSet = CRM_Price_BAO_PriceSet::getSetDetail($this->priceSetID, TRUE, FALSE);
1617 $priceSet = CRM_Utils_Array::value($this->priceSetID, $priceSet);
1618 $this->eventFeeBlock = CRM_Utils_Array::value('fields', $priceSet);
1619 return $event;
1620 }
1621
6a488035 1622 /**
eceb18cc 1623 * Delete event.
6a488035 1624 *
e16033b4
TO
1625 * @param int $id
1626 * ID of the event.
8deefe64
EM
1627 *
1628 * @return array|int
6a488035 1629 */
00be9182 1630 public function eventDelete($id) {
6a488035
TO
1631 $params = array(
1632 'event_id' => $id,
6a488035 1633 );
8cba5814 1634 return $this->callAPISuccess('event', 'delete', $params);
6a488035
TO
1635 }
1636
1637 /**
eceb18cc 1638 * Delete participant.
6a488035
TO
1639 *
1640 * @param int $participantID
8deefe64
EM
1641 *
1642 * @return array|int
6a488035 1643 */
00be9182 1644 public function participantDelete($participantID) {
6a488035
TO
1645 $params = array(
1646 'id' => $participantID,
6a488035 1647 );
a60c0bc8
SL
1648 $check = $this->callAPISuccess('Participant', 'get', $params);
1649 if ($check['count'] > 0) {
1650 return $this->callAPISuccess('Participant', 'delete', $params);
1651 }
6a488035
TO
1652 }
1653
1654 /**
eceb18cc 1655 * Create participant payment.
6a488035 1656 *
100fef9d
CW
1657 * @param int $participantID
1658 * @param int $contributionID
a6c01b45
CW
1659 * @return int
1660 * $id of created payment
6a488035 1661 */
00be9182 1662 public function participantPaymentCreate($participantID, $contributionID = NULL) {
6a488035
TO
1663 //Create Participant Payment record With Values
1664 $params = array(
1665 'participant_id' => $participantID,
1666 'contribution_id' => $contributionID,
6a488035
TO
1667 );
1668
f6722559 1669 $result = $this->callAPISuccess('participant_payment', 'create', $params);
6a488035
TO
1670 return $result['id'];
1671 }
1672
1673 /**
eceb18cc 1674 * Delete participant payment.
6a488035
TO
1675 *
1676 * @param int $paymentID
1677 */
00be9182 1678 public function participantPaymentDelete($paymentID) {
6a488035
TO
1679 $params = array(
1680 'id' => $paymentID,
6a488035 1681 );
f6722559 1682 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
6a488035
TO
1683 }
1684
1685 /**
eceb18cc 1686 * Add a Location.
6a488035 1687 *
100fef9d 1688 * @param int $contactID
a6c01b45
CW
1689 * @return int
1690 * location id of created location
6a488035 1691 */
00be9182 1692 public function locationAdd($contactID) {
6a488035
TO
1693 $address = array(
1694 1 => array(
1695 'location_type' => 'New Location Type',
1696 'is_primary' => 1,
1697 'name' => 'Saint Helier St',
1698 'county' => 'Marin',
86797006 1699 'country' => 'UNITED STATES',
6a488035
TO
1700 'state_province' => 'Michigan',
1701 'supplemental_address_1' => 'Hallmark Ct',
1702 'supplemental_address_2' => 'Jersey Village',
207f62c6 1703 'supplemental_address_3' => 'My Town',
21dfd5f5 1704 ),
6a488035
TO
1705 );
1706
1707 $params = array(
1708 'contact_id' => $contactID,
1709 'address' => $address,
6a488035
TO
1710 'location_format' => '2.0',
1711 'location_type' => 'New Location Type',
1712 );
1713
f6722559 1714 $result = $this->callAPISuccess('Location', 'create', $params);
6a488035
TO
1715 return $result;
1716 }
1717
1718 /**
eceb18cc 1719 * Delete Locations of contact.
6a488035 1720 *
e16033b4
TO
1721 * @param array $params
1722 * Parameters.
6a488035 1723 */
00be9182 1724 public function locationDelete($params) {
c490a46a 1725 $this->callAPISuccess('Location', 'delete', $params);
6a488035
TO
1726 }
1727
1728 /**
eceb18cc 1729 * Add a Location Type.
6a488035 1730 *
100fef9d 1731 * @param array $params
16b10e64
CW
1732 * @return CRM_Core_DAO_LocationType
1733 * location id of created location
6a488035 1734 */
00be9182 1735 public function locationTypeCreate($params = NULL) {
6a488035
TO
1736 if ($params === NULL) {
1737 $params = array(
1738 'name' => 'New Location Type',
1739 'vcard_name' => 'New Location Type',
1740 'description' => 'Location Type for Delete',
1741 'is_active' => 1,
1742 );
1743 }
1744
6a488035
TO
1745 $locationType = new CRM_Core_DAO_LocationType();
1746 $locationType->copyValues($params);
1747 $locationType->save();
1748 // clear getfields cache
2683ce94 1749 CRM_Core_PseudoConstant::flush();
f6722559 1750 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
6a488035
TO
1751 return $locationType;
1752 }
1753
1754 /**
eceb18cc 1755 * Delete a Location Type.
6a488035 1756 *
79d7553f 1757 * @param int $locationTypeId
6a488035 1758 */
00be9182 1759 public function locationTypeDelete($locationTypeId) {
6a488035
TO
1760 $locationType = new CRM_Core_DAO_LocationType();
1761 $locationType->id = $locationTypeId;
1762 $locationType->delete();
1763 }
1764
927f93e2
TM
1765 /**
1766 * Add a Mapping.
1767 *
1768 * @param array $params
1769 * @return CRM_Core_DAO_Mapping
1770 * Mapping id of created mapping
1771 */
1772 public function mappingCreate($params = NULL) {
1773 if ($params === NULL) {
1774 $params = array(
1775 'name' => 'Mapping name',
1776 'description' => 'Mapping description',
1777 // 'Export Contact' mapping.
1778 'mapping_type_id' => 7,
1779 );
1780 }
1781
1782 $mapping = new CRM_Core_DAO_Mapping();
1783 $mapping->copyValues($params);
1784 $mapping->save();
1785 // clear getfields cache
1786 CRM_Core_PseudoConstant::flush();
1787 $this->callAPISuccess('mapping', 'getfields', array('version' => 3, 'cache_clear' => 1));
1788 return $mapping;
1789 }
1790
1791 /**
1792 * Delete a Mapping
1793 *
1794 * @param int $mappingId
1795 */
1796 public function mappingDelete($mappingId) {
1797 $mapping = new CRM_Core_DAO_Mapping();
1798 $mapping->id = $mappingId;
1799 $mapping->delete();
1800 }
1801
6a488035 1802 /**
eceb18cc 1803 * Add a Group.
6a488035 1804 *
2a6da8d7 1805 * @param array $params
a6c01b45
CW
1806 * @return int
1807 * groupId of created group
6a488035 1808 */
00be9182 1809 public function groupCreate($params = array()) {
fadb804f 1810 $params = array_merge(array(
5896d037
TO
1811 'name' => 'Test Group 1',
1812 'domain_id' => 1,
1813 'title' => 'New Test Group Created',
1814 'description' => 'New Test Group Created',
1815 'is_active' => 1,
1816 'visibility' => 'Public Pages',
1817 'group_type' => array(
1818 '1' => 1,
1819 '2' => 1,
1820 ),
1821 ), $params);
6a488035 1822
f6722559 1823 $result = $this->callAPISuccess('Group', 'create', $params);
1824 return $result['id'];
6a488035
TO
1825 }
1826
5e8daa54 1827 /**
1828 * Prepare class for ACLs.
1829 */
1830 protected function prepareForACLs() {
1831 $config = CRM_Core_Config::singleton();
1832 $config->userPermissionClass->permissions = array();
1833 }
1834
1835 /**
1836 * Reset after ACLs.
1837 */
1838 protected function cleanUpAfterACLs() {
1839 CRM_Utils_Hook::singleton()->reset();
1840 $tablesToTruncate = array(
1841 'civicrm_acl',
1842 'civicrm_acl_cache',
1843 'civicrm_acl_entity_role',
1844 'civicrm_acl_contact_cache',
1845 );
1846 $this->quickCleanup($tablesToTruncate);
1847 $config = CRM_Core_Config::singleton();
1848 unset($config->userPermissionClass->permissions);
1849 }
c3137c08 1850 /**
1851 * Create a smart group.
1852 *
1853 * By default it will be a group of households.
1854 *
1855 * @param array $smartGroupParams
1856 * @param array $groupParams
1857 * @return int
1858 */
1859 public function smartGroupCreate($smartGroupParams = array(), $groupParams = array()) {
1860 $smartGroupParams = array_merge(array(
1861 'formValues' => array('contact_type' => array('IN' => array('Household'))),
1862 ),
1863 $smartGroupParams);
1864 $savedSearch = CRM_Contact_BAO_SavedSearch::create($smartGroupParams);
1865
1866 $groupParams['saved_search_id'] = $savedSearch->id;
1867 return $this->groupCreate($groupParams);
1868 }
7811a84b 1869
6c6e6187 1870 /**
eceb18cc 1871 * Function to add a Group.
ef643544 1872 *
7811a84b 1873 * @params array to add group
ef643544 1874 *
257e7666
EM
1875 * @param int $groupID
1876 * @param int $totalCount
6ec61f19 1877 * @param bool $random
a130e045
DG
1878 * @return int
1879 * groupId of created group
ef643544 1880 */
6ec61f19 1881 public function groupContactCreate($groupID, $totalCount = 10, $random = FALSE) {
ef643544 1882 $params = array('group_id' => $groupID);
6c6e6187 1883 for ($i = 1; $i <= $totalCount; $i++) {
6ec61f19 1884 $contactID = $this->individualCreate(array(), 0, $random);
ef643544 1885 if ($i == 1) {
1886 $params += array('contact_id' => $contactID);
1887 }
1888 else {
1889 $params += array("contact_id.$i" => $contactID);
1890 }
1891 }
1892 $result = $this->callAPISuccess('GroupContact', 'create', $params);
7811a84b 1893
ef643544 1894 return $result;
1895 }
1896
6a488035 1897 /**
eceb18cc 1898 * Delete a Group.
6a488035 1899 *
c490a46a 1900 * @param int $gid
6a488035 1901 */
00be9182 1902 public function groupDelete($gid) {
6a488035
TO
1903
1904 $params = array(
1905 'id' => $gid,
6a488035
TO
1906 );
1907
f6722559 1908 $this->callAPISuccess('Group', 'delete', $params);
6a488035
TO
1909 }
1910
5c496c74 1911 /**
eceb18cc 1912 * Create a UFField.
5c496c74 1913 * @param array $params
1914 */
00be9182 1915 public function uFFieldCreate($params = array()) {
5c496c74 1916 $params = array_merge(array(
1917 'uf_group_id' => 1,
1918 'field_name' => 'first_name',
1919 'is_active' => 1,
1920 'is_required' => 1,
1921 'visibility' => 'Public Pages and Listings',
1922 'is_searchable' => '1',
1923 'label' => 'first_name',
1924 'field_type' => 'Individual',
1925 'weight' => 1,
1926 ), $params);
1927 $this->callAPISuccess('uf_field', 'create', $params);
1928 }
2a6da8d7 1929
6a488035 1930 /**
eceb18cc 1931 * Add a UF Join Entry.
6a488035 1932 *
100fef9d 1933 * @param array $params
a6c01b45
CW
1934 * @return int
1935 * $id of created UF Join
6a488035 1936 */
00be9182 1937 public function ufjoinCreate($params = NULL) {
6a488035
TO
1938 if ($params === NULL) {
1939 $params = array(
1940 'is_active' => 1,
1941 'module' => 'CiviEvent',
1942 'entity_table' => 'civicrm_event',
1943 'entity_id' => 3,
1944 'weight' => 1,
1945 'uf_group_id' => 1,
1946 );
1947 }
f6722559 1948 $result = $this->callAPISuccess('uf_join', 'create', $params);
6a488035
TO
1949 return $result;
1950 }
1951
1952 /**
eceb18cc 1953 * Delete a UF Join Entry.
6a488035 1954 *
a130e045
DG
1955 * @param array $params
1956 * with missing uf_group_id
6a488035 1957 */
00be9182 1958 public function ufjoinDelete($params = NULL) {
6a488035
TO
1959 if ($params === NULL) {
1960 $params = array(
1961 'is_active' => 1,
1962 'module' => 'CiviEvent',
1963 'entity_table' => 'civicrm_event',
1964 'entity_id' => 3,
1965 'weight' => 1,
1966 'uf_group_id' => '',
1967 );
1968 }
1969
1970 crm_add_uf_join($params);
1971 }
1972
c03f1689
EM
1973 /**
1974 * @param array $params
1975 * Optional parameters.
d31d0888 1976 * @param bool $reloadConfig
1977 * While enabling CiviCampaign component, we shouldn't always forcibly
1978 * reload config as this hinder hook call in test environment
c03f1689
EM
1979 *
1980 * @return int
1981 * Campaign ID.
1982 */
d31d0888 1983 public function campaignCreate($params = array(), $reloadConfig = TRUE) {
1984 $this->enableCiviCampaign($reloadConfig);
c03f1689
EM
1985 $campaign = $this->callAPISuccess('campaign', 'create', array_merge(array(
1986 'name' => 'big_campaign',
1987 'title' => 'Campaign',
1988 ), $params));
1989 return $campaign['id'];
1990 }
1991
6a488035 1992 /**
eceb18cc 1993 * Create Group for a contact.
6a488035
TO
1994 *
1995 * @param int $contactId
1996 */
00be9182 1997 public function contactGroupCreate($contactId) {
6a488035
TO
1998 $params = array(
1999 'contact_id.1' => $contactId,
2000 'group_id' => 1,
2001 );
2002
f6722559 2003 $this->callAPISuccess('GroupContact', 'Create', $params);
6a488035
TO
2004 }
2005
2006 /**
eceb18cc 2007 * Delete Group for a contact.
6a488035 2008 *
100fef9d 2009 * @param int $contactId
6a488035 2010 */
00be9182 2011 public function contactGroupDelete($contactId) {
6a488035
TO
2012 $params = array(
2013 'contact_id.1' => $contactId,
2014 'group_id' => 1,
2015 );
0f643fb2 2016 $this->civicrm_api('GroupContact', 'Delete', $params);
6a488035
TO
2017 }
2018
2019 /**
eceb18cc 2020 * Create Activity.
6a488035 2021 *
c490a46a 2022 * @param array $params
2a6da8d7 2023 * @return array|int
6a488035 2024 */
5d8b37be 2025 public function activityCreate($params = array()) {
2026 $params = array_merge(array(
2027 'subject' => 'Discussion on warm beer',
2028 'activity_date_time' => date('Ymd'),
2029 'duration_hours' => 30,
2030 'duration_minutes' => 20,
2031 'location' => 'Baker Street',
2032 'details' => 'Lets schedule a meeting',
2033 'status_id' => 1,
2034 'activity_name' => 'Meeting',
2035 ), $params);
2036 if (!isset($params['source_contact_id'])) {
2037 $params['source_contact_id'] = $this->individualCreate();
2038 }
2039 if (!isset($params['target_contact_id'])) {
2040 $params['target_contact_id'] = $this->individualCreate(array(
6a488035
TO
2041 'first_name' => 'Julia',
2042 'Last_name' => 'Anderson',
2043 'prefix' => 'Ms.',
2044 'email' => 'julia_anderson@civicrm.org',
2045 'contact_type' => 'Individual',
5d8b37be 2046 ));
2047 }
2048 if (!isset($params['assignee_contact_id'])) {
2049 $params['assignee_contact_id'] = $params['target_contact_id'];
6a488035
TO
2050 }
2051
f6722559 2052 $result = $this->callAPISuccess('Activity', 'create', $params);
6a488035 2053
5d8b37be 2054 $result['target_contact_id'] = $params['target_contact_id'];
2055 $result['assignee_contact_id'] = $params['assignee_contact_id'];
6a488035
TO
2056 return $result;
2057 }
2058
2059 /**
eceb18cc 2060 * Create an activity type.
6a488035 2061 *
e16033b4
TO
2062 * @param array $params
2063 * Parameters.
f0be539a 2064 * @return array
6a488035 2065 */
00be9182 2066 public function activityTypeCreate($params) {
f0be539a 2067 return $this->callAPISuccess('ActivityType', 'create', $params);
79d7553f 2068 }
6a488035
TO
2069
2070 /**
eceb18cc 2071 * Delete activity type.
6a488035 2072 *
e16033b4
TO
2073 * @param int $activityTypeId
2074 * Id of the activity type.
f0be539a 2075 * @return array
6a488035 2076 */
00be9182 2077 public function activityTypeDelete($activityTypeId) {
6a488035 2078 $params['activity_type_id'] = $activityTypeId;
f0be539a 2079 return $this->callAPISuccess('ActivityType', 'delete', $params);
79d7553f 2080 }
6a488035
TO
2081
2082 /**
eceb18cc 2083 * Create custom group.
6a488035 2084 *
2a6da8d7 2085 * @param array $params
27dd6252 2086 * @return array
6a488035 2087 */
00be9182 2088 public function customGroupCreate($params = array()) {
f6722559 2089 $defaults = array(
2090 'title' => 'new custom group',
2091 'extends' => 'Contact',
2092 'domain_id' => 1,
2093 'style' => 'Inline',
2094 'is_active' => 1,
2095 );
6a488035 2096
f6722559 2097 $params = array_merge($defaults, $params);
2098
f6722559 2099 //have a crack @ deleting it first in the hope this will prevent derailing our tests
5896d037 2100 $this->callAPISuccess('custom_group', 'get', array(
92915c55
TO
2101 'title' => $params['title'],
2102 array('api.custom_group.delete' => 1),
2103 ));
6a488035 2104
f6722559 2105 return $this->callAPISuccess('custom_group', 'create', $params);
6a488035
TO
2106 }
2107
2108 /**
100fef9d 2109 * Existing function doesn't allow params to be over-ridden so need a new one
6a488035 2110 * this one allows you to only pass in the params you want to change
1e1fdcf6
EM
2111 * @param array $params
2112 * @return array|int
6a488035 2113 */
00be9182 2114 public function CustomGroupCreateByParams($params = array()) {
6a488035
TO
2115 $defaults = array(
2116 'title' => "API Custom Group",
2117 'extends' => 'Contact',
2118 'domain_id' => 1,
2119 'style' => 'Inline',
2120 'is_active' => 1,
6a488035
TO
2121 );
2122 $params = array_merge($defaults, $params);
f6722559 2123 return $this->callAPISuccess('custom_group', 'create', $params);
6a488035
TO
2124 }
2125
2126 /**
eceb18cc 2127 * Create custom group with multi fields.
1e1fdcf6
EM
2128 * @param array $params
2129 * @return array|int
6a488035 2130 */
00be9182 2131 public function CustomGroupMultipleCreateByParams($params = array()) {
6a488035
TO
2132 $defaults = array(
2133 'style' => 'Tab',
2134 'is_multiple' => 1,
2135 );
2136 $params = array_merge($defaults, $params);
f6722559 2137 return $this->CustomGroupCreateByParams($params);
6a488035
TO
2138 }
2139
2140 /**
eceb18cc 2141 * Create custom group with multi fields.
1e1fdcf6
EM
2142 * @param array $params
2143 * @return array
6a488035 2144 */
00be9182 2145 public function CustomGroupMultipleCreateWithFields($params = array()) {
6a488035
TO
2146 // also need to pass on $params['custom_field'] if not set but not in place yet
2147 $ids = array();
2148 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2149 $ids['custom_group_id'] = $customGroup['id'];
6a488035 2150
5896d037 2151 $customField = $this->customFieldCreate(array(
92915c55
TO
2152 'custom_group_id' => $ids['custom_group_id'],
2153 'label' => 'field_1' . $ids['custom_group_id'],
e525d6af 2154 'in_selector' => 1,
92915c55 2155 ));
6a488035
TO
2156
2157 $ids['custom_field_id'][] = $customField['id'];
f6722559 2158
5896d037 2159 $customField = $this->customFieldCreate(array(
92915c55
TO
2160 'custom_group_id' => $ids['custom_group_id'],
2161 'default_value' => '',
2162 'label' => 'field_2' . $ids['custom_group_id'],
e525d6af 2163 'in_selector' => 1,
92915c55 2164 ));
6a488035 2165 $ids['custom_field_id'][] = $customField['id'];
f6722559 2166
5896d037 2167 $customField = $this->customFieldCreate(array(
92915c55
TO
2168 'custom_group_id' => $ids['custom_group_id'],
2169 'default_value' => '',
2170 'label' => 'field_3' . $ids['custom_group_id'],
e525d6af 2171 'in_selector' => 1,
92915c55 2172 ));
6a488035 2173 $ids['custom_field_id'][] = $customField['id'];
f6722559 2174
6a488035
TO
2175 return $ids;
2176 }
2177
2178 /**
2179 * Create a custom group with a single text custom field. See
2180 * participant:testCreateWithCustom for how to use this
2181 *
e16033b4
TO
2182 * @param string $function
2183 * __FUNCTION__.
5a4f6742
CW
2184 * @param string $filename
2185 * $file __FILE__.
6a488035 2186 *
a6c01b45
CW
2187 * @return array
2188 * ids of created objects
6a488035 2189 */
00be9182 2190 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
f6722559 2191 $params = array('title' => $function);
6a488035 2192 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
6c6e6187 2193 $params['extends'] = $entity ? $entity : 'Contact';
f6722559 2194 $customGroup = $this->CustomGroupCreate($params);
b422b715 2195 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
80085473 2196 CRM_Core_PseudoConstant::flush();
6a488035
TO
2197
2198 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2199 }
2200
2201 /**
eceb18cc 2202 * Delete custom group.
6a488035 2203 *
8deefe64
EM
2204 * @param int $customGroupID
2205 *
2206 * @return array|int
6a488035 2207 */
00be9182 2208 public function customGroupDelete($customGroupID) {
6a488035 2209 $params['id'] = $customGroupID;
f6722559 2210 return $this->callAPISuccess('custom_group', 'delete', $params);
6a488035
TO
2211 }
2212
2213 /**
eceb18cc 2214 * Create custom field.
6a488035 2215 *
e16033b4
TO
2216 * @param array $params
2217 * (custom_group_id) is required.
507d3b64 2218 * @return array
6a488035 2219 */
00be9182 2220 public function customFieldCreate($params) {
b422b715 2221 $params = array_merge(array(
2222 'label' => 'Custom Field',
6a488035
TO
2223 'data_type' => 'String',
2224 'html_type' => 'Text',
2225 'is_searchable' => 1,
2226 'is_active' => 1,
5c496c74 2227 'default_value' => 'defaultValue',
b422b715 2228 ), $params);
6a488035 2229
5c496c74 2230 $result = $this->callAPISuccess('custom_field', 'create', $params);
507d3b64
EM
2231 // these 2 functions are called with force to flush static caches
2232 CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
2233 CRM_Core_Component::getEnabledComponents(1);
2234 return $result;
6a488035
TO
2235 }
2236
2237 /**
eceb18cc 2238 * Delete custom field.
6a488035
TO
2239 *
2240 * @param int $customFieldID
8deefe64
EM
2241 *
2242 * @return array|int
6a488035 2243 */
00be9182 2244 public function customFieldDelete($customFieldID) {
6a488035
TO
2245
2246 $params['id'] = $customFieldID;
f6722559 2247 return $this->callAPISuccess('custom_field', 'delete', $params);
6a488035
TO
2248 }
2249
2250 /**
eceb18cc 2251 * Create note.
6a488035 2252 *
100fef9d 2253 * @param int $cId
a6c01b45 2254 * @return array
6a488035 2255 */
00be9182 2256 public function noteCreate($cId) {
6a488035
TO
2257 $params = array(
2258 'entity_table' => 'civicrm_contact',
2259 'entity_id' => $cId,
2260 'note' => 'hello I am testing Note',
2261 'contact_id' => $cId,
2262 'modified_date' => date('Ymd'),
2263 'subject' => 'Test Note',
6a488035
TO
2264 );
2265
f6722559 2266 return $this->callAPISuccess('Note', 'create', $params);
6a488035
TO
2267 }
2268
07fd63f5 2269 /**
eceb18cc 2270 * Enable CiviCampaign Component.
d31d0888 2271 *
2272 * @param bool $reloadConfig
2273 * Force relaod config or not
07fd63f5 2274 */
d31d0888 2275 public function enableCiviCampaign($reloadConfig = TRUE) {
07fd63f5 2276 CRM_Core_BAO_ConfigSetting::enableComponent('CiviCampaign');
d31d0888 2277 if ($reloadConfig) {
2278 // force reload of config object
2279 $config = CRM_Core_Config::singleton(TRUE, TRUE);
2280 }
07fd63f5
E
2281 //flush cache by calling with reset
2282 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2283 }
2284
6a488035
TO
2285 /**
2286 * Create test generated example in api/v3/examples.
78373706 2287 *
6a488035
TO
2288 * To turn this off (e.g. on the server) set
2289 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2290 * in your settings file
78373706 2291 *
a828d7b8
CW
2292 * @param string $entity
2293 * @param string $action
e16033b4
TO
2294 * @param array $params
2295 * Array as passed to civicrm_api function.
2296 * @param array $result
2297 * Array as received from the civicrm_api function.
a828d7b8 2298 * @param string $testFunction
e16033b4 2299 * Calling function - generally __FUNCTION__.
a828d7b8 2300 * @param string $testFile
e16033b4
TO
2301 * Called from file - generally __FILE__.
2302 * @param string $description
2303 * Descriptive text for the example file.
a828d7b8 2304 * @param string $exampleName
e4f46be0 2305 * Name for this example file (CamelCase) - if omitted the action name will be substituted.
6a488035 2306 */
a828d7b8 2307 private function documentMe($entity, $action, $params, $result, $testFunction, $testFile, $description = "", $exampleName = NULL) {
d2d04435 2308 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG) {
6a488035
TO
2309 return;
2310 }
a828d7b8
CW
2311 $entity = _civicrm_api_get_camel_name($entity);
2312 $action = strtolower($action);
2313
2314 if (empty($exampleName)) {
2315 // Attempt to convert lowercase action name to CamelCase.
2316 // This is clunky/imperfect due to the convention of all lowercase actions.
2317 $exampleName = CRM_Utils_String::convertStringToCamel($action);
2318 $knownPrefixes = array(
2319 'Get',
2320 'Set',
2321 'Create',
2322 'Update',
2323 'Send',
2324 );
2325 foreach ($knownPrefixes as $prefix) {
2326 if (strpos($exampleName, $prefix) === 0 && $prefix != $exampleName) {
2327 $exampleName[strlen($prefix)] = strtoupper($exampleName[strlen($prefix)]);
2328 }
6a488035
TO
2329 }
2330 }
6a488035 2331
fdd48527 2332 $this->tidyExampleResult($result);
5896d037 2333 if (isset($params['version'])) {
fb32de45 2334 unset($params['version']);
2335 }
5c49fee0
CW
2336 // Format multiline description as array
2337 $desc = array();
2338 if (is_string($description) && strlen($description)) {
2339 foreach (explode("\n", $description) as $line) {
2340 $desc[] = trim($line);
2341 }
2342 }
6a488035 2343 $smarty = CRM_Core_Smarty::singleton();
a828d7b8
CW
2344 $smarty->assign('testFunction', $testFunction);
2345 $smarty->assign('function', _civicrm_api_get_entity_name_from_camel($entity) . "_$action");
f0345440 2346 foreach ($params as $index => $param) {
2347 if (is_string($param)) {
2348 $params[$index] = addslashes($param);
2349 }
2350 }
6a488035
TO
2351 $smarty->assign('params', $params);
2352 $smarty->assign('entity', $entity);
a828d7b8 2353 $smarty->assign('testFile', basename($testFile));
5c49fee0 2354 $smarty->assign('description', $desc);
6a488035 2355 $smarty->assign('result', $result);
6a488035 2356 $smarty->assign('action', $action);
a828d7b8 2357
93afbc3a 2358 global $civicrm_root;
2359 if (file_exists($civicrm_root . '/tests/templates/documentFunction.tpl')) {
68e23469
MM
2360 if (!is_dir($civicrm_root . "/api/v3/examples/$entity")) {
2361 mkdir($civicrm_root . "/api/v3/examples/$entity");
6a488035 2362 }
93afbc3a 2363 $f = fopen($civicrm_root . "/api/v3/examples/$entity/$exampleName.php", "w+b");
2364 fwrite($f, $smarty->fetch($civicrm_root . '/tests/templates/documentFunction.tpl'));
3ec6e38d 2365 fclose($f);
6a488035
TO
2366 }
2367 }
2368
fdd48527 2369 /**
2370 * Tidy up examples array so that fields that change often ..don't
2371 * and debug related fields are unset
2a6da8d7 2372 *
c490a46a 2373 * @param array $result
fdd48527 2374 */
5896d037
TO
2375 public function tidyExampleResult(&$result) {
2376 if (!is_array($result)) {
fdd48527 2377 return;
2378 }
2379 $fieldsToChange = array(
2380 'hash' => '67eac7789eaee00',
2381 'modified_date' => '2012-11-14 16:02:35',
f27f2724 2382 'created_date' => '2013-07-28 08:49:19',
fdd48527 2383 'create_date' => '20120130621222105',
f27f2724 2384 'application_received_date' => '20130728084957',
2385 'in_date' => '2013-07-28 08:50:19',
2386 'scheduled_date' => '20130728085413',
2387 'approval_date' => '20130728085413',
2388 'pledge_start_date_high' => '20130726090416',
9f1b81e0 2389 'start_date' => '2013-07-29 00:00:00',
2390 'event_start_date' => '2013-07-29 00:00:00',
2391 'end_date' => '2013-08-04 00:00:00',
2392 'event_end_date' => '2013-08-04 00:00:00',
2393 'decision_date' => '20130805000000',
fdd48527 2394 );
2395
6c6e6187 2396 $keysToUnset = array('xdebug', 'undefined_fields');
fdd48527 2397 foreach ($keysToUnset as $unwantedKey) {
5896d037 2398 if (isset($result[$unwantedKey])) {
fdd48527 2399 unset($result[$unwantedKey]);
2400 }
2401 }
9f1b81e0 2402 if (isset($result['values'])) {
5896d037 2403 if (!is_array($result['values'])) {
9f1b81e0 2404 return;
2405 }
2406 $resultArray = &$result['values'];
2407 }
5896d037 2408 elseif (is_array($result)) {
9f1b81e0 2409 $resultArray = &$result;
2410 }
2411 else {
2412 return;
2413 }
fdd48527 2414
9f1b81e0 2415 foreach ($resultArray as $index => &$values) {
5896d037 2416 if (!is_array($values)) {
6c6e6187
TO
2417 continue;
2418 }
5896d037
TO
2419 foreach ($values as $key => &$value) {
2420 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2421 if (isset($value['is_error'])) {
6c6e6187
TO
2422 // we have a std nested result format
2423 $this->tidyExampleResult($value);
fdd48527 2424 }
5896d037 2425 else {
6c6e6187
TO
2426 foreach ($value as &$nestedResult) {
2427 // this is an alternative syntax for nested results a keyed array of results
2428 $this->tidyExampleResult($nestedResult);
2429 }
b25fe59a 2430 }
fdd48527 2431 }
5896d037 2432 if (in_array($key, $keysToUnset)) {
6c6e6187
TO
2433 unset($values[$key]);
2434 break;
2435 }
5896d037 2436 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
6c6e6187
TO
2437 $value = $fieldsToChange[$key];
2438 }
5896d037 2439 if (is_string($value)) {
6c6e6187
TO
2440 $value = addslashes($value);
2441 }
2442 }
fdd48527 2443 }
2444 }
2445
6a488035 2446 /**
eceb18cc 2447 * Create custom field with Option Values.
6a488035 2448 *
77b97be7 2449 * @param array $customGroup
e16033b4
TO
2450 * @param string $name
2451 * Name of custom field.
412585fb 2452 * @param array $extraParams
2453 * Additional parameters to pass through.
77b97be7
EM
2454 *
2455 * @return array|int
6a488035 2456 */
412585fb 2457 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
6a488035
TO
2458 $fieldParams = array(
2459 'custom_group_id' => $customGroup['id'],
2460 'name' => 'test_custom_group',
2461 'label' => 'Country',
2462 'html_type' => 'Select',
2463 'data_type' => 'String',
2464 'weight' => 4,
2465 'is_required' => 1,
2466 'is_searchable' => 0,
2467 'is_active' => 1,
6a488035
TO
2468 );
2469
2470 $optionGroup = array(
2471 'domain_id' => 1,
2472 'name' => 'option_group1',
2473 'label' => 'option_group_label1',
2474 );
2475
2476 $optionValue = array(
2477 'option_label' => array('Label1', 'Label2'),
2478 'option_value' => array('value1', 'value2'),
2479 'option_name' => array($name . '_1', $name . '_2'),
2480 'option_weight' => array(1, 2),
2481 'option_status' => 1,
2482 );
2483
412585fb 2484 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
6a488035 2485
f6722559 2486 return $this->callAPISuccess('custom_field', 'create', $params);
6a488035
TO
2487 }
2488
4cbe18b8
EM
2489 /**
2490 * @param $entities
2491 *
2492 * @return bool
2493 */
00be9182 2494 public function confirmEntitiesDeleted($entities) {
6a488035
TO
2495 foreach ($entities as $entity) {
2496
f6722559 2497 $result = $this->callAPISuccess($entity, 'Get', array());
6a488035
TO
2498 if ($result['error'] == 1 || $result['count'] > 0) {
2499 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2500 return TRUE;
2501 }
2502 }
f0be539a 2503 return FALSE;
6a488035
TO
2504 }
2505
4cbe18b8 2506 /**
0fff773f 2507 * Quick clean by emptying tables created for the test.
2508 *
2509 * @param array $tablesToTruncate
4cbe18b8 2510 * @param bool $dropCustomValueTables
507d3b64 2511 * @throws \Exception
4cbe18b8 2512 */
00be9182 2513 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
d67f1f28
TO
2514 if ($this->tx) {
2515 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2516 }
6a488035 2517 if ($dropCustomValueTables) {
0fff773f 2518 $optionGroupResult = CRM_Core_DAO::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
2519 while ($optionGroupResult->fetch()) {
2520 if (!empty($optionGroupResult->option_group_id)) {
2521 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id);
2522 }
2523 }
6a488035
TO
2524 $tablesToTruncate[] = 'civicrm_custom_group';
2525 $tablesToTruncate[] = 'civicrm_custom_field';
2526 }
2527
0b6f58fa
ARW
2528 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate, $tablesToTruncate));
2529
6a488035
TO
2530 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2531 foreach ($tablesToTruncate as $table) {
2532 $sql = "TRUNCATE TABLE $table";
2533 CRM_Core_DAO::executeQuery($sql);
2534 }
2535 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2536
2537 if ($dropCustomValueTables) {
2538 $dbName = self::getDBName();
2539 $query = "
2540SELECT TABLE_NAME as tableName
2541FROM INFORMATION_SCHEMA.TABLES
2542WHERE TABLE_SCHEMA = '{$dbName}'
2543AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2544";
2545
2546 $tableDAO = CRM_Core_DAO::executeQuery($query);
2547 while ($tableDAO->fetch()) {
2548 $sql = "DROP TABLE {$tableDAO->tableName}";
2549 CRM_Core_DAO::executeQuery($sql);
2550 }
2551 }
2552 }
2553
b38530f2
EM
2554 /**
2555 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2556 */
00be9182 2557 public function quickCleanUpFinancialEntities() {
b38530f2 2558 $tablesToTruncate = array(
a380f4a0
EM
2559 'civicrm_activity',
2560 'civicrm_activity_contact',
b38530f2 2561 'civicrm_contribution',
39d632fd 2562 'civicrm_contribution_soft',
945f423d 2563 'civicrm_contribution_product',
b38530f2 2564 'civicrm_financial_trxn',
39d632fd 2565 'civicrm_financial_item',
b38530f2
EM
2566 'civicrm_contribution_recur',
2567 'civicrm_line_item',
2568 'civicrm_contribution_page',
2569 'civicrm_payment_processor',
2570 'civicrm_entity_financial_trxn',
2571 'civicrm_membership',
2572 'civicrm_membership_type',
2573 'civicrm_membership_payment',
cab024d4 2574 'civicrm_membership_log',
f9342903 2575 'civicrm_membership_block',
b38530f2
EM
2576 'civicrm_event',
2577 'civicrm_participant',
2578 'civicrm_participant_payment',
2579 'civicrm_pledge',
294cc627 2580 'civicrm_pledge_payment',
1cf3c2b1 2581 'civicrm_price_set_entity',
108ff21a
EM
2582 'civicrm_price_field_value',
2583 'civicrm_price_field',
b38530f2
EM
2584 );
2585 $this->quickCleanup($tablesToTruncate);
4278b952 2586 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
108ff21a 2587 $this->restoreDefaultPriceSetConfig();
6d8a45ed
EM
2588 $var = TRUE;
2589 CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE);
9fbf312f 2590 $this->disableTaxAndInvoicing();
83644f47 2591 $this->setCurrencySeparators(',');
2592 CRM_Core_PseudoConstant::flush('taxRates');
7a3b0ca3 2593 System::singleton()->flushProcessors();
108ff21a
EM
2594 }
2595
00be9182 2596 public function restoreDefaultPriceSetConfig() {
cdd71d6b 2597 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
2598 CRM_Core_DAO::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
108ff21a 2599 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)");
5afce5ad 2600 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`, `non_deductible_amount`) VALUES (1, 1, 'contribution_amount', 'Contribution Amount', NULL, '1', NULL, NULL, 1, NULL, NULL, 0, 1, 1, 0.00)");
b38530f2 2601 }
6a488035
TO
2602 /*
2603 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2604 * Default behaviour is to also delete the entity
e16033b4 2605 * @param array $params
e4f46be0 2606 * Params array to check against.
e16033b4
TO
2607 * @param int $id
2608 * Id of the entity concerned.
2609 * @param string $entity
2610 * Name of entity concerned (e.g. membership).
2611 * @param bool $delete
2612 * Should the entity be deleted as part of this check.
2613 * @param string $errorText
2614 * Text to print on error.
6a488035 2615 */
4cbe18b8 2616 /**
c490a46a 2617 * @param array $params
100fef9d 2618 * @param int $id
4cbe18b8
EM
2619 * @param $entity
2620 * @param int $delete
2621 * @param string $errorText
2622 *
2623 * @throws Exception
2624 */
00be9182 2625 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
6a488035 2626
f6722559 2627 $result = $this->callAPISuccessGetSingle($entity, array(
6a488035 2628 'id' => $id,
6a488035
TO
2629 ));
2630
2631 if ($delete) {
f6722559 2632 $this->callAPISuccess($entity, 'Delete', array(
6a488035 2633 'id' => $id,
6a488035
TO
2634 ));
2635 }
b0aaad8c 2636 $dateFields = $keys = $dateTimeFields = array();
f6722559 2637 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
6a488035
TO
2638 foreach ($fields['values'] as $field => $settings) {
2639 if (array_key_exists($field, $result)) {
2640 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = $field;
2641 }
2642 else {
2643 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = CRM_Utils_Array::value('name', $settings, $field);
2644 }
afd404ea 2645 $type = CRM_Utils_Array::value('type', $settings);
2646 if ($type == CRM_Utils_Type::T_DATE) {
2647 $dateFields[] = $settings['name'];
2648 // we should identify both real names & unique names as dates
5896d037 2649 if ($field != $settings['name']) {
afd404ea 2650 $dateFields[] = $field;
2651 }
2652 }
5896d037 2653 if ($type == CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) {
afd404ea 2654 $dateTimeFields[] = $settings['name'];
2655 // we should identify both real names & unique names as dates
5896d037 2656 if ($field != $settings['name']) {
afd404ea 2657 $dateTimeFields[] = $field;
2658 }
6a488035
TO
2659 }
2660 }
2661
2662 if (strtolower($entity) == 'contribution') {
2663 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2664 // this is not returned in id format
2665 unset($params['payment_instrument_id']);
2666 $params['contribution_source'] = $params['source'];
2667 unset($params['source']);
2668 }
2669
2670 foreach ($params as $key => $value) {
afd404ea 2671 if ($key == 'version' || substr($key, 0, 3) == 'api' || !array_key_exists($keys[$key], $result)) {
6a488035
TO
2672 continue;
2673 }
2674 if (in_array($key, $dateFields)) {
2675 $value = date('Y-m-d', strtotime($value));
2676 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2677 }
afd404ea 2678 if (in_array($key, $dateTimeFields)) {
2679 $value = date('Y-m-d H:i:s', strtotime($value));
a72cec08 2680 $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 2681 }
2682 $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
2683 }
2684 }
2685
2686 /**
eceb18cc 2687 * Get formatted values in the actual and expected result.
e16033b4
TO
2688 * @param array $actual
2689 * Actual calculated values.
2690 * @param array $expected
2691 * Expected values.
6a488035 2692 */
00be9182 2693 public function checkArrayEquals(&$actual, &$expected) {
6a488035
TO
2694 self::unsetId($actual);
2695 self::unsetId($expected);
2696 $this->assertEquals($actual, $expected);
2697 }
2698
2699 /**
100fef9d 2700 * Unset the key 'id' from the array
e16033b4
TO
2701 * @param array $unformattedArray
2702 * The array from which the 'id' has to be unset.
6a488035 2703 */
00be9182 2704 public static function unsetId(&$unformattedArray) {
6a488035
TO
2705 $formattedArray = array();
2706 if (array_key_exists('id', $unformattedArray)) {
2707 unset($unformattedArray['id']);
2708 }
a7488080 2709 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
6a488035 2710 foreach ($unformattedArray['values'] as $key => $value) {
6c6e6187 2711 if (is_array($value)) {
6a488035
TO
2712 foreach ($value as $k => $v) {
2713 if ($k == 'id') {
2714 unset($value[$k]);
2715 }
2716 }
2717 }
2718 elseif ($key == 'id') {
2719 $unformattedArray[$key];
2720 }
2721 $formattedArray = array($value);
2722 }
2723 $unformattedArray['values'] = $formattedArray;
2724 }
2725 }
2726
2727 /**
2728 * Helper to enable/disable custom directory support
2729 *
e16033b4
TO
2730 * @param array $customDirs
2731 * With members:.
6a488035
TO
2732 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2733 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2734 */
00be9182 2735 public function customDirectories($customDirs) {
6a488035
TO
2736 $config = CRM_Core_Config::singleton();
2737
2738 if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
2739 unset($config->customPHPPathDir);
2740 }
2741 elseif ($customDirs['php_path'] === TRUE) {
2742 $config->customPHPPathDir = dirname(dirname(__FILE__)) . '/custom_directories/php/';
2743 }
2744 else {
2745 $config->customPHPPathDir = $php_path;
2746 }
2747
2748 if (empty($customDirs['template_path']) || $customDirs['template_path'] === FALSE) {
2749 unset($config->customTemplateDir);
2750 }
2751 elseif ($customDirs['template_path'] === TRUE) {
2752 $config->customTemplateDir = dirname(dirname(__FILE__)) . '/custom_directories/templates/';
2753 }
2754 else {
2755 $config->customTemplateDir = $template_path;
2756 }
2757 }
2758
2759 /**
eceb18cc 2760 * Generate a temporary folder.
6a488035 2761 *
2a6da8d7 2762 * @param string $prefix
a6c01b45 2763 * @return string
6a488035 2764 */
00be9182 2765 public function createTempDir($prefix = 'test-') {
6a488035
TO
2766 $tempDir = CRM_Utils_File::tempdir($prefix);
2767 $this->tempDirs[] = $tempDir;
2768 return $tempDir;
2769 }
2770
00be9182 2771 public function cleanTempDirs() {
6a488035
TO
2772 if (!is_array($this->tempDirs)) {
2773 // fix test errors where this is not set
2774 return;
2775 }
2776 foreach ($this->tempDirs as $tempDir) {
2777 if (is_dir($tempDir)) {
2778 CRM_Utils_File::cleanDir($tempDir, TRUE, FALSE);
2779 }
2780 }
2781 }
2782
2783 /**
eceb18cc 2784 * Temporarily replace the singleton extension with a different one.
1e1fdcf6 2785 * @param \CRM_Extension_System $system
6a488035 2786 */
00be9182 2787 public function setExtensionSystem(CRM_Extension_System $system) {
6a488035
TO
2788 if ($this->origExtensionSystem == NULL) {
2789 $this->origExtensionSystem = CRM_Extension_System::singleton();
2790 }
2791 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2792 }
2793
00be9182 2794 public function unsetExtensionSystem() {
6a488035
TO
2795 if ($this->origExtensionSystem !== NULL) {
2796 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2797 $this->origExtensionSystem = NULL;
2798 }
2799 }
f17d75bb 2800
076d8c82
TO
2801 /**
2802 * Temporarily alter the settings-metadata to add a mock setting.
2803 *
2804 * WARNING: The setting metadata will disappear on the next cache-clear.
2805 *
2806 * @param $extras
2807 * @return void
2808 */
00be9182 2809 public function setMockSettingsMetaData($extras) {
e1d39824 2810 Civi::service('settings_manager')->flush();
076d8c82 2811
5896d037
TO
2812 CRM_Utils_Hook::singleton()
2813 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2814 $metadata = array_merge($metadata, $extras);
2815 });
076d8c82
TO
2816
2817 $fields = $this->callAPISuccess('setting', 'getfields', array());
2818 foreach ($extras as $key => $spec) {
2819 $this->assertNotEmpty($spec['title']);
2820 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2821 }
2822 }
2823
4cbe18b8 2824 /**
100fef9d 2825 * @param string $name
4cbe18b8 2826 */
00be9182 2827 public function financialAccountDelete($name) {
f17d75bb
PN
2828 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2829 $financialAccount->name = $name;
5896d037 2830 if ($financialAccount->find(TRUE)) {
f17d75bb
PN
2831 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2832 $entityFinancialType->financial_account_id = $financialAccount->id;
2833 $entityFinancialType->delete();
2834 $financialAccount->delete();
2835 }
2836 }
fb32de45 2837
2b7d3f8a 2838 /**
2839 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2840 * (NB unclear if this is still required)
2841 */
00be9182 2842 public function _sethtmlGlobals() {
2b7d3f8a 2843 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2844 'required' => array(
2845 'html_quickform_rule_required',
21dfd5f5 2846 'HTML/QuickForm/Rule/Required.php',
2b7d3f8a 2847 ),
2848 'maxlength' => array(
2849 'html_quickform_rule_range',
21dfd5f5 2850 'HTML/QuickForm/Rule/Range.php',
2b7d3f8a 2851 ),
2852 'minlength' => array(
2853 'html_quickform_rule_range',
21dfd5f5 2854 'HTML/QuickForm/Rule/Range.php',
2b7d3f8a 2855 ),
2856 'rangelength' => array(
2857 'html_quickform_rule_range',
21dfd5f5 2858 'HTML/QuickForm/Rule/Range.php',
2b7d3f8a 2859 ),
2860 'email' => array(
2861 'html_quickform_rule_email',
21dfd5f5 2862 'HTML/QuickForm/Rule/Email.php',
2b7d3f8a 2863 ),
2864 'regex' => array(
2865 'html_quickform_rule_regex',
21dfd5f5 2866 'HTML/QuickForm/Rule/Regex.php',
2b7d3f8a 2867 ),
2868 'lettersonly' => array(
2869 'html_quickform_rule_regex',
21dfd5f5 2870 'HTML/QuickForm/Rule/Regex.php',
2b7d3f8a 2871 ),
2872 'alphanumeric' => array(
2873 'html_quickform_rule_regex',
21dfd5f5 2874 'HTML/QuickForm/Rule/Regex.php',
2b7d3f8a 2875 ),
2876 'numeric' => array(
2877 'html_quickform_rule_regex',
21dfd5f5 2878 'HTML/QuickForm/Rule/Regex.php',
2b7d3f8a 2879 ),
2880 'nopunctuation' => array(
2881 'html_quickform_rule_regex',
21dfd5f5 2882 'HTML/QuickForm/Rule/Regex.php',
2b7d3f8a 2883 ),
2884 'nonzero' => array(
2885 'html_quickform_rule_regex',
21dfd5f5 2886 'HTML/QuickForm/Rule/Regex.php',
2b7d3f8a 2887 ),
2888 'callback' => array(
2889 'html_quickform_rule_callback',
21dfd5f5 2890 'HTML/QuickForm/Rule/Callback.php',
2b7d3f8a 2891 ),
2892 'compare' => array(
2893 'html_quickform_rule_compare',
21dfd5f5
TO
2894 'HTML/QuickForm/Rule/Compare.php',
2895 ),
2b7d3f8a 2896 );
2897 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2898 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2899 'group' => array(
2900 'HTML/QuickForm/group.php',
21dfd5f5 2901 'HTML_QuickForm_group',
2b7d3f8a 2902 ),
2903 'hidden' => array(
2904 'HTML/QuickForm/hidden.php',
21dfd5f5 2905 'HTML_QuickForm_hidden',
2b7d3f8a 2906 ),
2907 'reset' => array(
2908 'HTML/QuickForm/reset.php',
21dfd5f5 2909 'HTML_QuickForm_reset',
2b7d3f8a 2910 ),
2911 'checkbox' => array(
2912 'HTML/QuickForm/checkbox.php',
21dfd5f5 2913 'HTML_QuickForm_checkbox',
2b7d3f8a 2914 ),
2915 'file' => array(
2916 'HTML/QuickForm/file.php',
21dfd5f5 2917 'HTML_QuickForm_file',
2b7d3f8a 2918 ),
2919 'image' => array(
2920 'HTML/QuickForm/image.php',
21dfd5f5 2921 'HTML_QuickForm_image',
2b7d3f8a 2922 ),
2923 'password' => array(
2924 'HTML/QuickForm/password.php',
21dfd5f5 2925 'HTML_QuickForm_password',
2b7d3f8a 2926 ),
2927 'radio' => array(
2928 'HTML/QuickForm/radio.php',
21dfd5f5 2929 'HTML_QuickForm_radio',
2b7d3f8a 2930 ),
2931 'button' => array(
2932 'HTML/QuickForm/button.php',
21dfd5f5 2933 'HTML_QuickForm_button',
2b7d3f8a 2934 ),
2935 'submit' => array(
2936 'HTML/QuickForm/submit.php',
21dfd5f5 2937 'HTML_QuickForm_submit',
2b7d3f8a 2938 ),
2939 'select' => array(
2940 'HTML/QuickForm/select.php',
21dfd5f5 2941 'HTML_QuickForm_select',
2b7d3f8a 2942 ),
2943 'hiddenselect' => array(
2944 'HTML/QuickForm/hiddenselect.php',
21dfd5f5 2945 'HTML_QuickForm_hiddenselect',
2b7d3f8a 2946 ),
2947 'text' => array(
2948 'HTML/QuickForm/text.php',
21dfd5f5 2949 'HTML_QuickForm_text',
2b7d3f8a 2950 ),
2951 'textarea' => array(
2952 'HTML/QuickForm/textarea.php',
21dfd5f5 2953 'HTML_QuickForm_textarea',
2b7d3f8a 2954 ),
2955 'fckeditor' => array(
2956 'HTML/QuickForm/fckeditor.php',
21dfd5f5 2957 'HTML_QuickForm_FCKEditor',
2b7d3f8a 2958 ),
2959 'tinymce' => array(
2960 'HTML/QuickForm/tinymce.php',
21dfd5f5 2961 'HTML_QuickForm_TinyMCE',
2b7d3f8a 2962 ),
2963 'dojoeditor' => array(
2964 'HTML/QuickForm/dojoeditor.php',
21dfd5f5 2965 'HTML_QuickForm_dojoeditor',
2b7d3f8a 2966 ),
2967 'link' => array(
2968 'HTML/QuickForm/link.php',
21dfd5f5 2969 'HTML_QuickForm_link',
2b7d3f8a 2970 ),
2971 'advcheckbox' => array(
2972 'HTML/QuickForm/advcheckbox.php',
21dfd5f5 2973 'HTML_QuickForm_advcheckbox',
2b7d3f8a 2974 ),
2975 'date' => array(
2976 'HTML/QuickForm/date.php',
21dfd5f5 2977 'HTML_QuickForm_date',
2b7d3f8a 2978 ),
2979 'static' => array(
2980 'HTML/QuickForm/static.php',
21dfd5f5 2981 'HTML_QuickForm_static',
2b7d3f8a 2982 ),
2983 'header' => array(
2984 'HTML/QuickForm/header.php',
21dfd5f5 2985 'HTML_QuickForm_header',
2b7d3f8a 2986 ),
2987 'html' => array(
2988 'HTML/QuickForm/html.php',
21dfd5f5 2989 'HTML_QuickForm_html',
2b7d3f8a 2990 ),
2991 'hierselect' => array(
2992 'HTML/QuickForm/hierselect.php',
21dfd5f5 2993 'HTML_QuickForm_hierselect',
2b7d3f8a 2994 ),
2995 'autocomplete' => array(
2996 'HTML/QuickForm/autocomplete.php',
21dfd5f5 2997 'HTML_QuickForm_autocomplete',
2b7d3f8a 2998 ),
2999 'xbutton' => array(
3000 'HTML/QuickForm/xbutton.php',
21dfd5f5 3001 'HTML_QuickForm_xbutton',
2b7d3f8a 3002 ),
3003 'advmultiselect' => array(
3004 'HTML/QuickForm/advmultiselect.php',
21dfd5f5
TO
3005 'HTML_QuickForm_advmultiselect',
3006 ),
2b7d3f8a 3007 );
3008 }
3009
48e399ac
EM
3010 /**
3011 * Set up an acl allowing contact to see 2 specified groups
c206647d 3012 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
48e399ac 3013 *
c206647d 3014 * You need to have pre-created these groups & created the user e.g
48e399ac
EM
3015 * $this->createLoggedInUser();
3016 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
3017 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
ea3ddccf 3018 *
3019 * @param bool $isProfile
48e399ac 3020 */
181f536c 3021 public function setupACL($isProfile = FALSE) {
aaac0e0b
EM
3022 global $_REQUEST;
3023 $_REQUEST = $this->_params;
108ff21a 3024
48e399ac
EM
3025 CRM_Core_Config::singleton()->userPermissionClass->permissions = array('access CiviCRM');
3026 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
e5720c45
SL
3027 $ov = new CRM_Core_DAO_OptionValue();
3028 $ov->option_group_id = $optionGroupID;
3029 $ov->value = 55;
3030 if ($ov->find(TRUE)) {
3031 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
3032 }
6c6e6187 3033 $optionValue = $this->callAPISuccess('option_value', 'create', array(
5896d037 3034 'option_group_id' => $optionGroupID,
48e399ac
EM
3035 'label' => 'pick me',
3036 'value' => 55,
3037 ));
3038
48e399ac
EM
3039 CRM_Core_DAO::executeQuery("
3040 TRUNCATE civicrm_acl_cache
3041 ");
3042
3043 CRM_Core_DAO::executeQuery("
3044 TRUNCATE civicrm_acl_contact_cache
3045 ");
3046
48e399ac
EM
3047 CRM_Core_DAO::executeQuery("
3048 INSERT INTO civicrm_acl_entity_role (
181f536c 3049 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
3050 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
48e399ac
EM
3051 ");
3052
181f536c 3053 if ($isProfile) {
3054 CRM_Core_DAO::executeQuery("
3055 INSERT INTO civicrm_acl (
3056 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3057 )
3058 VALUES (
3059 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
3060 );
3061 ");
3062 }
3063 else {
3064 CRM_Core_DAO::executeQuery("
3065 INSERT INTO civicrm_acl (
3066 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3067 )
3068 VALUES (
3069 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3070 );
3071 ");
3072
3073 CRM_Core_DAO::executeQuery("
3074 INSERT INTO civicrm_acl (
3075 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3076 )
3077 VALUES (
3078 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3079 );
3080 ");
181f536c 3081 }
48e399ac 3082
48e399ac
EM
3083 $this->_loggedInUser = CRM_Core_Session::singleton()->get('userID');
3084 $this->callAPISuccess('group_contact', 'create', array(
3085 'group_id' => $this->_permissionedGroup,
3086 'contact_id' => $this->_loggedInUser,
3087 ));
08a2ea5e 3088
3089 if (!$isProfile) {
3090 //flush cache
3091 CRM_ACL_BAO_Cache::resetCache();
08a2ea5e 3092 CRM_ACL_API::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3093 }
48e399ac
EM
3094 }
3095
cab024d4 3096 /**
100fef9d 3097 * Alter default price set so that the field numbers are not all 1 (hiding errors)
cab024d4 3098 */
00be9182 3099 public function offsetDefaultPriceSet() {
cab024d4
EM
3100 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3101 $firstID = $contributionPriceSet['id'];
5896d037 3102 $this->callAPISuccess('price_set', 'create', array(
92915c55
TO
3103 'id' => $contributionPriceSet['id'],
3104 'is_active' => 0,
3105 'name' => 'old',
3106 ));
cab024d4
EM
3107 unset($contributionPriceSet['id']);
3108 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
5896d037 3109 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
92915c55
TO
3110 'price_set_id' => $firstID,
3111 'options' => array('limit' => 1),
3112 ));
cab024d4
EM
3113 unset($priceField['id']);
3114 $priceField['price_set_id'] = $newPriceSet['id'];
3115 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
5896d037 3116 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
92915c55
TO
3117 'price_set_id' => $firstID,
3118 'sequential' => 1,
3119 'options' => array('limit' => 1),
3120 ));
cab024d4
EM
3121
3122 unset($priceFieldValue['id']);
3123 //create some padding to use up ids
3124 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3125 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3126 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
cab024d4
EM
3127 }
3128
4aef704e 3129 /**
eceb18cc 3130 * Create an instance of the paypal processor.
4aef704e 3131 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3132 * this parent class & we don't have a structure for that yet
3133 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
e4f46be0 3134 * & the best protection against that is the functions this class affords
1e1fdcf6 3135 * @param array $params
79d7553f 3136 * @return int $result['id'] payment processor id
4aef704e 3137 */
00be9182 3138 public function paymentProcessorCreate($params = array()) {
4aef704e 3139 $params = array_merge(array(
5896d037
TO
3140 'name' => 'demo',
3141 'domain_id' => CRM_Core_Config::domainID(),
3142 'payment_processor_type_id' => 'PayPal',
3143 'is_active' => 1,
3144 'is_default' => 0,
3145 'is_test' => 1,
3146 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3147 'password' => '1183377788',
3148 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3149 'url_site' => 'https://www.sandbox.paypal.com/',
3150 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3151 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3152 'class_name' => 'Payment_PayPalImpl',
3153 'billing_mode' => 3,
3154 'financial_type_id' => 1,
43c8d1dd 3155 'financial_account_id' => 12,
f69a9ac3 3156 // Credit card = 1 so can pass 'by accident'.
3157 'payment_instrument_id' => 'Debit Card',
5896d037
TO
3158 ),
3159 $params);
3160 if (!is_numeric($params['payment_processor_type_id'])) {
4aef704e 3161 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3162 //here
3163 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3164 'name' => $params['payment_processor_type_id'],
3165 'return' => 'id',
3166 ), 'integer');
3167 }
3168 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3169 return $result['id'];
3170 }
a9ac877b 3171
0dbefed3 3172 /**
eceb18cc 3173 * Set up initial recurring payment allowing subsequent IPN payments.
0dbefed3 3174 */
b6b59c64 3175 public function setupRecurringPaymentProcessorTransaction($params = array()) {
3176 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
0dbefed3
EM
3177 'contact_id' => $this->_contactID,
3178 'amount' => 1000,
3179 'sequential' => 1,
3180 'installments' => 5,
3181 'frequency_unit' => 'Month',
3182 'frequency_interval' => 1,
3183 'invoice_id' => $this->_invoiceID,
3184 'contribution_status_id' => 2,
481312d9 3185 'payment_processor_id' => $this->_paymentProcessorID,
3186 // processor provided ID - use contact ID as proxy.
3187 'processor_id' => $this->_contactID,
0dbefed3
EM
3188 'api.contribution.create' => array(
3189 'total_amount' => '200',
3190 'invoice_id' => $this->_invoiceID,
3191 'financial_type_id' => 1,
3192 'contribution_status_id' => 'Pending',
3193 'contact_id' => $this->_contactID,
3194 'contribution_page_id' => $this->_contributionPageID,
3195 'payment_processor_id' => $this->_paymentProcessorID,
6b1b1558 3196 'is_test' => 0,
21dfd5f5 3197 ),
b6b59c64 3198 ), $params));
0dbefed3
EM
3199 $this->_contributionRecurID = $contributionRecur['id'];
3200 $this->_contributionID = $contributionRecur['values']['0']['api.contribution.create']['id'];
3201 }
a86d27fc 3202
a9ac877b 3203 /**
100fef9d 3204 * 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 3205 */
00be9182 3206 public function setupMembershipRecurringPaymentProcessorTransaction() {
a9ac877b 3207 $this->ids['membership_type'] = $this->membershipTypeCreate();
69140e67 3208 //create a contribution so our membership & contribution don't both have id = 1
b6b59c64 3209 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
3210 $this->contributionCreate(array(
3211 'contact_id' => $this->_contactID,
3212 'is_test' => 1,
3213 'financial_type_id' => 1,
3214 'invoice_id' => 'abcd',
3215 'trxn_id' => 345,
3216 ));
3217 }
69140e67
EM
3218 $this->setupRecurringPaymentProcessorTransaction();
3219
a9ac877b
EM
3220 $this->ids['membership'] = $this->callAPISuccess('membership', 'create', array(
3221 'contact_id' => $this->_contactID,
3222 'membership_type_id' => $this->ids['membership_type'],
3223 'contribution_recur_id' => $this->_contributionRecurID,
a9ac877b
EM
3224 'format.only_id' => TRUE,
3225 ));
69140e67
EM
3226 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3227 CRM_Core_DAO::executeQuery("TRUNCATE civicrm_line_item");
3228
3229 $this->callAPISuccess('line_item', 'create', array(
3230 'entity_table' => 'civicrm_membership',
3231 'entity_id' => $this->ids['membership'],
3232 'contribution_id' => $this->_contributionID,
3233 'label' => 'General',
3234 'qty' => 1,
3235 'unit_price' => 200,
3236 'line_total' => 200,
3237 'financial_type_id' => 1,
5896d037 3238 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
92915c55
TO
3239 'return' => 'id',
3240 'label' => 'Membership Amount',
b6b59c64 3241 'options' => array('limit' => 1, 'sort' => 'id DESC'),
92915c55 3242 )),
5896d037 3243 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
92915c55
TO
3244 'return' => 'id',
3245 'label' => 'General',
b6b59c64 3246 'options' => array('limit' => 1, 'sort' => 'id DESC'),
92915c55 3247 )),
69140e67 3248 ));
5896d037 3249 $this->callAPISuccess('membership_payment', 'create', array(
92915c55
TO
3250 'contribution_id' => $this->_contributionID,
3251 'membership_id' => $this->ids['membership'],
3252 ));
a9ac877b 3253 }
6a488035 3254
4cbe18b8
EM
3255 /**
3256 * @param $message
3257 *
3258 * @throws Exception
a9ac877b 3259 */
00be9182 3260 public function CiviUnitTestCase_fatalErrorHandler($message) {
a9ac877b
EM
3261 throw new Exception("{$message['message']}: {$message['code']}");
3262 }
4aef704e 3263
3264 /**
eceb18cc 3265 * Helper function to create new mailing.
cdc5c450 3266 *
3267 * @param array $params
3268 *
3269 * @return int
4aef704e 3270 */
d15a97f4 3271 public function createMailing($params = array()) {
cdc5c450 3272 $params = array_merge(array(
4aef704e 3273 'subject' => 'maild' . rand(),
21b09c13 3274 'body_text' => 'bdkfhdskfhduew{domain.address}{action.optOutUrl}',
4aef704e 3275 'name' => 'mailing name' . rand(),
3276 'created_id' => 1,
cdc5c450 3277 ), $params);
4aef704e 3278
3279 $result = $this->callAPISuccess('Mailing', 'create', $params);
3280 return $result['id'];
3281 }
3282
3283 /**
eceb18cc 3284 * Helper function to delete mailing.
4aef704e 3285 * @param $id
3286 */
00be9182 3287 public function deleteMailing($id) {
4aef704e 3288 $params = array(
3289 'id' => $id,
3290 );
3291
3292 $this->callAPISuccess('Mailing', 'delete', $params);
3293 }
d67f1f28
TO
3294
3295 /**
eceb18cc 3296 * Wrap the entire test case in a transaction.
d67f1f28
TO
3297 *
3298 * Only subsequent DB statements will be wrapped in TX -- this cannot
3299 * retroactively wrap old DB statements. Therefore, it makes sense to
3300 * call this at the beginning of setUp().
3301 *
3302 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3303 * this option does not work with, e.g., custom-data.
3304 *
3305 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3306 * if TRUNCATE or ALTER is called while using a transaction.
3307 *
e16033b4
TO
3308 * @param bool $nest
3309 * Whether to use nesting or reference-counting.
d67f1f28 3310 */
00be9182 3311 public function useTransaction($nest = TRUE) {
d67f1f28
TO
3312 if (!$this->tx) {
3313 $this->tx = new CRM_Core_Transaction($nest);
3314 $this->tx->rollback();
3315 }
3316 }
a335f6b2 3317
b3c30fda 3318 /**
54957108 3319 * Assert the attachment exists.
3320 *
3321 * @param bool $exists
b3c30fda
CW
3322 * @param array $apiResult
3323 */
3324 protected function assertAttachmentExistence($exists, $apiResult) {
3325 $fileId = $apiResult['id'];
3326 $this->assertTrue(is_numeric($fileId));
3327 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
3328 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
3329 1 => array($fileId, 'Int'),
3330 ));
3331 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
3332 1 => array($fileId, 'Int'),
3333 ));
3334 }
3335
c039f658 3336 /**
3337 * Create a price set for an event.
3338 *
3339 * @param int $feeTotal
601c7a24 3340 * @param int $minAmt
f660d2ad 3341 * @param string $type
c039f658 3342 *
3343 * @return int
3344 * Price Set ID.
3345 */
f660d2ad 3346 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
c039f658 3347 // creating price set, price field
3348 $paramsSet['title'] = 'Price Set';
3349 $paramsSet['name'] = CRM_Utils_String::titleToVar('Price Set');
3350 $paramsSet['is_active'] = FALSE;
3351 $paramsSet['extends'] = 1;
601c7a24 3352 $paramsSet['min_amount'] = $minAmt;
c039f658 3353
f660d2ad 3354 $priceSet = CRM_Price_BAO_PriceSet::create($paramsSet);
3355 $this->_ids['price_set'] = $priceSet->id;
c039f658 3356
c039f658 3357 $paramsField = array(
3358 'label' => 'Price Field',
3359 'name' => CRM_Utils_String::titleToVar('Price Field'),
f660d2ad 3360 'html_type' => $type,
c039f658 3361 'price' => $feeTotal,
3362 'option_label' => array('1' => 'Price Field'),
3363 'option_value' => array('1' => $feeTotal),
3364 'option_name' => array('1' => $feeTotal),
3365 'option_weight' => array('1' => 1),
3366 'option_amount' => array('1' => 1),
3367 'is_display_amounts' => 1,
3368 'weight' => 1,
3369 'options_per_line' => 1,
3370 'is_active' => array('1' => 1),
f660d2ad 3371 'price_set_id' => $this->_ids['price_set'],
c039f658 3372 'is_enter_qty' => 1,
8484a5f0 3373 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
c039f658 3374 );
f660d2ad 3375 if ($type === 'Radio') {
3376 $paramsField['is_enter_qty'] = 0;
3377 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
3378 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
3379 }
c039f658 3380 CRM_Price_BAO_PriceField::create($paramsField);
f660d2ad 3381 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids['price_set']));
3382 $this->_ids['price_field'] = array_keys($fields['values']);
3383 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids['price_field'][0]));
3384 $this->_ids['price_field_value'] = array_keys($fieldValues['values']);
c039f658 3385
f660d2ad 3386 return $this->_ids['price_set'];
c039f658 3387 }
3388
481312d9 3389 /**
3390 * Add a profile to a contribution page.
3391 *
3392 * @param string $name
3393 * @param int $contributionPageID
3394 */
3395 protected function addProfile($name, $contributionPageID) {
3396 $this->callAPISuccess('UFJoin', 'create', array(
3397 'uf_group_id' => $name,
3398 'module' => 'CiviContribute',
3399 'entity_table' => 'civicrm_contribution_page',
3400 'entity_id' => $contributionPageID,
3401 'weight' => 1,
3402 ));
3403 }
3404
db62fd2b
PN
3405 /**
3406 * Add participant with contribution
3407 *
3408 * @return array
3409 */
3410 protected function createParticipantWithContribution() {
3411 // creating price set, price field
a630a84e 3412 $this->_contactId = $this->individualCreate();
3413 $event = $this->eventCreate();
3414 $this->_eventId = $event['id'];
db62fd2b
PN
3415 $eventParams = array(
3416 'id' => $this->_eventId,
3417 'financial_type_id' => 4,
3418 'is_monetary' => 1,
3419 );
3420 $this->callAPISuccess('event', 'create', $eventParams);
73c0e107 3421 $priceFields = $this->createPriceSet('event', $this->_eventId);
db62fd2b
PN
3422 $participantParams = array(
3423 'financial_type_id' => 4,
3424 'event_id' => $this->_eventId,
3425 'role_id' => 1,
3426 'status_id' => 14,
3427 'fee_currency' => 'USD',
3428 'contact_id' => $this->_contactId,
3429 );
3430 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
3431 $contributionParams = array(
3432 'total_amount' => 150,
3433 'currency' => 'USD',
3434 'contact_id' => $this->_contactId,
3435 'financial_type_id' => 4,
3436 'contribution_status_id' => 1,
3437 'partial_payment_total' => 300.00,
f49cdeab 3438 'partial_amount_to_pay' => 150,
db62fd2b
PN
3439 'contribution_mode' => 'participant',
3440 'participant_id' => $participant['id'],
3441 );
3442 foreach ($priceFields['values'] as $key => $priceField) {
3443 $lineItems[1][$key] = array(
3444 'price_field_id' => $priceField['price_field_id'],
3445 'price_field_value_id' => $priceField['id'],
3446 'label' => $priceField['label'],
3447 'field_title' => $priceField['label'],
3448 'qty' => 1,
3449 'unit_price' => $priceField['amount'],
3450 'line_total' => $priceField['amount'],
3451 'financial_type_id' => $priceField['financial_type_id'],
3452 );
3453 }
3454 $contributionParams['line_item'] = $lineItems;
3455 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
3456 $paymentParticipant = array(
3457 'participant_id' => $participant['id'],
3458 'contribution_id' => $contribution['id'],
3459 );
db62fd2b
PN
3460 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
3461 return array($lineItems, $contribution);
3462 }
3463
73c0e107
PN
3464 /**
3465 * Create price set
3466 *
3467 * @param string $component
3468 * @param int $componentId
3469 *
3470 * @return array
3471 */
c91b1cc3 3472 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
5c3d600f
PN
3473 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
3474 $paramsSet['name'] = CRM_Utils_String::titleToVar($paramsSet['title']);
73c0e107
PN
3475 $paramsSet['is_active'] = TRUE;
3476 $paramsSet['financial_type_id'] = 4;
3477 $paramsSet['extends'] = 1;
3478 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
3479 $priceSetId = $priceSet['id'];
3480 //Checking for priceset added in the table.
3481 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
3482 'id', $paramsSet['title'], 'Check DB for created priceset'
3483 );
c91b1cc3 3484 $paramsField = array_merge(array(
73c0e107
PN
3485 'label' => 'Price Field',
3486 'name' => CRM_Utils_String::titleToVar('Price Field'),
3487 'html_type' => 'CheckBox',
3488 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3489 'option_value' => array('1' => 100, '2' => 200),
3490 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
3491 'option_weight' => array('1' => 1, '2' => 2),
3492 'option_amount' => array('1' => 100, '2' => 200),
3493 'is_display_amounts' => 1,
3494 'weight' => 1,
3495 'options_per_line' => 1,
3496 'is_active' => array('1' => 1, '2' => 1),
3497 'price_set_id' => $priceSet['id'],
3498 'is_enter_qty' => 1,
8484a5f0 3499 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
c91b1cc3
E
3500 ), $priceFieldOptions);
3501
73c0e107
PN
3502 $priceField = CRM_Price_BAO_PriceField::create($paramsField);
3503 if ($componentId) {
3504 CRM_Price_BAO_PriceSet::addTo('civicrm_' . $component, $componentId, $priceSetId);
3505 }
3506 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id));
3507 }
3508
b80f2ad1
E
3509 /**
3510 * Replace the template with a test-oriented template designed to show all the variables.
3511 *
3512 * @param string $templateName
3513 */
3514 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
3515 $testTemplate = file_get_contents(__DIR__ . '/../../templates/message_templates/' . $templateName . '_html.tpl');
3516 CRM_Core_DAO::executeQuery(
3517 "UPDATE civicrm_option_group og
3518 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3519 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3520 SET m.msg_html = '{$testTemplate}'
3521 WHERE og.name = 'msg_tpl_workflow_contribution'
3522 AND ov.name = '{$templateName}'
3523 AND m.is_default = 1"
3524 );
3525 }
3526
3527 /**
3528 * Reinstate the default template.
3529 *
3530 * @param string $templateName
3531 */
3532 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
3533 CRM_Core_DAO::executeQuery(
3534 "UPDATE civicrm_option_group og
3535 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
3536 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
3537 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
3538 SET m.msg_html = m2.msg_html
3539 WHERE og.name = 'msg_tpl_workflow_contribution'
3540 AND ov.name = '{$templateName}'
3541 AND m.is_default = 1"
3542 );
3543 }
3544
8d35246a
EM
3545 /**
3546 * Flush statics relating to financial type.
3547 */
3548 protected function flushFinancialTypeStatics() {
3549 if (isset(\Civi::$statics['CRM_Financial_BAO_FinancialType'])) {
3550 unset(\Civi::$statics['CRM_Financial_BAO_FinancialType']);
3551 }
4954339a
EM
3552 if (isset(\Civi::$statics['CRM_Contribute_PseudoConstant'])) {
3553 unset(\Civi::$statics['CRM_Contribute_PseudoConstant']);
3554 }
8d35246a 3555 CRM_Contribute_PseudoConstant::flush('financialType');
4954339a
EM
3556 CRM_Contribute_PseudoConstant::flush('membershipType');
3557 // Pseudoconstants may be saved to the cache table.
3558 CRM_Core_DAO::executeQuery("TRUNCATE civicrm_cache");
3559 CRM_Financial_BAO_FinancialType::$_statusACLFt = array();
8d35246a
EM
3560 CRM_Financial_BAO_FinancialType::$_availableFinancialTypes = NULL;
3561 }
3562
3563 /**
3564 * Set the permissions to the supplied array.
3565 *
3566 * @param array $permissions
3567 */
3568 protected function setPermissions($permissions) {
3569 CRM_Core_Config::singleton()->userPermissionClass->permissions = $permissions;
3570 $this->flushFinancialTypeStatics();
3571 }
3572
bf722049 3573 /**
3574 * @param array $params
3575 * @param $context
3576 */
3577 public function _checkFinancialRecords($params, $context) {
3578 $entityParams = array(
3579 'entity_id' => $params['id'],
3580 'entity_table' => 'civicrm_contribution',
3581 );
3582 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
3583 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
3584 if ($context == 'pending') {
3585 $trxn = CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams);
3586 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
3587 return;
3588 }
3589 $trxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
3590 $trxnParams = array(
3591 'id' => $trxn['financial_trxn_id'],
3592 );
3593 if ($context != 'online' && $context != 'payLater') {
3594 $compareParams = array(
3595 'to_financial_account_id' => 6,
3596 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3597 'status_id' => 1,
3598 );
3599 }
3600 if ($context == 'feeAmount') {
3601 $compareParams['fee_amount'] = 50;
3602 }
3603 elseif ($context == 'online') {
3604 $compareParams = array(
3605 'to_financial_account_id' => 12,
3606 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3607 'status_id' => 1,
f69a9ac3 3608 'payment_instrument_id' => CRM_Utils_Array::value('payment_instrument_id', $params, 1),
bf722049 3609 );
3610 }
3611 elseif ($context == 'payLater') {
3612 $compareParams = array(
3613 'to_financial_account_id' => 7,
3614 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3615 'status_id' => 2,
3616 );
3617 }
3618 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3619 $entityParams = array(
3620 'financial_trxn_id' => $trxn['financial_trxn_id'],
3621 'entity_table' => 'civicrm_financial_item',
3622 );
3623 $entityTrxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
3624 $fitemParams = array(
3625 'id' => $entityTrxn['entity_id'],
3626 );
3627 $compareParams = array(
3628 'amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3629 'status_id' => 1,
1a1a2f4f 3630 'financial_account_id' => CRM_Utils_Array::value('financial_account_id', $params, 1),
bf722049 3631 );
3632 if ($context == 'payLater') {
3633 $compareParams = array(
3634 'amount' => CRM_Utils_Array::value('total_amount', $params, 100),
3635 'status_id' => 3,
1a1a2f4f 3636 'financial_account_id' => CRM_Utils_Array::value('financial_account_id', $params, 1),
bf722049 3637 );
3638 }
3639 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3640 if ($context == 'feeAmount') {
3641 $maxParams = array(
3642 'entity_id' => $params['id'],
3643 'entity_table' => 'civicrm_contribution',
3644 );
3645 $maxTrxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($maxParams, TRUE));
3646 $trxnParams = array(
3647 'id' => $maxTrxn['financial_trxn_id'],
3648 );
3649 $compareParams = array(
3650 'to_financial_account_id' => 5,
3651 'from_financial_account_id' => 6,
3652 'total_amount' => 50,
3653 'status_id' => 1,
3654 );
3655 $trxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['id'], 'DESC');
3656 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
3657 $fitemParams = array(
3658 'entity_id' => $trxnId['financialTrxnId'],
3659 'entity_table' => 'civicrm_financial_trxn',
3660 );
3661 $compareParams = array(
3662 'amount' => 50,
3663 'status_id' => 1,
3664 'financial_account_id' => 5,
3665 );
3666 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
3667 }
3668 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
3669 // line should be copied into all the functions that call this function & evaluated there
3670 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
3671 // when calling completeTransaction or repeatTransaction.
3672 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
3673 }
3674
8484a5f0 3675 /**
3676 * Return financial type id on basis of name
3677 *
3678 * @param string $name Financial type m/c name
3679 *
3680 * @return int
3681 */
3682 public function getFinancialTypeId($name) {
3683 return CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
3684 }
3685
204beda3 3686 /**
3687 * Cleanup function for contents of $this->ids.
3688 *
3689 * This is a best effort cleanup to use in tear downs etc.
3690 *
3691 * It will not fail if the data has already been removed (some tests may do
3692 * their own cleanup).
3693 */
3694 protected function cleanUpSetUpIDs() {
3695 foreach ($this->setupIDs as $entity => $id) {
3696 try {
3697 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
3698 }
3699 catch (CiviCRM_API3_Exception $e) {
3700 // This is a best-effort cleanup function, ignore.
3701 }
3702 }
3703 }
3704
adbc354b
PN
3705 /**
3706 * Create Financial Type.
3707 *
3708 * @param array $params
3709 *
3710 * @return array
3711 */
3712 protected function createFinancialType($params = array()) {
3713 $params = array_merge($params,
3714 array(
3715 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
3716 'is_active' => 1,
3717 )
3718 );
3719 return $this->callAPISuccess('FinancialType', 'create', $params);
3720 }
3721
ec5da26a 3722 /**
3723 * Enable Tax and Invoicing
3724 */
3725 protected function enableTaxAndInvoicing($params = array()) {
3726 // Enable component contribute setting
3727 $contributeSetting = array_merge($params,
3728 array(
3729 'invoicing' => 1,
3730 'invoice_prefix' => 'INV_',
3731 'credit_notes_prefix' => 'CN_',
3732 'due_date' => 10,
3733 'due_date_period' => 'days',
3734 'notes' => '',
3735 'is_email_pdf' => 1,
3736 'tax_term' => 'Sales Tax',
3737 'tax_display_settings' => 'Inclusive',
3738 )
3739 );
3740 return Civi::settings()->set('contribution_invoice_settings', $contributeSetting);
3741 }
3742
9fbf312f 3743 /**
3744 * Enable Tax and Invoicing
3745 */
3746 protected function disableTaxAndInvoicing($params = array()) {
f436577a 3747 if (!empty(\Civi::$statics['CRM_Core_PseudoConstant']) && isset(\Civi::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
3748 unset(\Civi::$statics['CRM_Core_PseudoConstant']['taxRates']);
3749 }
9fbf312f 3750 // Enable component contribute setting
3751 $contributeSetting = array_merge($params,
3752 array(
3753 'invoicing' => 0,
3754 )
3755 );
3756 return Civi::settings()->set('contribution_invoice_settings', $contributeSetting);
3757 }
3758
7a1f3919
PN
3759 /**
3760 * Add Sales Tax relation for financial type with financial account.
3761 *
3762 * @param int $financialTypeId
3763 *
3764 * @return obj
3765 */
3766 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
3767 $params = array(
3768 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
3769 'financial_account_type_id' => key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
3770 'is_deductible' => 1,
3771 'is_tax' => 1,
3772 'tax_rate' => 10,
3773 'is_active' => 1,
3774 );
3775 $account = CRM_Financial_BAO_FinancialAccount::add($params);
3776 $entityParams = array(
3777 'entity_table' => 'civicrm_financial_type',
7a1f3919 3778 'entity_id' => $financialTypeId,
5b3543ce 3779 'account_relationship' => key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
7a1f3919 3780 );
5b3543ce 3781
f436577a 3782 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
3783 \Civi::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
3784
5b3543ce
JM
3785 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
3786 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
3787 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
3788 $dao->copyValues($entityParams);
3789 $dao->find();
3790 if ($dao->fetch()) {
3791 $entityParams['id'] = $dao->id;
3792 }
3793 $entityParams['financial_account_id'] = $account->id;
3794
7a1f3919
PN
3795 return CRM_Financial_BAO_FinancialTypeAccount::add($entityParams);
3796 }
3797
65e172a3 3798 /**
3799 * Create price set with contribution test for test setup.
3800 *
3801 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
3802 * on parent class at some point (fn is not in 4.4).
3803 *
3804 * @param $entity
3805 * @param array $params
3806 */
3807 public function createPriceSetWithPage($entity = NULL, $params = array()) {
3808 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
3809 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
3810 'title' => "Test Contribution Page",
3811 'financial_type_id' => 1,
3812 'currency' => 'NZD',
3813 'goal_amount' => 50,
3814 'is_pay_later' => 1,
3815 'is_monetary' => TRUE,
3816 'is_email_receipt' => FALSE,
3817 ));
3818 $priceSet = $this->callAPISuccess('price_set', 'create', array(
3819 'is_quick_config' => 0,
3820 'extends' => 'CiviMember',
3821 'financial_type_id' => 1,
3822 'title' => 'my Page',
3823 ));
3824 $priceSetID = $priceSet['id'];
3825
3826 CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
3827 $priceField = $this->callAPISuccess('price_field', 'create', array(
3828 'price_set_id' => $priceSetID,
3829 'label' => 'Goat Breed',
3830 'html_type' => 'Radio',
3831 ));
3832 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3833 'price_set_id' => $priceSetID,
3834 'price_field_id' => $priceField['id'],
3835 'label' => 'Long Haired Goat',
3836 'amount' => 20,
3837 'financial_type_id' => 'Donation',
3838 'membership_type_id' => $membershipTypeID,
3839 'membership_num_terms' => 1,
3840 )
3841 );
3842 $this->_ids['price_field_value'] = array($priceFieldValue['id']);
3843 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3844 'price_set_id' => $priceSetID,
3845 'price_field_id' => $priceField['id'],
3846 'label' => 'Shoe-eating Goat',
3847 'amount' => 10,
3848 'financial_type_id' => 'Donation',
3849 'membership_type_id' => $membershipTypeID,
3850 'membership_num_terms' => 2,
3851 )
3852 );
3853 $this->_ids['price_field_value'][] = $priceFieldValue['id'];
3854
3855 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3856 'price_set_id' => $priceSetID,
3857 'price_field_id' => $priceField['id'],
3858 'label' => 'Shoe-eating Goat',
3859 'amount' => 10,
3860 'financial_type_id' => 'Donation',
3861 )
3862 );
3863 $this->_ids['price_field_value']['cont'] = $priceFieldValue['id'];
3864
3865 $this->_ids['price_set'] = $priceSetID;
3866 $this->_ids['contribution_page'] = $contributionPageResult['id'];
3867 $this->_ids['price_field'] = array($priceField['id']);
3868
3869 $this->_ids['membership_type'] = $membershipTypeID;
3870 }
3871
33072bc7 3872 /**
3873 * No results returned.
3874 *
3875 * @implements CRM_Utils_Hook::aclWhereClause
3876 *
3877 * @param string $type
3878 * @param array $tables
3879 * @param array $whereTables
3880 * @param int $contactID
3881 * @param string $where
3882 */
3883 public function aclWhereHookNoResults($type, &$tables, &$whereTables, &$contactID, &$where) {
3884 }
3885
3c9d67b0 3886 /**
3887 * Only specified contact returned.
3888 * @implements CRM_Utils_Hook::aclWhereClause
3889 * @param $type
3890 * @param $tables
3891 * @param $whereTables
3892 * @param $contactID
3893 * @param $where
3894 */
3895 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3896 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts) . ")";
3897 }
3898
88ebed7c
JP
3899 /**
3900 * @implements CRM_Utils_Hook::selectWhereClause
3901 *
3902 * @param string $entity
3903 * @param array $clauses
3904 */
3905 public function selectWhereClauseHook($entity, &$clauses) {
3906 if ($entity == 'Event') {
3907 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3908 }
3909 }
3910
29a59599
JP
3911 /**
3912 * An implementation of hook_civicrm_post used with all our test cases.
3913 *
3914 * @param $op
3915 * @param string $objectName
3916 * @param int $objectId
3917 * @param $objectRef
3918 */
3919 public function onPost($op, $objectName, $objectId, &$objectRef) {
3920 if ($op == 'create' && $objectName == 'Individual') {
3921 CRM_Core_DAO::executeQuery(
3922 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3923 array(
3924 1 => array($objectId, 'Integer'),
3925 )
3926 );
3927 }
3928
3929 if ($op == 'edit' && $objectName == 'Participant') {
3930 $params = array(
3931 1 => array($objectId, 'Integer'),
3932 );
3933 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3934 CRM_Core_DAO::executeQuery($query, $params);
3935 }
3936 }
3937
f8df7165 3938
3939 /**
3940 * Instantiate form object.
3941 *
3942 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3943 *
3944 * @param string $class
3945 * Name of form class.
3946 *
3947 * @return \CRM_Core_Form
3948 */
3949 public function getFormObject($class) {
3950 $form = new $class();
3951 $_SERVER['REQUEST_METHOD'] = 'GET';
3952 $form->controller = new CRM_Core_Controller();
3953 return $form;
3954 }
3955
83644f47 3956 /**
3957 * Get possible thousand separators.
3958 *
3959 * @return array
3960 */
3961 public function getThousandSeparators() {
3962 return array(array('.'), array(','));
3963 }
3964
3965 /**
3966 * Set the separators for thousands and decimal points.
3967 *
3968 * @param string $thousandSeparator
3969 */
3970 protected function setCurrencySeparators($thousandSeparator) {
3971 Civi::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3972 Civi::settings()
3973 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ? '.' : ','));
3974 }
3975
3976 /**
3977 * Format money as it would be input.
3978 *
3979 * @param string $amount
3980 *
3981 * @return string
3982 */
3983 protected function formatMoneyInput($amount) {
3984 return CRM_Utils_Money::format($amount, NULL, '%a');
3985 }
3986
3ca4bd1b 3987
3988 /**
3989 * Get the contribution object.
3990 *
3991 * @param int $contributionID
3992 *
3993 * @return \CRM_Contribute_BAO_Contribution
3994 */
3995 protected function getContributionObject($contributionID) {
3996 $contributionObj = new CRM_Contribute_BAO_Contribution();
3997 $contributionObj->id = $contributionID;
3998 $contributionObj->find(TRUE);
3999 return $contributionObj;
4000 }
4001
a86d27fc 4002}