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