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