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