Fix OptionGroup::values cache CRM-12464
[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
29/**
30 * Include configuration
31 */
32define('CIVICRM_SETTINGS_PATH', __DIR__ . '/civicrm.settings.dist.php');
33define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__ . '/civicrm.settings.local.php');
34
35if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH)) {
36 require_once CIVICRM_SETTINGS_LOCAL_PATH;
37}
38require_once CIVICRM_SETTINGS_PATH;
39/**
40 * Include class definitions
41 */
42require_once 'PHPUnit/Extensions/Database/TestCase.php';
43require_once 'PHPUnit/Framework/TestResult.php';
44require_once 'PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php';
45require_once 'PHPUnit/Extensions/Database/DataSet/XmlDataSet.php';
46require_once 'PHPUnit/Extensions/Database/DataSet/QueryDataSet.php';
47require_once 'tests/phpunit/Utils.php';
48require_once 'api/api.php';
49require_once 'CRM/Financial/BAO/FinancialType.php';
50define('API_LATEST_VERSION', 3);
51
52/**
53 * Base class for CiviCRM unit tests
54 *
55 * Common functions for unit tests
56 * @package CiviCRM
57 */
58class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
59
60 /**
61 * Database has been initialized
62 *
63 * @var boolean
64 */
65 private static $dbInit = FALSE;
66
67 /**
68 * Database connection
69 *
70 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
71 */
72 protected $_dbconn;
73
74 /**
75 * The database name
76 *
77 * @var string
78 */
79 static protected $_dbName;
80
81 /**
82 * @var array of temporary directory names
83 */
84 protected $tempDirs;
85
86 /**
87 * @var Utils instance
88 */
89 public static $utils;
90
91 /**
92 * @var boolean populateOnce allows to skip db resets in setUp
93 *
94 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
95 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
96 * "CHECK RUNS" ONLY!
97 *
98 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
99 *
100 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
101 */
102 public static $populateOnce = FALSE;
103
104 /**
105 * Allow classes to state E-notice compliance
106 */
107 public $_eNoticeCompliant = FALSE;
108
109 /**
110 * @var boolean DBResetRequired allows skipping DB reset
111 * in specific test case. If you still need
112 * to reset single test (method) of such case, call
113 * $this->cleanDB() in the first line of this
114 * test (method).
115 */
116 public $DBResetRequired = TRUE;
117
118 /**
119 * Constructor
120 *
121 * Because we are overriding the parent class constructor, we
122 * need to show the same arguments as exist in the constructor of
123 * PHPUnit_Framework_TestCase, since
124 * PHPUnit_Framework_TestSuite::createTest() creates a
125 * ReflectionClass of the Test class and checks the constructor
126 * of that class to decide how to set up the test.
127 *
128 * @param string $name
129 * @param array $data
130 * @param string $dataName
131 */
132 function __construct($name = NULL, array$data = array(), $dataName = '') {
133 parent::__construct($name, $data, $dataName);
134
135 // we need full error reporting
136 error_reporting(E_ALL & ~E_NOTICE);
137
138 if (!empty($GLOBALS['mysql_db'])) {
139 self::$_dbName = $GLOBALS['mysql_db'];
140 }
141 else {
142 self::$_dbName = 'civicrm_tests_dev';
143 }
144
145 // create test database
146 self::$utils = new Utils($GLOBALS['mysql_host'],
147 $GLOBALS['mysql_user'],
148 $GLOBALS['mysql_pass']
149 );
150
151 // also load the class loader
152 require_once 'CRM/Core/ClassLoader.php';
153 CRM_Core_ClassLoader::singleton()->register();
154 if (function_exists('_civix_phpunit_setUp')) { // FIXME: loosen coupling
155 _civix_phpunit_setUp();
156 }
157 }
158
159 function requireDBReset() {
160 return $this->DBResetRequired;
161 }
162
163 static function getDBName() {
164 $dbName = !empty($GLOBALS['mysql_db']) ? $GLOBALS['mysql_db'] : 'civicrm_tests_dev';
165 return $dbName;
166 }
167
168 /**
169 * Create database connection for this instance
170 *
171 * Initialize the test database if it hasn't been initialized
172 *
173 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
174 */
175 protected function getConnection() {
176 $dbName = self::$_dbName;
177 if (!self::$dbInit) {
178 $dbName = self::getDBName();
179
180 // install test database
181 echo PHP_EOL . "Installing {$dbName} database" . PHP_EOL;
182
183 self::_populateDB(FALSE, $this);
184
185 self::$dbInit = TRUE;
186 }
187 return $this->createDefaultDBConnection(self::$utils->pdo, $dbName);
188 }
189
190 /**
191 * Required implementation of abstract method
192 */
193 protected function getDataSet() {
194 }
195
196 private static function _populateDB($perClass = FALSE, &$object = NULL) {
197
198 if ($perClass || $object == NULL) {
199 $dbreset = TRUE;
200 }
201 else {
202 $dbreset = $object->requireDBReset();
203 }
204
205 if (self::$populateOnce || !$dbreset) {
206 return;
207 }
208 self::$populateOnce = NULL;
209
210 $dbName = self::getDBName();
211 $pdo = self::$utils->pdo;
212 // only consider real tables and not views
213 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
214 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
215
216 $truncates = array();
217 $drops = array();
218 foreach ($tables as $table) {
219 // skip log tables
220 if (substr($table['table_name'], 0, 4) == 'log_') {
221 continue;
222 }
223
224 // don't change list of installed extensions
225 if ($table['table_name'] == 'civicrm_extension') {
226 continue;
227 }
228
229 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
230 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
231 }
232 else {
233 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
234 }
235 }
236
237 $queries = array(
238 "USE {$dbName};",
239 "SET foreign_key_checks = 0",
240 // SQL mode needs to be strict, that's our standard
241 "SET SQL_MODE='STRICT_ALL_TABLES';",
242 "SET global innodb_flush_log_at_trx_commit = 2;",
243 );
244 $queries = array_merge($queries, $truncates);
245 $queries = array_merge($queries, $drops);
246 foreach ($queries as $query) {
247 if (self::$utils->do_query($query) === FALSE) {
248 // failed to create test database
249 echo "failed to create test db.";
250 exit;
251 }
252 }
253
254 // initialize test database
255 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/civicrm_data.mysql";
256 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/test_data.mysql";
257 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/test_data_second_domain.mysql";
258
259 $query2 = file_get_contents($sql_file2);
260 $query3 = file_get_contents($sql_file3);
261 $query4 = file_get_contents($sql_file4);
262 if (self::$utils->do_query($query2) === FALSE) {
263 echo "Cannot load civicrm_data.mysql. Aborting.";
264 exit;
265 }
266 if (self::$utils->do_query($query3) === FALSE) {
267 echo "Cannot load test_data.mysql. Aborting.";
268 exit;
269 }
270 if (self::$utils->do_query($query4) === FALSE) {
271 echo "Cannot load test_data.mysql. Aborting.";
272 exit;
273 }
274
275 // done with all the loading, get transactions back
276 if (self::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
277 echo "Cannot set global? Huh?";
278 exit;
279 }
280
281 if (self::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
282 echo "Cannot get foreign keys back? Huh?";
283 exit;
284 }
285
286 unset($query, $query2, $query3);
287
288 // Rebuild triggers
289 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
290 }
291
292 public static function setUpBeforeClass() {
293 self::_populateDB(TRUE);
294
295 // also set this global hack
296 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
297 }
298
299 /**
300 * Common setup functions for all unit tests
301 */
302 protected function setUp() {
303 CRM_Utils_Hook::singleton(TRUE);
304 $this->errorScope = CRM_Core_TemporaryErrorScope::useException(); // REVERT
305 // Use a temporary file for STDIN
306 $GLOBALS['stdin'] = tmpfile();
307 if ($GLOBALS['stdin'] === FALSE) {
308 echo "Couldn't open temporary file\n";
309 exit(1);
310 }
311
312 // Get and save a connection to the database
313 $this->_dbconn = $this->getConnection();
314
315 // reload database before each test
316 // $this->_populateDB();
317
318 // "initialize" CiviCRM to avoid problems when running single tests
319 // FIXME: look at it closer in second stage
320
321 // initialize the object once db is loaded
322 require_once 'CRM/Core/Config.php';
323 $config = CRM_Core_Config::singleton();
324
325 // when running unit tests, use mockup user framework
326 $config->setUserFramework('UnitTests');
327
328 // also fix the fatal error handler to throw exceptions,
329 // rather than exit
330 $config->fatalErrorHandler = 'CiviUnitTestCase_fatalErrorHandler';
331
332 // enable backtrace to get meaningful errors
333 $config->backtrace = 1;
334
335 // disable any left-over test extensions
336 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
337
338 // reset all the caches
339 CRM_Utils_System::flushCache();
340
341 // clear permissions stub to not check permissions
342 $config = CRM_Core_Config::singleton();
343 $config->userPermissionClass->permissions = NULL;
344
345 //flush component settings
346 CRM_Core_Component::getEnabledComponents(TRUE);
347
348 if ($this->_eNoticeCompliant) {
349 error_reporting(E_ALL);
350 }
351 else {
352 error_reporting(E_ALL & ~E_NOTICE);
353 }
354 }
355
356 /**
357 * emulate a logged in user since certain functions use that
358 * value to store a record in the DB (like activity)
359 * CRM-8180
360 */
361 public function createLoggedInUser() {
362 $params = array(
363 'first_name' => 'Logged In',
364 'last_name' => 'User ' . rand(),
365 'contact_type' => 'Individual',
366 );
367 $contactID = $this->individualCreate($params);
368
369 $session = CRM_Core_Session::singleton();
370 $session->set('userID', $contactID);
371 }
372
373 public function cleanDB() {
374 self::$populateOnce = NULL;
375 $this->DBResetRequired = TRUE;
376
377 $this->_dbconn = $this->getConnection();
378 $this->_populateDB();
379 $this->tempDirs = array();
380 }
381
382 /**
383 * Common teardown functions for all unit tests
384 */
385 protected function tearDown() {
386 error_reporting(E_ALL & ~E_NOTICE);
387 $tablesToTruncate = array('civicrm_contact');
388 $this->quickCleanup($tablesToTruncate);
389 $this->cleanTempDirs();
390 $this->unsetExtensionSystem();
391 }
392
393 /**
394 * FIXME: Maybe a better way to do it
395 */
396 function foreignKeyChecksOff() {
397 self::$utils = new Utils($GLOBALS['mysql_host'],
398 $GLOBALS['mysql_user'],
399 $GLOBALS['mysql_pass']
400 );
401 $dbName = self::getDBName();
402 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
403 if (self::$utils->do_query($query) === FALSE) {
404 // fail happens
405 echo 'Cannot set foreign_key_checks = 0';
406 exit(1);
407 }
408 return TRUE;
409 }
410
411 function foreignKeyChecksOn() {
412 // FIXME: might not be needed if previous fixme implemented
413 }
414
415 /**
416 * Generic function to compare expected values after an api call to retrieved
417 * DB values.
418 *
419 * @daoName string DAO Name of object we're evaluating.
420 * @id int Id of object
421 * @match array Associative array of field name => expected value. Empty if asserting
422 * that a DELETE occurred
423 * @delete boolean True if we're checking that a DELETE action occurred.
424 */
425 function assertDBState($daoName, $id, $match, $delete = FALSE) {
426 if (empty($id)) {
427 // adding this here since developers forget to check for an id
428 // and hence we get the first value in the db
429 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
430 }
431
4d5c2eb5 432 $object = new $daoName();
6a488035
TO
433 $object->id = $id;
434 $verifiedCount = 0;
435
436 // If we're asserting successful record deletion, make sure object is NOT found.
437 if ($delete) {
438 if ($object->find(TRUE)) {
439 $this->fail("Object not deleted by delete operation: $daoName, $id");
440 }
441 return;
442 }
443
444 // Otherwise check matches of DAO field values against expected values in $match.
445 if ($object->find(TRUE)) {
446 $fields = & $object->fields();
447 foreach ($fields as $name => $value) {
448 $dbName = $value['name'];
449 if (isset($match[$name])) {
450 $verifiedCount++;
451 $this->assertEquals($object->$dbName, $match[$name]);
452 }
453 elseif (isset($match[$dbName])) {
454 $verifiedCount++;
455 $this->assertEquals($object->$dbName, $match[$dbName]);
456 }
457 }
458 }
459 else {
460 $this->fail("Could not retrieve object: $daoName, $id");
461 }
462 $object->free();
463 $matchSize = count($match);
464 if ($verifiedCount != $matchSize) {
465 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
466 }
467 }
468
469 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
470 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
471 if (empty($searchValue)) {
472 $this->fail("empty value passed to assertDBNotNull");
473 }
474 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
475 $this->assertNotNull($value, $message);
476
477 return $value;
478 }
479
480 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
481 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
482 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
483 $this->assertNull($value, $message);
484 }
485
486 // Request a record from the DB by id. Success if row not found.
487 function assertDBRowNotExist($daoName, $id, $message = NULL) {
488 $message = $message ? $message : "$daoName (#$id) should not exist";
489 $value = CRM_Core_DAO::getFieldValue($daoName, $id, 'id', 'id', TRUE);
490 $this->assertNull($value, $message);
491 }
492
493 // Request a record from the DB by id. Success if row not found.
494 function assertDBRowExist($daoName, $id, $message = NULL) {
495 $message = $message ? $message : "$daoName (#$id) should exist";
496 $value = CRM_Core_DAO::getFieldValue($daoName, $id, 'id', 'id', TRUE);
497 $this->assertEquals($id, $value, $message);
498 }
499
500 // Compare a single column value in a retrieved DB record to an expected value
501 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
502 $expectedValue, $message
503 ) {
504 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
505 $this->assertEquals($value, $expectedValue, $message);
506 }
507
508 // Compare all values in a single retrieved DB record to an array of expected values
509 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
510 //get the values from db
511 $dbValues = array();
512 CRM_Core_DAO::commonRetrieve($daoName, $searchParams, $dbValues);
513
514 // compare db values with expected values
515 self::assertAttributesEquals($expectedValues, $dbValues);
516 }
517
518 /**
519 * Assert that a SQL query returns a given value
520 *
521 * The first argument is an expected value. The remaining arguments are passed
522 * to CRM_Core_DAO::singleValueQuery
523 *
524 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
525 * array(1 => array("Whiz", "String")));
526 */
527 function assertDBQuery($expected, $query, $params = array()) {
528 $actual = CRM_Core_DAO::singleValueQuery($query, $params);
529 $this->assertEquals($expected, $actual,
530 sprintf('expected=[%s] actual=[%s] query=[%s]',
531 $expected, $actual, CRM_Core_DAO::composeQuery($query, $params, FALSE)
532 )
533 );
534 }
535
536 /**
537 * Assert that two array-trees are exactly equal, notwithstanding
538 * the sorting of keys
539 *
540 * @param array $expected
541 * @param array $actual
542 */
543 function assertTreeEquals($expected, $actual) {
544 $e = array();
545 $a = array();
546 CRM_Utils_Array::flatten($expected, $e, '', ':::');
547 CRM_Utils_Array::flatten($actual, $a, '', ':::');
548 ksort($e);
549 ksort($a);
550
551 $this->assertEquals($e, $a);
552 }
553
dc92f2f8
TO
554 /**
555 * Assert that two numbers are approximately equal
556 *
557 * @param int|float $expected
558 * @param int|float $actual
559 * @param int|float $tolerance
560 * @param string $message
561 */
562 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
563 if ($message === NULL) {
564 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
565 }
566 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
567 }
568
6a488035
TO
569 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
570 foreach ($expectedValues as $paramName => $paramValue) {
571 if (isset($actualValues[$paramName])) {
572 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is $paramValue value 2 is {$actualValues[$paramName]}");
573 }
574 else {
575 $this->fail("Attribute '$paramName' not present in actual array.");
576 }
577 }
578 }
579
580 function assertArrayKeyExists($key, &$list) {
581 $result = isset($list[$key]) ? TRUE : FALSE;
582 $this->assertTrue($result, ts("%1 element exists?",
583 array(1 => $key)
584 ));
585 }
586
587 function assertArrayValueNotNull($key, &$list) {
588 $this->assertArrayKeyExists($key, $list);
589
590 $value = isset($list[$key]) ? $list[$key] : NULL;
591 $this->assertTrue($value,
592 ts("%1 element not null?",
593 array(1 => $key)
594 )
595 );
596 }
597
598 function assertAPISuccess($apiResult, $prefix = '') {
599 if (!empty($prefix)) {
600 $prefix .= ': ';
601 }
602 $this->assertEquals(0, $apiResult['is_error'], $prefix . (empty($apiResult['error_message']) ? '' : $apiResult['error_message']));
603 }
604
605 function assertType($expected, $actual, $message = '') {
606 return $this->assertInternalType($expected, $actual, $message);
607 }
608
609 /**
610 * Generic function to create Organisation, to be used in test cases
611 *
612 * @param array parameters for civicrm_contact_add api function call
613 *
614 * @return int id of Organisation created
615 */
616 function organizationCreate($params = array()) {
617 if (!$params) {
618 $params = array();
619 }
620 $orgParams = array(
621 'organization_name' => 'Unit Test Organization',
622 'contact_type' => 'Organization',
623 'version' => API_LATEST_VERSION,
624 );
625 return $this->_contactCreate(array_merge($orgParams, $params));
626 }
627
628 /**
629 * Generic function to create Individual, to be used in test cases
630 *
631 * @param array parameters for civicrm_contact_add api function call
632 *
633 * @return int id of Individual created
634 */
635 function individualCreate($params = NULL) {
636 if ($params === NULL) {
637 $params = array(
638 'first_name' => 'Anthony',
639 'middle_name' => 'J.',
640 'last_name' => 'Anderson',
641 'prefix_id' => 3,
642 'suffix_id' => 3,
643 'email' => 'anthony_anderson@civicrm.org',
644 'contact_type' => 'Individual',
645 );
646 }
647 $params['version'] = API_LATEST_VERSION;
648 return $this->_contactCreate($params);
649 }
650
651 /**
652 * Generic function to create Household, to be used in test cases
653 *
654 * @param array parameters for civicrm_contact_add api function call
655 *
656 * @return int id of Household created
657 */
658 function householdCreate($params = NULL) {
659 if ($params === NULL) {
660 $params = array(
661 'household_name' => 'Unit Test household',
662 'contact_type' => 'Household',
663 );
664 }
665 $params['version'] = API_LATEST_VERSION;
666 return $this->_contactCreate($params);
667 }
668
669 /**
670 * Private helper function for calling civicrm_contact_add
671 *
672 * @param array parameters for civicrm_contact_add api function call
673 *
674 * @return int id of Household created
675 */
676 private function _contactCreate($params) {
677 $params['version'] = API_LATEST_VERSION;
678 $result = civicrm_api('Contact', 'create', $params);
679 if (CRM_Utils_Array::value('is_error', $result) ||
680 !CRM_Utils_Array::value('id', $result)
681 ) {
682 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array::value('error_message', $result));
683 }
684 return $result['id'];
685 }
686
687 function contactDelete($contactID) {
688 $params['id'] = $contactID;
689 $params['version'] = API_LATEST_VERSION;
690 $params['skip_undelete'] = 1;
691 $domain = new CRM_Core_BAO_Domain;
692 $domain->contact_id = $contactID;
693 if ($domain->find(TRUE)) {
694 // we are finding tests trying to delete the domain contact in cleanup
695 //since this is mainly for cleanup lets put a safeguard here
696 return;
697 }
698 $result = civicrm_api('Contact', 'delete', $params);
699 if (CRM_Utils_Array::value('is_error', $result)) {
700 throw new Exception('Could not delete contact, with message: ' . CRM_Utils_Array::value('error_message', $result));
701 }
702 return;
703 }
704
705 function contactTypeDelete($contactTypeId) {
706 require_once 'CRM/Contact/BAO/ContactType.php';
707 $result = CRM_Contact_BAO_ContactType::del($contactTypeId);
708 if (!$result) {
709 throw new Exception('Could not delete contact type');
710 }
711 }
712
713 function membershipTypeCreate($contactID, $contributionTypeID = 1, $version = 3) {
714 require_once 'CRM/Member/PseudoConstant.php';
715 CRM_Member_PseudoConstant::flush('membershipType');
716 CRM_Core_Config::clearDBCache();
717 $params = array(
718 'name' => 'General',
719 'duration_unit' => 'year',
720 'duration_interval' => 1,
721 'period_type' => 'rolling',
722 'member_of_contact_id' => $contactID,
723 'domain_id' => 1,
724 // FIXME: I know it's 1, cause it was loaded directly to the db.
725 // FIXME: when we load all the data, we'll need to address this to
726 // FIXME: avoid hunting numbers around.
727 'financial_type_id' => $contributionTypeID,
728 'is_active' => 1,
729 'version' => $version,
730 'sequential' => 1,
731 'visibility' => 1,
732 );
733
734 $result = civicrm_api('MembershipType', 'Create', $params);
735 require_once 'CRM/Member/PseudoConstant.php';
736 CRM_Member_PseudoConstant::flush('membershipType');
737 CRM_Utils_Cache::singleton()->flush();
738 if (CRM_Utils_Array::value('is_error', $result) ||
739 (!CRM_Utils_Array::value('id', $result) && !CRM_Utils_Array::value('id', $result['values'][0]))
740 ) {
741 throw new Exception('Could not create membership type, with message: ' . CRM_Utils_Array::value('error_message', $result));
742 }
743
744 return $result['id'];
745 }
746
747 function contactMembershipCreate($params) {
748 $pre = array(
749 'join_date' => '2007-01-21',
750 'start_date' => '2007-01-21',
751 'end_date' => '2007-12-21',
752 'source' => 'Payment',
753 'version' => API_LATEST_VERSION,
754 );
755
756 foreach ($pre as $key => $val) {
757 if (!isset($params[$key])) {
758 $params[$key] = $val;
759 }
760 }
761
762 $result = civicrm_api('Membership', 'create', $params);
763
764 if (CRM_Utils_Array::value('is_error', $result) ||
765 !CRM_Utils_Array::value('id', $result)
766 ) {
767 if (CRM_Utils_Array::value('error_message', $result)) {
768 throw new Exception('Could not create membership, with message: ' . CRM_Utils_Array::value('error_message', $result));
769 }
770 else {
771 throw new Exception('Could not create membership' . ' - in line: ' . __LINE__);
772 }
773 }
774
775 return $result['id'];
776 }
777
778 /**
779 * Function to delete Membership Type
780 *
781 * @param int $membershipTypeID
782 */
783 function membershipTypeDelete($params) {
784 $params['version'] = API_LATEST_VERSION;
785
786 $result = civicrm_api('MembershipType', 'Delete', $params);
787 if (CRM_Utils_Array::value('is_error', $result)) {
788 throw new Exception('Could not delete membership type' . $result['error_message']);
789 }
790 return;
791 }
792
793 function membershipDelete($membershipID) {
794 $deleteParams = array('version' => 3, 'id' => $membershipID);
795 $result = civicrm_api('Membership', 'Delete', $deleteParams);
796 if (CRM_Utils_Array::value('is_error', $result)) {
797 throw new Exception('Could not delete membership ' . $result['error_message'] . " params were " . print_r($deleteParams, TRUE));
798 }
799 return;
800 }
801
802 function membershipStatusCreate($name = 'test member status') {
803 $params['name'] = $name;
804 $params['start_event'] = 'start_date';
805 $params['end_event'] = 'end_date';
806 $params['is_current_member'] = 1;
807 $params['is_active'] = 1;
808 $params['version'] = API_LATEST_VERSION;
809
810 $result = civicrm_api('MembershipStatus', 'Create', $params);
811 require_once 'CRM/Member/PseudoConstant.php';
812 CRM_Member_PseudoConstant::flush('membershipStatus');
813 if (CRM_Utils_Array::value('is_error', $result)) {
814 throw new Exception("Could not create membership status: $name, Error message: " . $result['error_message']);
815 exit();
816 }
817 return $result['id'];
818 }
819
820 function membershipStatusDelete($membershipStatusID) {
821 if (!$membershipStatusID) {
822 return;
823 }
824 $result = civicrm_api('MembershipStatus', 'Delete', array('id' => $membershipStatusID, 'version' => 3));
825 if (CRM_Utils_Array::value('is_error', $result)) {
826 throw new Exception('Could not delete membership status' . $result['error_message']);
827 }
828 return;
829 }
830
831 function relationshipTypeCreate($params = NULL) {
832 if (is_null($params)) {
833 $params = array(
834 'name_a_b' => 'Relation 1 for relationship type create',
835 'name_b_a' => 'Relation 2 for relationship type create',
836 'contact_type_a' => 'Individual',
837 'contact_type_b' => 'Organization',
838 'is_reserved' => 1,
839 'is_active' => 1,
840 );
841 }
842
843 $params['version'] = API_LATEST_VERSION;
844
845 $result = civicrm_api('relationship_type', 'create', $params);
846
847 if (civicrm_error($params) || CRM_Utils_Array::value('is_error', $result)) {
848 throw new Exception('Could not create relationship type');
849 }
850
851 require_once 'CRM/Core/PseudoConstant.php';
852 CRM_Core_PseudoConstant::flush('relationshipType');
853
854 return $result['id'];
855 }
856
857 /**
858 * Function to delete Relatinship Type
859 *
860 * @param int $relationshipTypeID
861 */
862 function relationshipTypeDelete($relationshipTypeID) {
863 $params['id'] = $relationshipTypeID;
864 $params['version'] = API_LATEST_VERSION;
865 civicrm_api('relationship_type', 'delete', $params);
866
867 if (civicrm_error($params)) {
868 throw new Exception('Could not delete relationship type');
869 }
870
871 return;
872 }
873
874 function paymentProcessorTypeCreate($params = NULL) {
875 if (is_null($params)) {
876 $params = array(
877 'name' => 'API_Test_PP',
878 'title' => 'API Test Payment Processor',
879 'class_name' => 'CRM_Core_Payment_APITest',
880 'billing_mode' => 'form',
881 'is_recur' => 0,
882 'is_reserved' => 1,
883 'is_active' => 1,
884 );
885 }
886
887 $params['version'] = API_LATEST_VERSION;
888
889 $result = civicrm_api('payment_processor_type', 'create', $params);
890
891 if (civicrm_error($params) || CRM_Utils_Array::value('is_error', $result)) {
892 throw new Exception('Could not create payment processor type');
893 }
894
895 require_once 'CRM/Core/PseudoConstant.php';
896 CRM_Core_PseudoConstant::flush('paymentProcessorType');
897
898 return $result['id'];
899 }
900
901 /**
902 * Function to create Participant
903 *
904 * @param array $params array of contact id and event id values
905 *
906 * @return int $id of participant created
907 */
908 function participantCreate($params) {
909 $defaults = array(
910 'contact_id' => $params['contactID'],
911 'event_id' => $params['eventID'],
912 'status_id' => 2,
913 'role_id' => 1,
914 'register_date' => 20070219,
915 'source' => 'Wimbeldon',
916 'event_level' => 'Payment',
917 'version' => API_LATEST_VERSION,
918 );
919
920 $params = array_merge($defaults, $params);
921 $result = civicrm_api('Participant', 'create', $params);
922 if (CRM_Utils_Array::value('is_error', $result)) {
923 throw new Exception('Could not create participant ' . $result['error_message']);
924 }
925 return $result['id'];
926 }
927
928 /**
929 * Function to create Payment Processor
930 *
931 * @return object of Payment Processsor
932 */
933 function processorCreate() {
934 $processorParams = array(
935 'domain_id' => 1,
936 'name' => 'Dummy',
937 'payment_processor_type_id' => 10,
938 'financial_account_id' => 12,
939 'is_active' => 1,
940 'user_name' => '',
941 'url_site' => 'http://dummy.com',
942 'url_recur' => 'http://dummy.com',
943 'billing_mode' => 1,
944 );
945 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::create($processorParams);
946 return $paymentProcessor;
947 }
948
949 /**
950 * Function to create contribution page
951 *
952 * @return object of contribution page
953 */
954 function contributionPageCreate($params) {
955 $this->_pageParams = array(
956 'version' => 3,
957 'title' => 'Test Contribution Page',
958 'financial_type_id' => 1,
959 'currency' => 'USD',
960 'financial_account_id' => 1,
961 'payment_processor' => $params['processor_id'],
962 'is_active' => 1,
963 'is_allow_other_amount' => 1,
964 'min_amount' => 10,
965 'max_amount' => 1000,
966 );
967 $contributionPage = civicrm_api('contribution_page', 'create', $this->_pageParams);
968 return $contributionPage;
969 }
970
971 /**
972 * Function to create Financial Type
973 *
974 * @return int $id of financial account created
975 */
976 function contributionTypeCreate() {
977
978 $op = new PHPUnit_Extensions_Database_Operation_Insert();
979 $op->execute($this->_dbconn,
980 new PHPUnit_Extensions_Database_DataSet_XMLDataSet(
981 dirname(__FILE__) . '/../api/v' . API_LATEST_VERSION . '/dataset/financial_types.xml'
982 )
983 );
984
985 require_once 'CRM/Contribute/PseudoConstant.php';
986 $financialType = CRM_Contribute_PseudoConstant::financialType();
987 CRM_Contribute_PseudoConstant::flush('financialType');
988 return key($financialType);
989 }
990
991 /**
992 * Function to delete financial Types
993 * * @param int $contributionTypeId
994 */
995 function contributionTypeDelete($contributionTypeID = NULL) {
996 if ($contributionTypeID === NULL) {
997 civicrm_api('Contribution', 'get',
998 array(
999 'version' => 3,
1000 'financial_type_id' => 10,
1001 'api.contribution.delete' => 1,
1002 )
1003 );
1004 civicrm_api('Contribution', 'get',
1005 array(
1006 'version' => 3,
1007 'financial_type_id' => 11,
1008 'api.contribution.delete' => 1,
1009 )
1010 );
1011
1012 // we know those were loaded from /dataset/financial_types.xml
1013 $del = CRM_Financial_BAO_FinancialType::del(10, 1);
1014 $del = CRM_Financial_BAO_FinancialType::del(11, 1);
1015 }
1016 else {
1017 civicrm_api('Contribution', 'get', array(
1018 'version' => 3,
1019 'financial_type_id' => $contributionTypeID,
1020 'api.contribution.delete' => 1
1021 ));
1022 $del = CRM_Financial_BAO_FinancialType::del($contributionTypeID, 1);
1023 }
1024 if (is_array($del)) {
1025 $this->assertEquals(0, CRM_Utils_Array::value('is_error', $del), $del['error_message']);
1026 }
1027 }
1028
1029 /**
1030 * Function to create Tag
1031 *
1032 * @return int tag_id of created tag
1033 */
1034 function tagCreate($params = NULL) {
1035 if ($params === NULL) {
1036 $params = array(
1037 'name' => 'New Tag3' . rand(),
1038 'description' => 'This is description for New Tag ' . rand(),
1039 'domain_id' => '1',
1040 'version' => API_LATEST_VERSION,
1041 );
1042 }
1043
1044 $result = civicrm_api('Tag', 'create', $params);
1045 return $result;
1046 }
1047
1048 /**
1049 * Function to delete Tag
1050 *
1051 * @param int $tagId id of the tag to be deleted
1052 */
1053 function tagDelete($tagId) {
1054 require_once 'api/api.php';
1055 $params = array(
1056 'tag_id' => $tagId,
1057 'version' => API_LATEST_VERSION,
1058 );
1059 $result = civicrm_api('Tag', 'delete', $params);
1060 if (CRM_Utils_Array::value('is_error', $result)) {
1061 throw new Exception('Could not delete tag');
1062 }
1063 return $result['id'];
1064 }
1065
1066 /**
1067 * Add entity(s) to the tag
1068 *
1069 * @param array $params
1070 *
1071 */
1072 function entityTagAdd($params) {
1073 $params['version'] = API_LATEST_VERSION;
1074 $result = civicrm_api('entity_tag', 'create', $params);
1075
1076 if (CRM_Utils_Array::value('is_error', $result)) {
1077 throw new Exception('Error while creating entity tag');
1078 }
1079 return TRUE;
1080 }
1081
1082 /**
1083 * Function to create contribution
1084 *
1085 * @param int $cID contact_id
1086 * @param int $cTypeID id of financial type
1087 *
1088 * @return int id of created contribution
1089 */
1090 function pledgeCreate($cID) {
1091 $params = array(
1092 'contact_id' => $cID,
1093 'pledge_create_date' => date('Ymd'),
1094 'start_date' => date('Ymd'),
1095 'scheduled_date' => date('Ymd'),
1096 'amount' => 100.00,
1097 'pledge_status_id' => '2',
1098 'financial_type_id' => '1',
1099 'pledge_original_installment_amount' => 20,
1100 'frequency_interval' => 5,
1101 'frequency_unit' => 'year',
1102 'frequency_day' => 15,
1103 'installments' => 5,
1104 'version' => API_LATEST_VERSION,
1105 );
1106
1107 $result = civicrm_api('Pledge', 'create', $params);
1108 return $result['id'];
1109 }
1110
1111 /**
1112 * Function to delete contribution
1113 *
1114 * @param int $contributionId
1115 */
1116 function pledgeDelete($pledgeId) {
1117 $params = array(
1118 'pledge_id' => $pledgeId,
1119 'version' => API_LATEST_VERSION,
1120 );
1121
1122 civicrm_api('Pledge', 'delete', $params);
1123 }
1124
1125 /**
1126 * Function to create contribution
1127 *
1128 * @param int $cID contact_id
1129 * @param int $cTypeID id of financial type
1130 *
1131 * @return int id of created contribution
1132 */
1133 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1134 $params = array(
1135 'domain_id' => 1,
1136 'contact_id' => $cID,
1137 'receive_date' => date('Ymd'),
1138 'total_amount' => 100.00,
1139 'financial_type_id' => empty($cTypeID) ? 1 : $cTypeID,
1140 'payment_instrument_id' => empty($paymentInstrumentID) ? 1 : $paymentInstrumentID,
1141 'non_deductible_amount' => 10.00,
1142 'trxn_id' => $trxnID,
1143 'invoice_id' => $invoiceID,
1144 'source' => 'SSF',
1145 'version' => API_LATEST_VERSION,
1146 'contribution_status_id' => 1,
1147 // 'note' => 'Donating for Nobel Cause', *Fixme
1148 );
1149
1150 if ($isFee) {
1151 $params['fee_amount'] = 5.00;
1152 $params['net_amount'] = 95.00;
1153 }
1154
1155 $result = civicrm_api('contribution', 'create', $params);
1156 if (CRM_Utils_Array::value('is_error', $result) ||
1157 !CRM_Utils_Array::value('id', $result)
1158 ) {
1159 if (CRM_Utils_Array::value('error_message', $result)) {
1160 throw new Exception('Could not create contribution, with message: ' . CRM_Utils_Array::value('error_message', $result));
1161 }
1162 else {
1163 throw new Exception('Could not create contribution in line: ' . __LINE__);
1164 }
1165 }
1166
1167 return $result['id'];
1168 }
1169
1170 /**
1171 * Function to create online contribution
1172 *
1173 * @param int $financialType id of financial type
1174 *
1175 * @return int id of created contribution
1176 */
1177 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1178 $contribParams = array(
1179 'contact_id' => $params['contact_id'],
1180 'receive_date' => date('Ymd'),
1181 'total_amount' => 100.00,
1182 'financial_type_id' => $financialType,
1183 'contribution_page_id' => $params['contribution_page_id'],
1184 'trxn_id' => 12345,
1185 'invoice_id' => 67890,
1186 'source' => 'SSF',
1187 'version' => $this->_apiversion,
1188 );
1189
1190 if (isset($params['contribution_status_id'])) {
1191 $contribParams['contribution_status_id'] = $params['contribution_status_id'];
1192 }
1193 else {
1194 $contribParams['contribution_status_id'] = 1;
1195 }
1196 if (isset($params['is_pay_later'])) {
1197 $contribParams['is_pay_later'] = 1;
1198 }
1199 if (isset($params['payment_processor'])) {
1200 $contribParams['payment_processor'] = $params['payment_processor'];
1201 }
1202 $result = civicrm_api('contribution', 'create', $contribParams);
1203 if (CRM_Utils_Array::value('is_error', $result) ||
1204 !CRM_Utils_Array::value('id', $result)
1205 ) {
1206 if (CRM_Utils_Array::value('error_message', $result)) {
1207 throw new Exception('Could not create contribution, with message: ' . CRM_Utils_Array::value('error_message', $result));
1208 }
1209 else {
1210 throw new Exception('Could not create contribution in line: ' . __LINE__);
1211 }
1212 }
1213
1214 return $result['id'];
1215 }
1216
1217 /**
1218 * Function to delete contribution
1219 *
1220 * @param int $contributionId
1221 */
1222 function contributionDelete($contributionId) {
1223 $params = array(
1224 'contribution_id' => $contributionId,
1225 'version' => API_LATEST_VERSION,
1226 );
1227 $result = civicrm_api('contribution', 'delete', $params);
1228
1229 if (CRM_Utils_Array::value('is_error', $result) ||
1230 !CRM_Utils_Array::value('id', $result)
1231 ) {
1232 if (CRM_Utils_Array::value('error_message', $result)) {
1233 throw new Exception('Could not delete contribution, with message: ' . CRM_Utils_Array::value('error_message', $result));
1234 }
1235 else {
1236 throw new Exception('Could not delete contribution - in line: ' . __LINE__);
1237 }
1238 }
1239
1240 return $result;
1241 }
1242
1243 /**
1244 * Function to create an Event
1245 *
1246 * @param array $params name-value pair for an event
1247 *
1248 * @return array $event
1249 */
1250 function eventCreate($params = array()) {
1251 // if no contact was passed, make up a dummy event creator
1252 if (!isset($params['contact_id'])) {
1253 $params['contact_id'] = $this->_contactCreate(array(
1254 'contact_type' => 'Individual',
1255 'first_name' => 'Event',
1256 'last_name' => 'Creator',
1257 'version' => API_LATEST_VERSION
1258 ));
1259 }
1260
1261 // set defaults for missing params
1262 $params = array_merge(array(
1263 'title' => 'Annual CiviCRM meet',
1264 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1265 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1266 'event_type_id' => 1,
1267 'is_public' => 1,
1268 'start_date' => 20081021,
1269 'end_date' => 20081023,
1270 'is_online_registration' => 1,
1271 'registration_start_date' => 20080601,
1272 'registration_end_date' => 20081015,
1273 'max_participants' => 100,
1274 'event_full_text' => 'Sorry! We are already full',
1275 'is_monetory' => 0,
1276 'is_active' => 1,
1277 'version' => API_LATEST_VERSION,
1278 'is_show_location' => 0,
1279 ), $params);
1280
1281 $result = civicrm_api('Event', 'create', $params);
1282 if ($result['is_error'] == 1) {
1283 throw new Exception($result['error_message']);
1284 }
1285 return $result;
1286 }
1287
1288 /**
1289 * Function to delete event
1290 *
1291 * @param int $id ID of the event
1292 */
1293 function eventDelete($id) {
1294 $params = array(
1295 'event_id' => $id,
1296 'version' => API_LATEST_VERSION,
1297 );
1298 civicrm_api('event', 'delete', $params);
1299 }
1300
1301 /**
1302 * Function to delete participant
1303 *
1304 * @param int $participantID
1305 */
1306 function participantDelete($participantID) {
1307 $params = array(
1308 'id' => $participantID,
1309 'version' => API_LATEST_VERSION,
1310 );
1311 $result = civicrm_api('Participant', 'delete', $params);
1312
1313 if (CRM_Utils_Array::value('is_error', $result)) {
1314 throw new Exception('Could not delete participant');
1315 }
1316 return;
1317 }
1318
1319 /**
1320 * Function to create participant payment
1321 *
1322 * @return int $id of created payment
1323 */
1324 function participantPaymentCreate($participantID, $contributionID = NULL) {
1325 //Create Participant Payment record With Values
1326 $params = array(
1327 'participant_id' => $participantID,
1328 'contribution_id' => $contributionID,
1329 'version' => API_LATEST_VERSION,
1330 );
1331
1332 $result = civicrm_api('participant_payment', 'create', $params);
1333
1334 if (CRM_Utils_Array::value('is_error', $result) ||
1335 !CRM_Utils_Array::value('id', $result)
1336 ) {
1337 if (CRM_Utils_Array::value('error_message', $result)) {
1338 throw new Exception('Could not delete contribution, with message: ' . CRM_Utils_Array::value('error_message', $result));
1339 }
1340 else {
1341 throw new Exception('Could not delete contribution - in line: ' . __LINE__);
1342 }
1343 }
1344
1345 return $result['id'];
1346 }
1347
1348 /**
1349 * Function to delete participant payment
1350 *
1351 * @param int $paymentID
1352 */
1353 function participantPaymentDelete($paymentID) {
1354 $params = array(
1355 'id' => $paymentID,
1356 'version' => API_LATEST_VERSION,
1357 );
1358
1359 $result = civicrm_api('participant_payment', 'delete', $params);
1360
1361 if (CRM_Utils_Array::value('is_error', $result)) {
1362 if (CRM_Utils_Array::value('error_message', $result)) {
1363 throw new Exception('Could not delete contribution, with message: ' . CRM_Utils_Array::value('error_message', $result));
1364 }
1365 else {
1366 throw new Exception('Could not delete contribution - in line: ' . __LINE__);
1367 }
1368 }
1369
1370 return;
1371 }
1372
1373 /**
1374 * Function to add a Location
1375 *
1376 * @return int location id of created location
1377 */
1378 function locationAdd($contactID) {
1379 $address = array(
1380 1 => array(
1381 'location_type' => 'New Location Type',
1382 'is_primary' => 1,
1383 'name' => 'Saint Helier St',
1384 'county' => 'Marin',
1385 'country' => 'United States',
1386 'state_province' => 'Michigan',
1387 'supplemental_address_1' => 'Hallmark Ct',
1388 'supplemental_address_2' => 'Jersey Village',
1389 )
1390 );
1391
1392 $params = array(
1393 'contact_id' => $contactID,
1394 'address' => $address,
1395 'version' => 2,
1396 'location_format' => '2.0',
1397 'location_type' => 'New Location Type',
1398 );
1399
1400 $result = civicrm_api('Location', 'create', $params);
1401
1402 if (civicrm_error($result)) {
1403 throw new Exception("Could not create location: {$result['error_message']}");
1404 }
1405
1406 return $result;
1407 }
1408
1409 /**
1410 * Function to delete Locations of contact
1411 *
1412 * @params array $pamars parameters
1413 */
1414 function locationDelete($params) {
1415 $params['version'] = 2;
1416
1417 $result = civicrm_api('Location', 'delete', $params);
1418 if (civicrm_error($result)) {
1419 throw new Exception("Could not delete location: {$result['error_message']}");
1420 }
1421
1422 return;
1423 }
1424
1425 /**
1426 * Function to add a Location Type
1427 *
1428 * @return int location id of created location
1429 */
1430 function locationTypeCreate($params = NULL) {
1431 if ($params === NULL) {
1432 $params = array(
1433 'name' => 'New Location Type',
1434 'vcard_name' => 'New Location Type',
1435 'description' => 'Location Type for Delete',
1436 'is_active' => 1,
1437 );
1438 }
1439
1440 require_once 'CRM/Core/DAO/LocationType.php';
1441 $locationType = new CRM_Core_DAO_LocationType();
1442 $locationType->copyValues($params);
1443 $locationType->save();
1444 // clear getfields cache
2683ce94 1445 CRM_Core_PseudoConstant::flush();
6a488035
TO
1446 civicrm_api('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1447 return $locationType;
1448 }
1449
1450 /**
1451 * Function to delete a Location Type
1452 *
1453 * @param int location type id
1454 */
1455 function locationTypeDelete($locationTypeId) {
1456 require_once 'CRM/Core/DAO/LocationType.php';
1457 $locationType = new CRM_Core_DAO_LocationType();
1458 $locationType->id = $locationTypeId;
1459 $locationType->delete();
1460 }
1461
1462 /**
1463 * Function to add a Group
1464 *
1465 * @params array to add group
1466 *
1467 * @return int groupId of created group
1468 *
1469 */
1470 function groupCreate($params = NULL) {
1471 if ($params === NULL) {
1472 $params = array(
1473 'name' => 'Test Group 1',
1474 'domain_id' => 1,
1475 'title' => 'New Test Group Created',
1476 'description' => 'New Test Group Created',
1477 'is_active' => 1,
1478 'visibility' => 'Public Pages',
1479 'group_type' => array(
1480 '1' => 1,
1481 '2' => 1,
1482 ),
1483 'version' => API_LATEST_VERSION,
1484 );
1485 }
1486
1487 $result = civicrm_api('Group', 'create', $params);
1488 if (CRM_Utils_Array::value('id', $result)) {
1489 return $result['id'];
1490 }
1491 elseif (CRM_Utils_Array::value('result', $result)) {
1492 return $result['result']->id;
1493 }
1494 else {
1495 return NULL;
1496 }
1497 }
1498
1499 /**
1500 * Function to delete a Group
1501 *
1502 * @param int $id
1503 */
1504 function groupDelete($gid) {
1505
1506 $params = array(
1507 'id' => $gid,
1508 'version' => API_LATEST_VERSION,
1509 );
1510
1511 civicrm_api('Group', 'delete', $params);
1512 }
1513
1514 /**
1515 * Function to add a UF Join Entry
1516 *
1517 * @return int $id of created UF Join
1518 */
1519 function ufjoinCreate($params = NULL) {
1520 if ($params === NULL) {
1521 $params = array(
1522 'is_active' => 1,
1523 'module' => 'CiviEvent',
1524 'entity_table' => 'civicrm_event',
1525 'entity_id' => 3,
1526 'weight' => 1,
1527 'uf_group_id' => 1,
1528 );
1529 }
1530
1531 $result = crm_add_uf_join($params);
1532
1533 return $result;
1534 }
1535
1536 /**
1537 * Function to delete a UF Join Entry
1538 *
1539 * @param array with missing uf_group_id
1540 */
1541 function ufjoinDelete($params = NULL) {
1542 if ($params === NULL) {
1543 $params = array(
1544 'is_active' => 1,
1545 'module' => 'CiviEvent',
1546 'entity_table' => 'civicrm_event',
1547 'entity_id' => 3,
1548 'weight' => 1,
1549 'uf_group_id' => '',
1550 );
1551 }
1552
1553 crm_add_uf_join($params);
1554 }
1555
1556 /**
1557 * Function to create Group for a contact
1558 *
1559 * @param int $contactId
1560 */
1561 function contactGroupCreate($contactId) {
1562 $params = array(
1563 'contact_id.1' => $contactId,
1564 'group_id' => 1,
1565 );
1566
1567 civicrm_api('GroupContact', 'Create', $params);
1568 }
1569
1570 /**
1571 * Function to delete Group for a contact
1572 *
1573 * @param array $params
1574 */
1575 function contactGroupDelete($contactId) {
1576 $params = array(
1577 'contact_id.1' => $contactId,
1578 'group_id' => 1,
1579 );
1580 civicrm_api('GroupContact', 'Delete', $params);
1581 }
1582
1583 /**
1584 * Function to create Activity
1585 *
1586 * @param int $contactId
1587 */
1588 function activityCreate($params = NULL) {
1589
1590 if ($params === NULL) {
1591 $individualSourceID = $this->individualCreate(NULL);
1592
1593 $contactParams = array(
1594 'first_name' => 'Julia',
1595 'Last_name' => 'Anderson',
1596 'prefix' => 'Ms.',
1597 'email' => 'julia_anderson@civicrm.org',
1598 'contact_type' => 'Individual',
1599 'version' => API_LATEST_VERSION,
1600 );
1601
1602 $individualTargetID = $this->individualCreate($contactParams);
1603
1604 $params = array(
1605 'source_contact_id' => $individualSourceID,
1606 'target_contact_id' => array($individualTargetID),
1607 'assignee_contact_id' => array($individualTargetID),
1608 'subject' => 'Discussion on warm beer',
1609 'activity_date_time' => date('Ymd'),
1610 'duration_hours' => 30,
1611 'duration_minutes' => 20,
1612 'location' => 'Baker Street',
1613 'details' => 'Lets schedule a meeting',
1614 'status_id' => 1,
1615 'activity_name' => 'Meeting',
1616 'version' => API_LATEST_VERSION,
1617 );
1618 }
1619
1620
1621 $result = civicrm_api('Activity', 'create', $params);
1622
1623 $result['target_contact_id'] = $individualTargetID;
1624 $result['assignee_contact_id'] = $individualTargetID;
1625 return $result;
1626 }
1627
1628 /**
1629 * Function to create an activity type
1630 *
1631 * @params array $params parameters
1632 */
1633 function activityTypeCreate($params) {
1634 $params['version'] = API_LATEST_VERSION;
1635 $result = civicrm_api('ActivityType', 'create', $params);
1636 if (CRM_Utils_Array::value('is_error', $result) ||
1637 !CRM_Utils_Array::value('id', $result)
1638 ) {
1639 throw new Exception('Could not create Activity type ' . $result['error_message']);
1640 }
1641 return $result;
1642 }
1643
1644 /**
1645 * Function to delete activity type
1646 *
1647 * @params Integer $activityTypeId id of the activity type
1648 */
1649 function activityTypeDelete($activityTypeId) {
1650 $params['activity_type_id'] = $activityTypeId;
1651 $params['version'] = API_LATEST_VERSION;
1652 $result = civicrm_api('ActivityType', 'delete', $params);
1653 if (!$result) {
1654 throw new Exception('Could not delete activity type');
1655 }
1656 return $result;
1657 }
1658
1659 /**
1660 * Function to create custom group
1661 *
1662 * @param string $className
1663 * @param string $title name of custom group
1664 */
1665 function customGroupCreate($extends = 'Contact', $title = 'title') {
1666
1667 if (CRM_Utils_Array::value('title', $extends)) {
1668 $params = $extends;
1669 $params['title'] = strlen($params['title']) > 13 ? substr($params['title'], 0, 13) : $params['title'];
1670 }
1671 else {
1672 $params = array(
1673 'title' => strlen($title) > 13 ? substr($title, 0, 13) : $title,
1674 'extends' => $extends,
1675 'domain_id' => 1,
1676 'style' => 'Inline',
1677 'is_active' => 1,
1678 'version' => API_LATEST_VERSION,
1679 );
1680 }
1681 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1682 $check = civicrm_api('custom_group', 'get', array_merge($params, array('api.custom_group.delete' => 1)));
1683
1684 $result = civicrm_api('custom_group', 'create', $params);
1685
1686 if (CRM_Utils_Array::value('is_error', $result) ||
1687 !CRM_Utils_Array::value('id', $result)
1688 ) {
1689 throw new Exception('Could not create Custom Group ' . print_r($params, TRUE) . $result['error_message']);
1690 }
1691 return $result;
1692 }
1693
1694 /**
1695 * existing function doesn't allow params to be over-ridden so need a new one
1696 * this one allows you to only pass in the params you want to change
1697 */
1698 function CustomGroupCreateByParams($params = array()) {
1699 $defaults = array(
1700 'title' => "API Custom Group",
1701 'extends' => 'Contact',
1702 'domain_id' => 1,
1703 'style' => 'Inline',
1704 'is_active' => 1,
1705 'version' => API_LATEST_VERSION,
1706 );
1707 $params = array_merge($defaults, $params);
1708 $result = civicrm_api('custom_group', 'create', $params);
1709
1710 if (CRM_Utils_Array::value('is_error', $result) ||
1711 !CRM_Utils_Array::value('id', $result)
1712 ) {
1713 throw new Exception('Could not create Custom Group ' . $result['error_message']);
1714 }
1715 return $result;
1716 }
1717
1718 /**
1719 * Create custom group with multi fields
1720 */
1721 function CustomGroupMultipleCreateByParams($params = array()) {
1722 $defaults = array(
1723 'style' => 'Tab',
1724 'is_multiple' => 1,
1725 );
1726 $params = array_merge($defaults, $params);
1727 $result = $this->CustomGroupCreateByParams($params);
1728
1729 if (CRM_Utils_Array::value('is_error', $result) ||
1730 !CRM_Utils_Array::value('id', $result)
1731 ) {
1732 throw new Exception('Could not create Custom Group ' . $result['error_message']);
1733 }
1734 return $result;
1735 }
1736
1737 /**
1738 * Create custom group with multi fields
1739 */
1740 function CustomGroupMultipleCreateWithFields($params = array()) {
1741 // also need to pass on $params['custom_field'] if not set but not in place yet
1742 $ids = array();
1743 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1744 $ids['custom_group_id'] = $customGroup['id'];
1745 if (CRM_Utils_Array::value('is_error', $ids['custom_group_id']) ||
1746 !CRM_Utils_Array::value('id', $customGroup)
1747 ) {
1748 throw new Exception('Could not create Custom Group from CustomGroupMultipleCreateWithFields' . $customGroup['error_message']);
1749 }
1750
1751 $customField = $this->customFieldCreate($ids['custom_group_id']);
1752
1753 $ids['custom_field_id'][] = $customField['id'];
1754 if (CRM_Utils_Array::value('is_error', $customField) ||
1755 !CRM_Utils_Array::value('id', $customField)
1756 ) {
1757 throw new Exception('Could not create Custom Field ' . $ids['custom_field']['error_message']);
1758 }
1759 $customField = $this->customFieldCreate($ids['custom_group_id'], 'field_2');
1760 $ids['custom_field_id'][] = $customField['id'];
1761 if (CRM_Utils_Array::value('is_error', $customField) ||
1762 !CRM_Utils_Array::value('id', $customField)
1763 ) {
1764 throw new Exception('Could not create Custom Field ' . $ids['custom_field']['error_message']);
1765 }
1766 $customField = $this->customFieldCreate($ids['custom_group_id'], 'field_3');
1767 $ids['custom_field_id'][] = $customField['id'];
1768 if (CRM_Utils_Array::value('is_error', $customField) ||
1769 !CRM_Utils_Array::value('id', $customField)
1770 ) {
1771 throw new Exception('Could not create Custom Field ' . $ids['custom_field']['error_message']);
1772 }
1773 return $ids;
1774 }
1775
1776 /**
1777 * Create a custom group with a single text custom field. See
1778 * participant:testCreateWithCustom for how to use this
1779 *
1780 * @param string $function __FUNCTION__
1781 * @param string $file __FILE__
1782 *
1783 * @return array $ids ids of created objects
1784 *
1785 */
1786 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1787 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1788 if (empty($entity)) {
1789 $entity = 'Contact';
1790 }
1791 $customGroup = $this->CustomGroupCreate($entity, $function);
1792 $customField = $this->customFieldCreate($customGroup['id'], $function);
1793 CRM_Core_PseudoConstant::flush('customGroup');
1794
1795 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1796 }
1797
1798 /**
1799 * Function to delete custom group
1800 *
1801 * @param int $customGroupID
1802 */
1803 function customGroupDelete($customGroupID) {
1804
1805 $params['id'] = $customGroupID;
1806 $params['version'] = API_LATEST_VERSION;
1807 $result = civicrm_api('custom_group', 'delete', $params);
1808 if (CRM_Utils_Array::value('is_error', $result)) {
1809 print_r($params);
1810 throw new Exception('Could not delete custom group' . $result['error_message']);
1811 }
1812 return;
1813 }
1814
1815 /**
1816 * Function to create custom field
1817 *
1818 * @param int $customGroupID
1819 * @param string $name name of custom field
1820 * @param int $apiversion API version to use
1821 */
1822 function customFieldCreate($customGroupID, $name = "Cust Field") {
1823
1824 $params = array(
1825 'label' => $name,
1826 'name' => $name,
1827 'custom_group_id' => $customGroupID,
1828 'data_type' => 'String',
1829 'html_type' => 'Text',
1830 'is_searchable' => 1,
1831 'is_active' => 1,
1832 'version' => API_LATEST_VERSION,
1833 );
1834
1835 $result = civicrm_api('custom_field', 'create', $params);
1836
1837 if ($result['is_error'] == 0 && isset($result['id'])) {
1838 CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
1839 // force reset of enabled components to help grab custom fields
1840 CRM_Core_Component::getEnabledComponents(1);
1841 return $result;
1842 }
1843
1844 if (civicrm_error($result)
1845 || !(CRM_Utils_Array::value('customFieldId', $result['result']))
1846 ) {
1847 throw new Exception('Could not create Custom Field ' . $result['error_message']);
1848 }
1849 }
1850
1851 /**
1852 * Function to delete custom field
1853 *
1854 * @param int $customFieldID
1855 */
1856 function customFieldDelete($customFieldID) {
1857
1858 $params['id'] = $customFieldID;
1859 $params['version'] = API_LATEST_VERSION;
1860
1861 $result = civicrm_api('custom_field', 'delete', $params);
1862
1863 if (civicrm_error($result)) {
1864 throw new Exception('Could not delete custom field');
1865 }
1866 return;
1867 }
1868
1869 /**
1870 * Function to create note
1871 *
1872 * @params array $params name-value pair for an event
1873 *
1874 * @return array $note
1875 */
1876 function noteCreate($cId) {
1877 $params = array(
1878 'entity_table' => 'civicrm_contact',
1879 'entity_id' => $cId,
1880 'note' => 'hello I am testing Note',
1881 'contact_id' => $cId,
1882 'modified_date' => date('Ymd'),
1883 'subject' => 'Test Note',
1884 'version' => API_LATEST_VERSION,
1885 );
1886
1887 $result = civicrm_api('Note', 'create', $params);
1888
1889 if (CRM_Utils_Array::value('is_error', $result)) {
1890 if (CRM_Utils_Array::value('error_message', $result)) {
1891 throw new Exception('Could not delete note, with message: ' . CRM_Utils_Array::value('error_message', $result));
1892 }
1893 else {
1894 throw new Exception('Could not delete note - in line: ' . __LINE__);
1895 }
1896 }
1897
1898 return $result;
1899 }
1900
1901 /**
1902 * Create test generated example in api/v3/examples.
1903 * To turn this off (e.g. on the server) set
1904 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
1905 * in your settings file
1906 * @param array $params array as passed to civicrm_api function
1907 * @param array $result array as received from the civicrm_api function
1908 * @param string $function calling function - generally __FUNCTION__
1909 * @param string $filename called from file - generally __FILE__
1910 * @param string $description descriptive text for the example file
1911 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
1912 * @param string $action - optional action - otherwise taken from function name
1913 */
1914 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
1915 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
1916 return;
1917 }
1918 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1919 //todo - this is a bit cludgey
1920 if (empty($action)) {
1921 if (strstr($function, 'Create')) {
1922 $action = empty($action) ? 'create' : $action;
1923 $entityAction = 'Create';
1924 }
1925 elseif (strstr($function, 'GetSingle')) {
1926 $action = empty($action) ? 'getsingle' : $action;
1927 $entityAction = 'GetSingle';
1928 }
1929 elseif (strstr($function, 'GetValue')) {
1930 $action = empty($action) ? 'getvalue' : $action;
1931 $entityAction = 'GetValue';
1932 }
1933 elseif (strstr($function, 'GetCount')) {
1934 $action = empty($action) ? 'getcount' : $action;
1935 $entityAction = 'GetCount';
1936 }
1937 elseif (strstr($function, 'Get')) {
1938 $action = empty($action) ? 'get' : $action;
1939 $entityAction = 'Get';
1940 }
1941 elseif (strstr($function, 'Delete')) {
1942 $action = empty($action) ? 'delete' : $action;
1943 $entityAction = 'Delete';
1944 }
1945 elseif (strstr($function, 'Update')) {
1946 $action = empty($action) ? 'update' : $action;
1947 $entityAction = 'Update';
1948 }
1949 elseif (strstr($function, 'Subscribe')) {
1950 $action = empty($action) ? 'subscribe' : $action;
1951 $entityAction = 'Subscribe';
1952 }
1953 elseif (strstr($function, 'Set')) {
1954 $action = empty($action) ? 'set' : $action;
1955 $entityAction = 'Set';
1956 }
1957 elseif (strstr($function, 'Apply')) {
1958 $action = empty($action) ? 'apply' : $action;
1959 $entityAction = 'Apply';
1960 }
1961 elseif (strstr($function, 'Replace')) {
1962 $action = empty($action) ? 'replace' : $action;
1963 $entityAction = 'Replace';
1964 }
1965 }
1966 else {
1967 $entityAction = ucwords($action);
1968 }
1969
1970 $fieldsToChange = array(
1971 'hash' => '67eac7789eaee00',
1972 'modified_date' => '2012-11-14 16:02:35',
1973 );
1974 //swap out keys that change too often
1975 foreach ($fieldsToChange as $changeKey => $changeValue) {
1976 if (isset($result['values']) && is_array($result['values'])) {
1977 foreach ($result['values'] as $key => $value) {
1978 if (is_array($value) && array_key_exists($changeKey, $value)) {
1979 $result['values'][$key][$changeKey] = $changeValue;
1980 }
1981 }
1982 }
1983 }
1984
1985 // a cleverer person than me would do it in a single regex
1986 if (strstr($entity, 'UF')) {
1987 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
1988 }
1989 else {
1990 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
1991 }
1992 $smarty = CRM_Core_Smarty::singleton();
1993 $smarty->assign('testfunction', $function);
1994 $function = $fnPrefix . "_" . strtolower($action);
1995 $smarty->assign('function', $function);
1996 $smarty->assign('fnPrefix', $fnPrefix);
1997 $smarty->assign('params', $params);
1998 $smarty->assign('entity', $entity);
1999 $smarty->assign('filename', basename($filename));
2000 $smarty->assign('description', $description);
2001 $smarty->assign('result', $result);
2002
2003 $smarty->assign('action', $action);
2004 if (empty($subfile)) {
2005 if (file_exists('../tests/templates/documentFunction.tpl')) {
2006 $f = fopen("../api/v3/examples/$entity$entityAction.php", "w");
2007 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2008 fclose($f);
2009 }
2010 }
2011 else {
2012 if (file_exists('../tests/templates/documentFunction.tpl')) {
2013 if (!is_dir("../api/v3/examples/$entity")) {
2014 mkdir("../api/v3/examples/$entity");
2015 }
2016 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2017 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2018 fclose($f);
2019 }
2020 }
2021 }
2022
2023 /**
2024 * Function to delete note
2025 *
2026 * @params int $noteID
2027 *
2028 */
2029 function noteDelete($params) {
2030 $params['version'] = API_LATEST_VERSION;
2031
2032 $result = civicrm_api('Note', 'delete', $params);
2033
2034 if (CRM_Utils_Array::value('is_error', $result)) {
2035 if (CRM_Utils_Array::value('error_message', $result)) {
2036 throw new Exception('Could not delete note, with message: ' . CRM_Utils_Array::value('error_message', $result));
2037 }
2038 else {
2039 throw new Exception('Could not delete note - in line: ' . __LINE__);
2040 }
2041 }
2042
2043 return $result;
2044 }
2045
2046 /**
2047 * Function to create custom field with Option Values
2048 *
2049 * @param array $customGroup
2050 * @param string $name name of custom field
2051 */
2052 function customFieldOptionValueCreate($customGroup, $name) {
2053 $fieldParams = array(
2054 'custom_group_id' => $customGroup['id'],
2055 'name' => 'test_custom_group',
2056 'label' => 'Country',
2057 'html_type' => 'Select',
2058 'data_type' => 'String',
2059 'weight' => 4,
2060 'is_required' => 1,
2061 'is_searchable' => 0,
2062 'is_active' => 1,
2063 'version' => API_LATEST_VERSION,
2064 );
2065
2066 $optionGroup = array(
2067 'domain_id' => 1,
2068 'name' => 'option_group1',
2069 'label' => 'option_group_label1',
2070 );
2071
2072 $optionValue = array(
2073 'option_label' => array('Label1', 'Label2'),
2074 'option_value' => array('value1', 'value2'),
2075 'option_name' => array($name . '_1', $name . '_2'),
2076 'option_weight' => array(1, 2),
2077 'option_status' => 1,
2078 );
2079
2080 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2081
2082 $result = civicrm_api('custom_field', 'create', $params);
2083
2084 if ($result['is_error'] == 0 && isset($result['id'])) {
2085 return $result;
2086 }
2087 if (civicrm_error($result)
2088 || !(CRM_Utils_Array::value('customFieldId', $result['result']))
2089 ) {
2090 throw new Exception('Could not create Custom Field');
2091 }
2092 return $result;
2093 }
2094
2095 function confirmEntitiesDeleted($entities) {
2096 foreach ($entities as $entity) {
2097
2098 $result = civicrm_api($entity, 'Get', array(
2099 'version' => 3,
2100 ));
2101 if ($result['error'] == 1 || $result['count'] > 0) {
2102 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2103 return TRUE;
2104 }
2105 }
2106 }
2107
2108 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2109 if ($dropCustomValueTables) {
2110 $tablesToTruncate[] = 'civicrm_custom_group';
2111 $tablesToTruncate[] = 'civicrm_custom_field';
2112 }
2113
2114 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2115 foreach ($tablesToTruncate as $table) {
2116 $sql = "TRUNCATE TABLE $table";
2117 CRM_Core_DAO::executeQuery($sql);
2118 }
2119 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2120
2121 if ($dropCustomValueTables) {
2122 $dbName = self::getDBName();
2123 $query = "
2124SELECT TABLE_NAME as tableName
2125FROM INFORMATION_SCHEMA.TABLES
2126WHERE TABLE_SCHEMA = '{$dbName}'
2127AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2128";
2129
2130 $tableDAO = CRM_Core_DAO::executeQuery($query);
2131 while ($tableDAO->fetch()) {
2132 $sql = "DROP TABLE {$tableDAO->tableName}";
2133 CRM_Core_DAO::executeQuery($sql);
2134 }
2135 }
2136 }
2137
2138 /*
2139 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2140 * Default behaviour is to also delete the entity
2141 * @param array $params params array to check agains
2142 * @param int $id id of the entity concerned
2143 * @param string $entity name of entity concerned (e.g. membership)
2144 * @param bool $delete should the entity be deleted as part of this check
2145 * @param string $errorText text to print on error
2146 *
2147 */
2148 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2149
2150 $result = civicrm_api($entity, 'GetSingle', array(
2151 'id' => $id,
2152 'version' => $this->_apiversion,
2153 ));
2154
2155 if ($delete) {
2156 civicrm_api($entity, 'Delete', array(
2157 'id' => $id,
2158 'version' => $this->_apiversion,
2159 ));
2160 }
2161 $dateFields = $keys = array();
2162 $fields = civicrm_api($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2163 foreach ($fields['values'] as $field => $settings) {
2164 if (array_key_exists($field, $result)) {
2165 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = $field;
2166 }
2167 else {
2168 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = CRM_Utils_Array::value('name', $settings, $field);
2169 }
2170
2171 if (CRM_Utils_Array::value('type', $settings) == CRM_Utils_Type::T_DATE) {
2172 $dateFields[] = $field;
2173 }
2174 }
2175
2176 if (strtolower($entity) == 'contribution') {
2177 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2178 // this is not returned in id format
2179 unset($params['payment_instrument_id']);
2180 $params['contribution_source'] = $params['source'];
2181 unset($params['source']);
2182 }
2183
2184 foreach ($params as $key => $value) {
2185 if ($key == 'version' || substr($key, 0, 3) == 'api') {
2186 continue;
2187 }
2188 if (in_array($key, $dateFields)) {
2189 $value = date('Y-m-d', strtotime($value));
2190 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2191 }
2192 $this->assertEquals($value, $result[$keys[$key]], $key . " GetandCheck function determines that value: $value doesn't match " . print_r($result, TRUE) . $errorText);
2193 }
2194 }
2195
2196 /**
2197 * Function to get formatted values in the actual and expected result
2198 * @param array $actual actual calculated values
2199 * @param array $expected expected values
2200 *
2201 */
2202 function checkArrayEquals(&$actual, &$expected) {
2203 self::unsetId($actual);
2204 self::unsetId($expected);
2205 $this->assertEquals($actual, $expected);
2206 }
2207
2208 /**
2209 * Function to unset the key 'id' from the array
2210 * @param array $unformattedArray The array from which the 'id' has to be unset
2211 *
2212 */
2213 static function unsetId(&$unformattedArray) {
2214 $formattedArray = array();
2215 if (array_key_exists('id', $unformattedArray)) {
2216 unset($unformattedArray['id']);
2217 }
2218 if (CRM_Utils_Array::value('values', $unformattedArray) && is_array($unformattedArray['values'])) {
2219 foreach ($unformattedArray['values'] as $key => $value) {
2220 if (is_Array($value)) {
2221 foreach ($value as $k => $v) {
2222 if ($k == 'id') {
2223 unset($value[$k]);
2224 }
2225 }
2226 }
2227 elseif ($key == 'id') {
2228 $unformattedArray[$key];
2229 }
2230 $formattedArray = array($value);
2231 }
2232 $unformattedArray['values'] = $formattedArray;
2233 }
2234 }
2235
2236 /**
2237 * Helper to enable/disable custom directory support
2238 *
2239 * @param array $customDirs with members:
2240 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2241 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2242 */
2243 function customDirectories($customDirs) {
2244 require_once 'CRM/Core/Config.php';
2245 $config = CRM_Core_Config::singleton();
2246
2247 if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
2248 unset($config->customPHPPathDir);
2249 }
2250 elseif ($customDirs['php_path'] === TRUE) {
2251 $config->customPHPPathDir = dirname(dirname(__FILE__)) . '/custom_directories/php/';
2252 }
2253 else {
2254 $config->customPHPPathDir = $php_path;
2255 }
2256
2257 if (empty($customDirs['template_path']) || $customDirs['template_path'] === FALSE) {
2258 unset($config->customTemplateDir);
2259 }
2260 elseif ($customDirs['template_path'] === TRUE) {
2261 $config->customTemplateDir = dirname(dirname(__FILE__)) . '/custom_directories/templates/';
2262 }
2263 else {
2264 $config->customTemplateDir = $template_path;
2265 }
2266 }
2267
2268 /**
2269 * Generate a temporary folder
2270 *
2271 * @return $string
2272 */
2273 function createTempDir($prefix = 'test-') {
2274 $tempDir = CRM_Utils_File::tempdir($prefix);
2275 $this->tempDirs[] = $tempDir;
2276 return $tempDir;
2277 }
2278
2279 function cleanTempDirs() {
2280 if (!is_array($this->tempDirs)) {
2281 // fix test errors where this is not set
2282 return;
2283 }
2284 foreach ($this->tempDirs as $tempDir) {
2285 if (is_dir($tempDir)) {
2286 CRM_Utils_File::cleanDir($tempDir, TRUE, FALSE);
2287 }
2288 }
2289 }
2290
2291 /**
2292 * Temporarily replace the singleton extension with a different one
2293 */
2294 function setExtensionSystem(CRM_Extension_System $system) {
2295 if ($this->origExtensionSystem == NULL) {
2296 $this->origExtensionSystem = CRM_Extension_System::singleton();
2297 }
2298 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2299 }
2300
2301 function unsetExtensionSystem() {
2302 if ($this->origExtensionSystem !== NULL) {
2303 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2304 $this->origExtensionSystem = NULL;
2305 }
2306 }
f17d75bb
PN
2307
2308 function financialAccountDelete($name) {
2309 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2310 $financialAccount->name = $name;
2311 if($financialAccount->find(TRUE)) {
2312 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2313 $entityFinancialType->financial_account_id = $financialAccount->id;
2314 $entityFinancialType->delete();
2315 $financialAccount->delete();
2316 }
2317 }
6a488035
TO
2318}
2319
2320function CiviUnitTestCase_fatalErrorHandler($message) {
2321 throw new Exception("{$message['message']}: {$message['code']}");
2322}