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