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