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