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