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