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