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