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