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