Merge pull request #14011 from colemanw/typeValidateCleanup
[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 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1361 $this->callAPISuccess('custom_group', 'get', array(
1362 'title' => $params['title'],
1363 array('api.custom_group.delete' => 1),
1364 ));
1365
1366 return $this->callAPISuccess('custom_group', 'create', $params);
1367 }
1368
1369 /**
1370 * Existing function doesn't allow params to be over-ridden so need a new one
1371 * this one allows you to only pass in the params you want to change
1372 * @param array $params
1373 * @return array|int
1374 */
1375 public function CustomGroupCreateByParams($params = array()) {
1376 $defaults = array(
1377 'title' => "API Custom Group",
1378 'extends' => 'Contact',
1379 'domain_id' => 1,
1380 'style' => 'Inline',
1381 'is_active' => 1,
1382 );
1383 $params = array_merge($defaults, $params);
1384 return $this->callAPISuccess('custom_group', 'create', $params);
1385 }
1386
1387 /**
1388 * Create custom group with multi fields.
1389 * @param array $params
1390 * @return array|int
1391 */
1392 public function CustomGroupMultipleCreateByParams($params = array()) {
1393 $defaults = array(
1394 'style' => 'Tab',
1395 'is_multiple' => 1,
1396 );
1397 $params = array_merge($defaults, $params);
1398 return $this->CustomGroupCreateByParams($params);
1399 }
1400
1401 /**
1402 * Create custom group with multi fields.
1403 * @param array $params
1404 * @return array
1405 */
1406 public function CustomGroupMultipleCreateWithFields($params = array()) {
1407 // also need to pass on $params['custom_field'] if not set but not in place yet
1408 $ids = array();
1409 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1410 $ids['custom_group_id'] = $customGroup['id'];
1411
1412 $customField = $this->customFieldCreate(array(
1413 'custom_group_id' => $ids['custom_group_id'],
1414 'label' => 'field_1' . $ids['custom_group_id'],
1415 'in_selector' => 1,
1416 ));
1417
1418 $ids['custom_field_id'][] = $customField['id'];
1419
1420 $customField = $this->customFieldCreate(array(
1421 'custom_group_id' => $ids['custom_group_id'],
1422 'default_value' => '',
1423 'label' => 'field_2' . $ids['custom_group_id'],
1424 'in_selector' => 1,
1425 ));
1426 $ids['custom_field_id'][] = $customField['id'];
1427
1428 $customField = $this->customFieldCreate(array(
1429 'custom_group_id' => $ids['custom_group_id'],
1430 'default_value' => '',
1431 'label' => 'field_3' . $ids['custom_group_id'],
1432 'in_selector' => 1,
1433 ));
1434 $ids['custom_field_id'][] = $customField['id'];
1435
1436 return $ids;
1437 }
1438
1439 /**
1440 * Create a custom group with a single text custom field. See
1441 * participant:testCreateWithCustom for how to use this
1442 *
1443 * @param string $function
1444 * __FUNCTION__.
1445 * @param string $filename
1446 * $file __FILE__.
1447 *
1448 * @return array
1449 * ids of created objects
1450 */
1451 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
1452 $params = array('title' => $function);
1453 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1454 $params['extends'] = $entity ? $entity : 'Contact';
1455 $customGroup = $this->CustomGroupCreate($params);
1456 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
1457 CRM_Core_PseudoConstant::flush();
1458
1459 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1460 }
1461
1462 /**
1463 * Create a custom group with a single text custom field, multi-select widget, with a variety of option values including upper and lower case.
1464 * See api_v3_SyntaxConformanceTest:testCustomDataGet for how to use this
1465 *
1466 * @param string $function
1467 * __FUNCTION__.
1468 * @param string $filename
1469 * $file __FILE__.
1470 *
1471 * @return array
1472 * ids of created objects
1473 */
1474 public function entityCustomGroupWithSingleStringMultiSelectFieldCreate($function, $filename) {
1475 $params = array('title' => $function);
1476 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
1477 $params['extends'] = $entity ? $entity : 'Contact';
1478 $customGroup = $this->CustomGroupCreate($params);
1479 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function, 'html_type' => 'Multi-Select', 'default_value' => 1));
1480 CRM_Core_PseudoConstant::flush();
1481 $options = [
1482 'defaultValue' => 'Default Value',
1483 'lowercasevalue' => 'Lowercase Value',
1484 1 => 'Integer Value',
1485 'NULL' => 'NULL',
1486 ];
1487 $custom_field_params = ['sequential' => 1, 'id' => $customField['id']];
1488 $custom_field_api_result = $this->callAPISuccess('custom_field', 'get', $custom_field_params);
1489 $this->assertNotEmpty($custom_field_api_result['values'][0]['option_group_id']);
1490 $option_group_params = ['sequential' => 1, 'id' => $custom_field_api_result['values'][0]['option_group_id']];
1491 $option_group_result = $this->callAPISuccess('OptionGroup', 'get', $option_group_params);
1492 $this->assertNotEmpty($option_group_result['values'][0]['name']);
1493 foreach ($options as $option_value => $option_label) {
1494 $option_group_params = ['option_group_id' => $option_group_result['values'][0]['name'], 'value' => $option_value, 'label' => $option_label];
1495 $option_value_result = $this->callAPISuccess('OptionValue', 'create', $option_group_params);
1496 }
1497
1498 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);
1499 }
1500
1501 /**
1502 * Delete custom group.
1503 *
1504 * @param int $customGroupID
1505 *
1506 * @return array|int
1507 */
1508 public function customGroupDelete($customGroupID) {
1509 $params['id'] = $customGroupID;
1510 return $this->callAPISuccess('custom_group', 'delete', $params);
1511 }
1512
1513 /**
1514 * Create custom field.
1515 *
1516 * @param array $params
1517 * (custom_group_id) is required.
1518 * @return array
1519 */
1520 public function customFieldCreate($params) {
1521 $params = array_merge(array(
1522 'label' => 'Custom Field',
1523 'data_type' => 'String',
1524 'html_type' => 'Text',
1525 'is_searchable' => 1,
1526 'is_active' => 1,
1527 'default_value' => 'defaultValue',
1528 ), $params);
1529
1530 $result = $this->callAPISuccess('custom_field', 'create', $params);
1531 // these 2 functions are called with force to flush static caches
1532 CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
1533 CRM_Core_Component::getEnabledComponents(1);
1534 return $result;
1535 }
1536
1537 /**
1538 * Delete custom field.
1539 *
1540 * @param int $customFieldID
1541 *
1542 * @return array|int
1543 */
1544 public function customFieldDelete($customFieldID) {
1545
1546 $params['id'] = $customFieldID;
1547 return $this->callAPISuccess('custom_field', 'delete', $params);
1548 }
1549
1550 /**
1551 * Create note.
1552 *
1553 * @param int $cId
1554 * @return array
1555 */
1556 public function noteCreate($cId) {
1557 $params = array(
1558 'entity_table' => 'civicrm_contact',
1559 'entity_id' => $cId,
1560 'note' => 'hello I am testing Note',
1561 'contact_id' => $cId,
1562 'modified_date' => date('Ymd'),
1563 'subject' => 'Test Note',
1564 );
1565
1566 return $this->callAPISuccess('Note', 'create', $params);
1567 }
1568
1569 /**
1570 * Enable CiviCampaign Component.
1571 *
1572 * @param bool $reloadConfig
1573 * Force relaod config or not
1574 */
1575 public function enableCiviCampaign($reloadConfig = TRUE) {
1576 CRM_Core_BAO_ConfigSetting::enableComponent('CiviCampaign');
1577 if ($reloadConfig) {
1578 // force reload of config object
1579 $config = CRM_Core_Config::singleton(TRUE, TRUE);
1580 }
1581 //flush cache by calling with reset
1582 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
1583 }
1584
1585 /**
1586 * Create custom field with Option Values.
1587 *
1588 * @param array $customGroup
1589 * @param string $name
1590 * Name of custom field.
1591 * @param array $extraParams
1592 * Additional parameters to pass through.
1593 *
1594 * @return array|int
1595 */
1596 public function customFieldOptionValueCreate($customGroup, $name, $extraParams = array()) {
1597 $fieldParams = array(
1598 'custom_group_id' => $customGroup['id'],
1599 'name' => 'test_custom_group',
1600 'label' => 'Country',
1601 'html_type' => 'Select',
1602 'data_type' => 'String',
1603 'weight' => 4,
1604 'is_required' => 1,
1605 'is_searchable' => 0,
1606 'is_active' => 1,
1607 );
1608
1609 $optionGroup = array(
1610 'domain_id' => 1,
1611 'name' => 'option_group1',
1612 'label' => 'option_group_label1',
1613 );
1614
1615 $optionValue = array(
1616 'option_label' => array('Label1', 'Label2'),
1617 'option_value' => array('value1', 'value2'),
1618 'option_name' => array($name . '_1', $name . '_2'),
1619 'option_weight' => array(1, 2),
1620 'option_status' => 1,
1621 );
1622
1623 $params = array_merge($fieldParams, $optionGroup, $optionValue, $extraParams);
1624
1625 return $this->callAPISuccess('custom_field', 'create', $params);
1626 }
1627
1628 /**
1629 * @param $entities
1630 *
1631 * @return bool
1632 */
1633 public function confirmEntitiesDeleted($entities) {
1634 foreach ($entities as $entity) {
1635
1636 $result = $this->callAPISuccess($entity, 'Get', array());
1637 if ($result['error'] == 1 || $result['count'] > 0) {
1638 // > than $entity[0] to allow a value to be passed in? e.g. domain?
1639 return TRUE;
1640 }
1641 }
1642 return FALSE;
1643 }
1644
1645 /**
1646 * Quick clean by emptying tables created for the test.
1647 *
1648 * @param array $tablesToTruncate
1649 * @param bool $dropCustomValueTables
1650 * @throws \Exception
1651 */
1652 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
1653 if ($this->tx) {
1654 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
1655 }
1656 if ($dropCustomValueTables) {
1657 $optionGroupResult = CRM_Core_DAO::executeQuery('SELECT option_group_id FROM civicrm_custom_field');
1658 while ($optionGroupResult->fetch()) {
1659 if (!empty($optionGroupResult->option_group_id)) {
1660 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_option_group WHERE id = ' . $optionGroupResult->option_group_id);
1661 }
1662 }
1663 $tablesToTruncate[] = 'civicrm_custom_group';
1664 $tablesToTruncate[] = 'civicrm_custom_field';
1665 }
1666
1667 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate, $tablesToTruncate));
1668
1669 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1670 foreach ($tablesToTruncate as $table) {
1671 $sql = "TRUNCATE TABLE $table";
1672 CRM_Core_DAO::executeQuery($sql);
1673 }
1674 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1675
1676 if ($dropCustomValueTables) {
1677 $dbName = self::getDBName();
1678 $query = "
1679 SELECT TABLE_NAME as tableName
1680 FROM INFORMATION_SCHEMA.TABLES
1681 WHERE TABLE_SCHEMA = '{$dbName}'
1682 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
1683 ";
1684
1685 $tableDAO = CRM_Core_DAO::executeQuery($query);
1686 while ($tableDAO->fetch()) {
1687 $sql = "DROP TABLE {$tableDAO->tableName}";
1688 CRM_Core_DAO::executeQuery($sql);
1689 }
1690 }
1691 }
1692
1693 /**
1694 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
1695 */
1696 public function quickCleanUpFinancialEntities() {
1697 $tablesToTruncate = array(
1698 'civicrm_activity',
1699 'civicrm_activity_contact',
1700 'civicrm_contribution',
1701 'civicrm_contribution_soft',
1702 'civicrm_contribution_product',
1703 'civicrm_financial_trxn',
1704 'civicrm_financial_item',
1705 'civicrm_contribution_recur',
1706 'civicrm_line_item',
1707 'civicrm_contribution_page',
1708 'civicrm_payment_processor',
1709 'civicrm_entity_financial_trxn',
1710 'civicrm_membership',
1711 'civicrm_membership_type',
1712 'civicrm_membership_payment',
1713 'civicrm_membership_log',
1714 'civicrm_membership_block',
1715 'civicrm_event',
1716 'civicrm_participant',
1717 'civicrm_participant_payment',
1718 'civicrm_pledge',
1719 'civicrm_pledge_payment',
1720 'civicrm_price_set_entity',
1721 'civicrm_price_field_value',
1722 'civicrm_price_field',
1723 );
1724 $this->quickCleanup($tablesToTruncate);
1725 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
1726 $this->restoreDefaultPriceSetConfig();
1727 $var = TRUE;
1728 CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE);
1729 $this->disableTaxAndInvoicing();
1730 $this->setCurrencySeparators(',');
1731 CRM_Core_PseudoConstant::flush('taxRates');
1732 System::singleton()->flushProcessors();
1733 }
1734
1735 public function restoreDefaultPriceSetConfig() {
1736 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_price_set WHERE name NOT IN('default_contribution_amount', 'default_membership_type_amount')");
1737 CRM_Core_DAO::executeQuery("UPDATE civicrm_price_set SET id = 1 WHERE name ='default_contribution_amount'");
1738 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)");
1739 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)");
1740 }
1741
1742 /*
1743 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
1744 * Default behaviour is to also delete the entity
1745 * @param array $params
1746 * Params array to check against.
1747 * @param int $id
1748 * Id of the entity concerned.
1749 * @param string $entity
1750 * Name of entity concerned (e.g. membership).
1751 * @param bool $delete
1752 * Should the entity be deleted as part of this check.
1753 * @param string $errorText
1754 * Text to print on error.
1755 */
1756
1757 /**
1758 * @param array $params
1759 * @param int $id
1760 * @param $entity
1761 * @param int $delete
1762 * @param string $errorText
1763 *
1764 * @throws Exception
1765 */
1766 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
1767
1768 $result = $this->callAPISuccessGetSingle($entity, array(
1769 'id' => $id,
1770 ));
1771
1772 if ($delete) {
1773 $this->callAPISuccess($entity, 'Delete', array(
1774 'id' => $id,
1775 ));
1776 }
1777 $dateFields = $keys = $dateTimeFields = array();
1778 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
1779 foreach ($fields['values'] as $field => $settings) {
1780 if (array_key_exists($field, $result)) {
1781 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = $field;
1782 }
1783 else {
1784 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = CRM_Utils_Array::value('name', $settings, $field);
1785 }
1786 $type = CRM_Utils_Array::value('type', $settings);
1787 if ($type == CRM_Utils_Type::T_DATE) {
1788 $dateFields[] = $settings['name'];
1789 // we should identify both real names & unique names as dates
1790 if ($field != $settings['name']) {
1791 $dateFields[] = $field;
1792 }
1793 }
1794 if ($type == CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) {
1795 $dateTimeFields[] = $settings['name'];
1796 // we should identify both real names & unique names as dates
1797 if ($field != $settings['name']) {
1798 $dateTimeFields[] = $field;
1799 }
1800 }
1801 }
1802
1803 if (strtolower($entity) == 'contribution') {
1804 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
1805 // this is not returned in id format
1806 unset($params['payment_instrument_id']);
1807 $params['contribution_source'] = $params['source'];
1808 unset($params['source']);
1809 }
1810
1811 foreach ($params as $key => $value) {
1812 if ($key == 'version' || substr($key, 0, 3) == 'api' || !array_key_exists($keys[$key], $result)) {
1813 continue;
1814 }
1815 if (in_array($key, $dateFields)) {
1816 $value = date('Y-m-d', strtotime($value));
1817 $result[$key] = date('Y-m-d', strtotime($result[$key]));
1818 }
1819 if (in_array($key, $dateTimeFields)) {
1820 $value = date('Y-m-d H:i:s', strtotime($value));
1821 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array::value($keys[$key], $result, CRM_Utils_Array::value($key, $result))));
1822 }
1823 $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);
1824 }
1825 }
1826
1827 /**
1828 * Get formatted values in the actual and expected result.
1829 * @param array $actual
1830 * Actual calculated values.
1831 * @param array $expected
1832 * Expected values.
1833 */
1834 public function checkArrayEquals(&$actual, &$expected) {
1835 self::unsetId($actual);
1836 self::unsetId($expected);
1837 $this->assertEquals($actual, $expected);
1838 }
1839
1840 /**
1841 * Unset the key 'id' from the array
1842 * @param array $unformattedArray
1843 * The array from which the 'id' has to be unset.
1844 */
1845 public static function unsetId(&$unformattedArray) {
1846 $formattedArray = array();
1847 if (array_key_exists('id', $unformattedArray)) {
1848 unset($unformattedArray['id']);
1849 }
1850 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
1851 foreach ($unformattedArray['values'] as $key => $value) {
1852 if (is_array($value)) {
1853 foreach ($value as $k => $v) {
1854 if ($k == 'id') {
1855 unset($value[$k]);
1856 }
1857 }
1858 }
1859 elseif ($key == 'id') {
1860 $unformattedArray[$key];
1861 }
1862 $formattedArray = array($value);
1863 }
1864 $unformattedArray['values'] = $formattedArray;
1865 }
1866 }
1867
1868 /**
1869 * Helper to enable/disable custom directory support
1870 *
1871 * @param array $customDirs
1872 * With members:.
1873 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1874 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
1875 */
1876 public function customDirectories($customDirs) {
1877 $config = CRM_Core_Config::singleton();
1878
1879 if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
1880 unset($config->customPHPPathDir);
1881 }
1882 elseif ($customDirs['php_path'] === TRUE) {
1883 $config->customPHPPathDir = dirname(dirname(__FILE__)) . '/custom_directories/php/';
1884 }
1885 else {
1886 $config->customPHPPathDir = $php_path;
1887 }
1888
1889 if (empty($customDirs['template_path']) || $customDirs['template_path'] === FALSE) {
1890 unset($config->customTemplateDir);
1891 }
1892 elseif ($customDirs['template_path'] === TRUE) {
1893 $config->customTemplateDir = dirname(dirname(__FILE__)) . '/custom_directories/templates/';
1894 }
1895 else {
1896 $config->customTemplateDir = $template_path;
1897 }
1898 }
1899
1900 /**
1901 * Generate a temporary folder.
1902 *
1903 * @param string $prefix
1904 * @return string
1905 */
1906 public function createTempDir($prefix = 'test-') {
1907 $tempDir = CRM_Utils_File::tempdir($prefix);
1908 $this->tempDirs[] = $tempDir;
1909 return $tempDir;
1910 }
1911
1912 public function cleanTempDirs() {
1913 if (!is_array($this->tempDirs)) {
1914 // fix test errors where this is not set
1915 return;
1916 }
1917 foreach ($this->tempDirs as $tempDir) {
1918 if (is_dir($tempDir)) {
1919 CRM_Utils_File::cleanDir($tempDir, TRUE, FALSE);
1920 }
1921 }
1922 }
1923
1924 /**
1925 * Temporarily replace the singleton extension with a different one.
1926 * @param \CRM_Extension_System $system
1927 */
1928 public function setExtensionSystem(CRM_Extension_System $system) {
1929 if ($this->origExtensionSystem == NULL) {
1930 $this->origExtensionSystem = CRM_Extension_System::singleton();
1931 }
1932 CRM_Extension_System::setSingleton($this->origExtensionSystem);
1933 }
1934
1935 public function unsetExtensionSystem() {
1936 if ($this->origExtensionSystem !== NULL) {
1937 CRM_Extension_System::setSingleton($this->origExtensionSystem);
1938 $this->origExtensionSystem = NULL;
1939 }
1940 }
1941
1942 /**
1943 * Temporarily alter the settings-metadata to add a mock setting.
1944 *
1945 * WARNING: The setting metadata will disappear on the next cache-clear.
1946 *
1947 * @param $extras
1948 * @return void
1949 */
1950 public function setMockSettingsMetaData($extras) {
1951 Civi::service('settings_manager')->flush();
1952
1953 CRM_Utils_Hook::singleton()
1954 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
1955 $metadata = array_merge($metadata, $extras);
1956 });
1957
1958 $fields = $this->callAPISuccess('setting', 'getfields', array());
1959 foreach ($extras as $key => $spec) {
1960 $this->assertNotEmpty($spec['title']);
1961 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
1962 }
1963 }
1964
1965 /**
1966 * @param string $name
1967 */
1968 public function financialAccountDelete($name) {
1969 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
1970 $financialAccount->name = $name;
1971 if ($financialAccount->find(TRUE)) {
1972 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
1973 $entityFinancialType->financial_account_id = $financialAccount->id;
1974 $entityFinancialType->delete();
1975 $financialAccount->delete();
1976 }
1977 }
1978
1979 /**
1980 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
1981 * (NB unclear if this is still required)
1982 */
1983 public function _sethtmlGlobals() {
1984 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
1985 'required' => array(
1986 'html_quickform_rule_required',
1987 'HTML/QuickForm/Rule/Required.php',
1988 ),
1989 'maxlength' => array(
1990 'html_quickform_rule_range',
1991 'HTML/QuickForm/Rule/Range.php',
1992 ),
1993 'minlength' => array(
1994 'html_quickform_rule_range',
1995 'HTML/QuickForm/Rule/Range.php',
1996 ),
1997 'rangelength' => array(
1998 'html_quickform_rule_range',
1999 'HTML/QuickForm/Rule/Range.php',
2000 ),
2001 'email' => array(
2002 'html_quickform_rule_email',
2003 'HTML/QuickForm/Rule/Email.php',
2004 ),
2005 'regex' => array(
2006 'html_quickform_rule_regex',
2007 'HTML/QuickForm/Rule/Regex.php',
2008 ),
2009 'lettersonly' => array(
2010 'html_quickform_rule_regex',
2011 'HTML/QuickForm/Rule/Regex.php',
2012 ),
2013 'alphanumeric' => array(
2014 'html_quickform_rule_regex',
2015 'HTML/QuickForm/Rule/Regex.php',
2016 ),
2017 'numeric' => array(
2018 'html_quickform_rule_regex',
2019 'HTML/QuickForm/Rule/Regex.php',
2020 ),
2021 'nopunctuation' => array(
2022 'html_quickform_rule_regex',
2023 'HTML/QuickForm/Rule/Regex.php',
2024 ),
2025 'nonzero' => array(
2026 'html_quickform_rule_regex',
2027 'HTML/QuickForm/Rule/Regex.php',
2028 ),
2029 'callback' => array(
2030 'html_quickform_rule_callback',
2031 'HTML/QuickForm/Rule/Callback.php',
2032 ),
2033 'compare' => array(
2034 'html_quickform_rule_compare',
2035 'HTML/QuickForm/Rule/Compare.php',
2036 ),
2037 );
2038 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2039 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2040 'group' => array(
2041 'HTML/QuickForm/group.php',
2042 'HTML_QuickForm_group',
2043 ),
2044 'hidden' => array(
2045 'HTML/QuickForm/hidden.php',
2046 'HTML_QuickForm_hidden',
2047 ),
2048 'reset' => array(
2049 'HTML/QuickForm/reset.php',
2050 'HTML_QuickForm_reset',
2051 ),
2052 'checkbox' => array(
2053 'HTML/QuickForm/checkbox.php',
2054 'HTML_QuickForm_checkbox',
2055 ),
2056 'file' => array(
2057 'HTML/QuickForm/file.php',
2058 'HTML_QuickForm_file',
2059 ),
2060 'image' => array(
2061 'HTML/QuickForm/image.php',
2062 'HTML_QuickForm_image',
2063 ),
2064 'password' => array(
2065 'HTML/QuickForm/password.php',
2066 'HTML_QuickForm_password',
2067 ),
2068 'radio' => array(
2069 'HTML/QuickForm/radio.php',
2070 'HTML_QuickForm_radio',
2071 ),
2072 'button' => array(
2073 'HTML/QuickForm/button.php',
2074 'HTML_QuickForm_button',
2075 ),
2076 'submit' => array(
2077 'HTML/QuickForm/submit.php',
2078 'HTML_QuickForm_submit',
2079 ),
2080 'select' => array(
2081 'HTML/QuickForm/select.php',
2082 'HTML_QuickForm_select',
2083 ),
2084 'hiddenselect' => array(
2085 'HTML/QuickForm/hiddenselect.php',
2086 'HTML_QuickForm_hiddenselect',
2087 ),
2088 'text' => array(
2089 'HTML/QuickForm/text.php',
2090 'HTML_QuickForm_text',
2091 ),
2092 'textarea' => array(
2093 'HTML/QuickForm/textarea.php',
2094 'HTML_QuickForm_textarea',
2095 ),
2096 'fckeditor' => array(
2097 'HTML/QuickForm/fckeditor.php',
2098 'HTML_QuickForm_FCKEditor',
2099 ),
2100 'tinymce' => array(
2101 'HTML/QuickForm/tinymce.php',
2102 'HTML_QuickForm_TinyMCE',
2103 ),
2104 'dojoeditor' => array(
2105 'HTML/QuickForm/dojoeditor.php',
2106 'HTML_QuickForm_dojoeditor',
2107 ),
2108 'link' => array(
2109 'HTML/QuickForm/link.php',
2110 'HTML_QuickForm_link',
2111 ),
2112 'advcheckbox' => array(
2113 'HTML/QuickForm/advcheckbox.php',
2114 'HTML_QuickForm_advcheckbox',
2115 ),
2116 'date' => array(
2117 'HTML/QuickForm/date.php',
2118 'HTML_QuickForm_date',
2119 ),
2120 'static' => array(
2121 'HTML/QuickForm/static.php',
2122 'HTML_QuickForm_static',
2123 ),
2124 'header' => array(
2125 'HTML/QuickForm/header.php',
2126 'HTML_QuickForm_header',
2127 ),
2128 'html' => array(
2129 'HTML/QuickForm/html.php',
2130 'HTML_QuickForm_html',
2131 ),
2132 'hierselect' => array(
2133 'HTML/QuickForm/hierselect.php',
2134 'HTML_QuickForm_hierselect',
2135 ),
2136 'autocomplete' => array(
2137 'HTML/QuickForm/autocomplete.php',
2138 'HTML_QuickForm_autocomplete',
2139 ),
2140 'xbutton' => array(
2141 'HTML/QuickForm/xbutton.php',
2142 'HTML_QuickForm_xbutton',
2143 ),
2144 'advmultiselect' => array(
2145 'HTML/QuickForm/advmultiselect.php',
2146 'HTML_QuickForm_advmultiselect',
2147 ),
2148 );
2149 }
2150
2151 /**
2152 * Set up an acl allowing contact to see 2 specified groups
2153 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2154 *
2155 * You need to have pre-created these groups & created the user e.g
2156 * $this->createLoggedInUser();
2157 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2158 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2159 *
2160 * @param bool $isProfile
2161 */
2162 public function setupACL($isProfile = FALSE) {
2163 global $_REQUEST;
2164 $_REQUEST = $this->_params;
2165
2166 CRM_Core_Config::singleton()->userPermissionClass->permissions = array('access CiviCRM');
2167 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2168 $ov = new CRM_Core_DAO_OptionValue();
2169 $ov->option_group_id = $optionGroupID;
2170 $ov->value = 55;
2171 if ($ov->find(TRUE)) {
2172 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_option_value WHERE id = {$ov->id}");
2173 }
2174 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2175 'option_group_id' => $optionGroupID,
2176 'label' => 'pick me',
2177 'value' => 55,
2178 ));
2179
2180 CRM_Core_DAO::executeQuery("
2181 TRUNCATE civicrm_acl_cache
2182 ");
2183
2184 CRM_Core_DAO::executeQuery("
2185 TRUNCATE civicrm_acl_contact_cache
2186 ");
2187
2188 CRM_Core_DAO::executeQuery("
2189 INSERT INTO civicrm_acl_entity_role (
2190 `acl_role_id`, `entity_table`, `entity_id`, `is_active`
2191 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup}, 1);
2192 ");
2193
2194 if ($isProfile) {
2195 CRM_Core_DAO::executeQuery("
2196 INSERT INTO civicrm_acl (
2197 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2198 )
2199 VALUES (
2200 'view picked', 'civicrm_acl_role', 55, 'Edit', 'civicrm_uf_group', 0, 1
2201 );
2202 ");
2203 }
2204 else {
2205 CRM_Core_DAO::executeQuery("
2206 INSERT INTO civicrm_acl (
2207 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2208 )
2209 VALUES (
2210 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2211 );
2212 ");
2213
2214 CRM_Core_DAO::executeQuery("
2215 INSERT INTO civicrm_acl (
2216 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2217 )
2218 VALUES (
2219 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2220 );
2221 ");
2222 }
2223
2224 $this->_loggedInUser = CRM_Core_Session::singleton()->get('userID');
2225 $this->callAPISuccess('group_contact', 'create', array(
2226 'group_id' => $this->_permissionedGroup,
2227 'contact_id' => $this->_loggedInUser,
2228 ));
2229
2230 if (!$isProfile) {
2231 //flush cache
2232 CRM_ACL_BAO_Cache::resetCache();
2233 CRM_ACL_API::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL);
2234 }
2235 }
2236
2237 /**
2238 * Alter default price set so that the field numbers are not all 1 (hiding errors)
2239 */
2240 public function offsetDefaultPriceSet() {
2241 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2242 $firstID = $contributionPriceSet['id'];
2243 $this->callAPISuccess('price_set', 'create', array(
2244 'id' => $contributionPriceSet['id'],
2245 'is_active' => 0,
2246 'name' => 'old',
2247 ));
2248 unset($contributionPriceSet['id']);
2249 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2250 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
2251 'price_set_id' => $firstID,
2252 'options' => array('limit' => 1),
2253 ));
2254 unset($priceField['id']);
2255 $priceField['price_set_id'] = $newPriceSet['id'];
2256 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2257 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
2258 'price_set_id' => $firstID,
2259 'sequential' => 1,
2260 'options' => array('limit' => 1),
2261 ));
2262
2263 unset($priceFieldValue['id']);
2264 //create some padding to use up ids
2265 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2266 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2267 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2268 }
2269
2270 /**
2271 * Create an instance of the paypal processor.
2272 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2273 * this parent class & we don't have a structure for that yet
2274 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2275 * & the best protection against that is the functions this class affords
2276 * @param array $params
2277 * @return int $result['id'] payment processor id
2278 */
2279 public function paymentProcessorCreate($params = array()) {
2280 $params = array_merge(array(
2281 'name' => 'demo',
2282 'domain_id' => CRM_Core_Config::domainID(),
2283 'payment_processor_type_id' => 'PayPal',
2284 'is_active' => 1,
2285 'is_default' => 0,
2286 'is_test' => 1,
2287 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2288 'password' => '1183377788',
2289 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2290 'url_site' => 'https://www.sandbox.paypal.com/',
2291 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2292 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2293 'class_name' => 'Payment_PayPalImpl',
2294 'billing_mode' => 3,
2295 'financial_type_id' => 1,
2296 'financial_account_id' => 12,
2297 // Credit card = 1 so can pass 'by accident'.
2298 'payment_instrument_id' => 'Debit Card',
2299 ), $params);
2300 if (!is_numeric($params['payment_processor_type_id'])) {
2301 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2302 //here
2303 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2304 'name' => $params['payment_processor_type_id'],
2305 'return' => 'id',
2306 ), 'integer');
2307 }
2308 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2309 return $result['id'];
2310 }
2311
2312 /**
2313 * Set up initial recurring payment allowing subsequent IPN payments.
2314 *
2315 * @param array $recurParams (Optional)
2316 * @param array $contributionParams (Optional)
2317 */
2318 public function setupRecurringPaymentProcessorTransaction($recurParams = [], $contributionParams = []) {
2319 $contributionParams = array_merge([
2320 'total_amount' => '200',
2321 'invoice_id' => $this->_invoiceID,
2322 'financial_type_id' => 'Donation',
2323 'contribution_status_id' => 'Pending',
2324 'contact_id' => $this->_contactID,
2325 'contribution_page_id' => $this->_contributionPageID,
2326 'payment_processor_id' => $this->_paymentProcessorID,
2327 'is_test' => 0,
2328 'skipCleanMoney' => TRUE,
2329 ], $contributionParams);
2330 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge(array(
2331 'contact_id' => $this->_contactID,
2332 'amount' => 1000,
2333 'sequential' => 1,
2334 'installments' => 5,
2335 'frequency_unit' => 'Month',
2336 'frequency_interval' => 1,
2337 'invoice_id' => $this->_invoiceID,
2338 'contribution_status_id' => 2,
2339 'payment_processor_id' => $this->_paymentProcessorID,
2340 // processor provided ID - use contact ID as proxy.
2341 'processor_id' => $this->_contactID,
2342 'api.contribution.create' => $contributionParams,
2343 ), $recurParams));
2344 $this->_contributionRecurID = $contributionRecur['id'];
2345 $this->_contributionID = $contributionRecur['values']['0']['api.contribution.create']['id'];
2346 }
2347
2348 /**
2349 * 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
2350 *
2351 * @param array $params Optionally modify params for membership/recur (duration_unit/frequency_unit)
2352 */
2353 public function setupMembershipRecurringPaymentProcessorTransaction($params = array()) {
2354 $membershipParams = $recurParams = array();
2355 if (!empty($params['duration_unit'])) {
2356 $membershipParams['duration_unit'] = $params['duration_unit'];
2357 }
2358 if (!empty($params['frequency_unit'])) {
2359 $recurParams['frequency_unit'] = $params['frequency_unit'];
2360 }
2361
2362 $this->ids['membership_type'] = $this->membershipTypeCreate($membershipParams);
2363 //create a contribution so our membership & contribution don't both have id = 1
2364 if ($this->callAPISuccess('Contribution', 'getcount', array()) == 0) {
2365 $this->contributionCreate(array(
2366 'contact_id' => $this->_contactID,
2367 'is_test' => 1,
2368 'financial_type_id' => 1,
2369 'invoice_id' => 'abcd',
2370 'trxn_id' => 345,
2371 ));
2372 }
2373 $this->setupRecurringPaymentProcessorTransaction($recurParams);
2374
2375 $this->ids['membership'] = $this->callAPISuccess('membership', 'create', array(
2376 'contact_id' => $this->_contactID,
2377 'membership_type_id' => $this->ids['membership_type'],
2378 'contribution_recur_id' => $this->_contributionRecurID,
2379 'format.only_id' => TRUE,
2380 ));
2381 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
2382 CRM_Core_DAO::executeQuery("TRUNCATE civicrm_line_item");
2383
2384 $this->callAPISuccess('line_item', 'create', array(
2385 'entity_table' => 'civicrm_membership',
2386 'entity_id' => $this->ids['membership'],
2387 'contribution_id' => $this->_contributionID,
2388 'label' => 'General',
2389 'qty' => 1,
2390 'unit_price' => 200,
2391 'line_total' => 200,
2392 'financial_type_id' => 1,
2393 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
2394 'return' => 'id',
2395 'label' => 'Membership Amount',
2396 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2397 )),
2398 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
2399 'return' => 'id',
2400 'label' => 'General',
2401 'options' => array('limit' => 1, 'sort' => 'id DESC'),
2402 )),
2403 ));
2404 $this->callAPISuccess('membership_payment', 'create', array(
2405 'contribution_id' => $this->_contributionID,
2406 'membership_id' => $this->ids['membership'],
2407 ));
2408 }
2409
2410 /**
2411 * @param $message
2412 *
2413 * @throws Exception
2414 */
2415 public function CiviUnitTestCase_fatalErrorHandler($message) {
2416 throw new Exception("{$message['message']}: {$message['code']}");
2417 }
2418
2419 /**
2420 * Wrap the entire test case in a transaction.
2421 *
2422 * Only subsequent DB statements will be wrapped in TX -- this cannot
2423 * retroactively wrap old DB statements. Therefore, it makes sense to
2424 * call this at the beginning of setUp().
2425 *
2426 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
2427 * this option does not work with, e.g., custom-data.
2428 *
2429 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
2430 * if TRUNCATE or ALTER is called while using a transaction.
2431 *
2432 * @param bool $nest
2433 * Whether to use nesting or reference-counting.
2434 */
2435 public function useTransaction($nest = TRUE) {
2436 if (!$this->tx) {
2437 $this->tx = new CRM_Core_Transaction($nest);
2438 $this->tx->rollback();
2439 }
2440 }
2441
2442 /**
2443 * Assert the attachment exists.
2444 *
2445 * @param bool $exists
2446 * @param array $apiResult
2447 */
2448 protected function assertAttachmentExistence($exists, $apiResult) {
2449 $fileId = $apiResult['id'];
2450 $this->assertTrue(is_numeric($fileId));
2451 $this->assertEquals($exists, file_exists($apiResult['values'][$fileId]['path']));
2452 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_file WHERE id = %1', array(
2453 1 => array($fileId, 'Int'),
2454 ));
2455 $this->assertDBQuery($exists ? 1 : 0, 'SELECT count(*) FROM civicrm_entity_file WHERE id = %1', array(
2456 1 => array($fileId, 'Int'),
2457 ));
2458 }
2459
2460 /**
2461 * Create a price set for an event.
2462 *
2463 * @param int $feeTotal
2464 * @param int $minAmt
2465 * @param string $type
2466 *
2467 * @return int
2468 * Price Set ID.
2469 */
2470 protected function eventPriceSetCreate($feeTotal, $minAmt = 0, $type = 'Text') {
2471 // creating price set, price field
2472 $paramsSet['title'] = 'Price Set';
2473 $paramsSet['name'] = CRM_Utils_String::titleToVar('Price Set');
2474 $paramsSet['is_active'] = FALSE;
2475 $paramsSet['extends'] = 1;
2476 $paramsSet['min_amount'] = $minAmt;
2477
2478 $priceSet = CRM_Price_BAO_PriceSet::create($paramsSet);
2479 $this->_ids['price_set'] = $priceSet->id;
2480
2481 $paramsField = array(
2482 'label' => 'Price Field',
2483 'name' => CRM_Utils_String::titleToVar('Price Field'),
2484 'html_type' => $type,
2485 'price' => $feeTotal,
2486 'option_label' => array('1' => 'Price Field'),
2487 'option_value' => array('1' => $feeTotal),
2488 'option_name' => array('1' => $feeTotal),
2489 'option_weight' => array('1' => 1),
2490 'option_amount' => array('1' => 1),
2491 'is_display_amounts' => 1,
2492 'weight' => 1,
2493 'options_per_line' => 1,
2494 'is_active' => array('1' => 1),
2495 'price_set_id' => $this->_ids['price_set'],
2496 'is_enter_qty' => 1,
2497 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2498 );
2499 if ($type === 'Radio') {
2500 $paramsField['is_enter_qty'] = 0;
2501 $paramsField['option_value'][2] = $paramsField['option_weight'][2] = $paramsField['option_amount'][2] = 100;
2502 $paramsField['option_label'][2] = $paramsField['option_name'][2] = 'hundy';
2503 }
2504 CRM_Price_BAO_PriceField::create($paramsField);
2505 $fields = $this->callAPISuccess('PriceField', 'get', array('price_set_id' => $this->_ids['price_set']));
2506 $this->_ids['price_field'] = array_keys($fields['values']);
2507 $fieldValues = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $this->_ids['price_field'][0]));
2508 $this->_ids['price_field_value'] = array_keys($fieldValues['values']);
2509
2510 return $this->_ids['price_set'];
2511 }
2512
2513 /**
2514 * Add a profile to a contribution page.
2515 *
2516 * @param string $name
2517 * @param int $contributionPageID
2518 * @param string $module
2519 */
2520 protected function addProfile($name, $contributionPageID, $module = 'CiviContribute') {
2521 $params = [
2522 'uf_group_id' => $name,
2523 'module' => $module,
2524 'entity_table' => 'civicrm_contribution_page',
2525 'entity_id' => $contributionPageID,
2526 'weight' => 1,
2527 ];
2528 if ($module !== 'CiviContribute') {
2529 $params['module_data'] = [$module => []];
2530 }
2531 $this->callAPISuccess('UFJoin', 'create', $params);
2532 }
2533
2534 /**
2535 * Add participant with contribution
2536 *
2537 * @return array
2538 */
2539 protected function createParticipantWithContribution() {
2540 // creating price set, price field
2541 $this->_contactId = $this->individualCreate();
2542 $event = $this->eventCreate();
2543 $this->_eventId = $event['id'];
2544 $eventParams = array(
2545 'id' => $this->_eventId,
2546 'financial_type_id' => 4,
2547 'is_monetary' => 1,
2548 );
2549 $this->callAPISuccess('event', 'create', $eventParams);
2550 $priceFields = $this->createPriceSet('event', $this->_eventId);
2551 $participantParams = array(
2552 'financial_type_id' => 4,
2553 'event_id' => $this->_eventId,
2554 'role_id' => 1,
2555 'status_id' => 14,
2556 'fee_currency' => 'USD',
2557 'contact_id' => $this->_contactId,
2558 );
2559 $participant = $this->callAPISuccess('Participant', 'create', $participantParams);
2560 $contributionParams = array(
2561 'total_amount' => 150,
2562 'currency' => 'USD',
2563 'contact_id' => $this->_contactId,
2564 'financial_type_id' => 4,
2565 'contribution_status_id' => 1,
2566 'partial_payment_total' => 300.00,
2567 'partial_amount_to_pay' => 150,
2568 'contribution_mode' => 'participant',
2569 'participant_id' => $participant['id'],
2570 );
2571 foreach ($priceFields['values'] as $key => $priceField) {
2572 $lineItems[1][$key] = array(
2573 'price_field_id' => $priceField['price_field_id'],
2574 'price_field_value_id' => $priceField['id'],
2575 'label' => $priceField['label'],
2576 'field_title' => $priceField['label'],
2577 'qty' => 1,
2578 'unit_price' => $priceField['amount'],
2579 'line_total' => $priceField['amount'],
2580 'financial_type_id' => $priceField['financial_type_id'],
2581 );
2582 }
2583 $contributionParams['line_item'] = $lineItems;
2584 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
2585 $paymentParticipant = array(
2586 'participant_id' => $participant['id'],
2587 'contribution_id' => $contribution['id'],
2588 );
2589 $this->callAPISuccess('ParticipantPayment', 'create', $paymentParticipant);
2590 return array($lineItems, $contribution);
2591 }
2592
2593 /**
2594 * Create price set
2595 *
2596 * @param string $component
2597 * @param int $componentId
2598 * @param array $priceFieldOptions
2599 *
2600 * @return array
2601 */
2602 protected function createPriceSet($component = 'contribution_page', $componentId = NULL, $priceFieldOptions = array()) {
2603 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 7);
2604 $paramsSet['name'] = CRM_Utils_String::titleToVar($paramsSet['title']);
2605 $paramsSet['is_active'] = TRUE;
2606 $paramsSet['financial_type_id'] = 'Event Fee';
2607 $paramsSet['extends'] = 1;
2608 $priceSet = $this->callAPISuccess('price_set', 'create', $paramsSet);
2609 $priceSetId = $priceSet['id'];
2610 //Checking for priceset added in the table.
2611 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
2612 'id', $paramsSet['title'], 'Check DB for created priceset'
2613 );
2614 $paramsField = array_merge(array(
2615 'label' => 'Price Field',
2616 'name' => CRM_Utils_String::titleToVar('Price Field'),
2617 'html_type' => 'CheckBox',
2618 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2619 'option_value' => array('1' => 100, '2' => 200),
2620 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
2621 'option_weight' => array('1' => 1, '2' => 2),
2622 'option_amount' => array('1' => 100, '2' => 200),
2623 'is_display_amounts' => 1,
2624 'weight' => 1,
2625 'options_per_line' => 1,
2626 'is_active' => array('1' => 1, '2' => 1),
2627 'price_set_id' => $priceSet['id'],
2628 'is_enter_qty' => 1,
2629 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
2630 ), $priceFieldOptions);
2631
2632 $priceField = CRM_Price_BAO_PriceField::create($paramsField);
2633 if ($componentId) {
2634 CRM_Price_BAO_PriceSet::addTo('civicrm_' . $component, $componentId, $priceSetId);
2635 }
2636 return $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id));
2637 }
2638
2639 /**
2640 * Replace the template with a test-oriented template designed to show all the variables.
2641 *
2642 * @param string $templateName
2643 */
2644 protected function swapMessageTemplateForTestTemplate($templateName = 'contribution_online_receipt') {
2645 $testTemplate = file_get_contents(__DIR__ . '/../../templates/message_templates/' . $templateName . '_html.tpl');
2646 CRM_Core_DAO::executeQuery(
2647 "UPDATE civicrm_option_group og
2648 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2649 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2650 SET m.msg_html = '{$testTemplate}'
2651 WHERE og.name = 'msg_tpl_workflow_contribution'
2652 AND ov.name = '{$templateName}'
2653 AND m.is_default = 1"
2654 );
2655 }
2656
2657 /**
2658 * Reinstate the default template.
2659 *
2660 * @param string $templateName
2661 */
2662 protected function revertTemplateToReservedTemplate($templateName = 'contribution_online_receipt') {
2663 CRM_Core_DAO::executeQuery(
2664 "UPDATE civicrm_option_group og
2665 LEFT JOIN civicrm_option_value ov ON ov.option_group_id = og.id
2666 LEFT JOIN civicrm_msg_template m ON m.workflow_id = ov.id
2667 LEFT JOIN civicrm_msg_template m2 ON m2.workflow_id = ov.id AND m2.is_reserved = 1
2668 SET m.msg_html = m2.msg_html
2669 WHERE og.name = 'msg_tpl_workflow_contribution'
2670 AND ov.name = '{$templateName}'
2671 AND m.is_default = 1"
2672 );
2673 }
2674
2675 /**
2676 * Flush statics relating to financial type.
2677 */
2678 protected function flushFinancialTypeStatics() {
2679 if (isset(\Civi::$statics['CRM_Financial_BAO_FinancialType'])) {
2680 unset(\Civi::$statics['CRM_Financial_BAO_FinancialType']);
2681 }
2682 if (isset(\Civi::$statics['CRM_Contribute_PseudoConstant'])) {
2683 unset(\Civi::$statics['CRM_Contribute_PseudoConstant']);
2684 }
2685 CRM_Contribute_PseudoConstant::flush('financialType');
2686 CRM_Contribute_PseudoConstant::flush('membershipType');
2687 // Pseudoconstants may be saved to the cache table.
2688 CRM_Core_DAO::executeQuery("TRUNCATE civicrm_cache");
2689 CRM_Financial_BAO_FinancialType::$_statusACLFt = array();
2690 CRM_Financial_BAO_FinancialType::$_availableFinancialTypes = NULL;
2691 }
2692
2693 /**
2694 * Set the permissions to the supplied array.
2695 *
2696 * @param array $permissions
2697 */
2698 protected function setPermissions($permissions) {
2699 CRM_Core_Config::singleton()->userPermissionClass->permissions = $permissions;
2700 $this->flushFinancialTypeStatics();
2701 }
2702
2703 /**
2704 * @param array $params
2705 * @param $context
2706 */
2707 public function _checkFinancialRecords($params, $context) {
2708 $entityParams = array(
2709 'entity_id' => $params['id'],
2710 'entity_table' => 'civicrm_contribution',
2711 );
2712 $contribution = $this->callAPISuccess('contribution', 'getsingle', array('id' => $params['id']));
2713 $this->assertEquals($contribution['total_amount'] - $contribution['fee_amount'], $contribution['net_amount']);
2714 if ($context == 'pending') {
2715 $trxn = CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams);
2716 $this->assertNull($trxn, 'No Trxn to be created until IPN callback');
2717 return;
2718 }
2719 $trxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
2720 $trxnParams = array(
2721 'id' => $trxn['financial_trxn_id'],
2722 );
2723 if ($context != 'online' && $context != 'payLater') {
2724 $compareParams = array(
2725 'to_financial_account_id' => 6,
2726 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
2727 'status_id' => 1,
2728 );
2729 }
2730 if ($context == 'feeAmount') {
2731 $compareParams['fee_amount'] = 50;
2732 }
2733 elseif ($context == 'online') {
2734 $compareParams = array(
2735 'to_financial_account_id' => 12,
2736 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
2737 'status_id' => 1,
2738 'payment_instrument_id' => CRM_Utils_Array::value('payment_instrument_id', $params, 1),
2739 );
2740 }
2741 elseif ($context == 'payLater') {
2742 $compareParams = array(
2743 'to_financial_account_id' => 7,
2744 'total_amount' => CRM_Utils_Array::value('total_amount', $params, 100),
2745 'status_id' => 2,
2746 );
2747 }
2748 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2749 $entityParams = array(
2750 'financial_trxn_id' => $trxn['financial_trxn_id'],
2751 'entity_table' => 'civicrm_financial_item',
2752 );
2753 $entityTrxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
2754 $fitemParams = array(
2755 'id' => $entityTrxn['entity_id'],
2756 );
2757 $compareParams = array(
2758 'amount' => CRM_Utils_Array::value('total_amount', $params, 100),
2759 'status_id' => 1,
2760 'financial_account_id' => CRM_Utils_Array::value('financial_account_id', $params, 1),
2761 );
2762 if ($context == 'payLater') {
2763 $compareParams = array(
2764 'amount' => CRM_Utils_Array::value('total_amount', $params, 100),
2765 'status_id' => 3,
2766 'financial_account_id' => CRM_Utils_Array::value('financial_account_id', $params, 1),
2767 );
2768 }
2769 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2770 if ($context == 'feeAmount') {
2771 $maxParams = array(
2772 'entity_id' => $params['id'],
2773 'entity_table' => 'civicrm_contribution',
2774 );
2775 $maxTrxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($maxParams, TRUE));
2776 $trxnParams = array(
2777 'id' => $maxTrxn['financial_trxn_id'],
2778 );
2779 $compareParams = array(
2780 'to_financial_account_id' => 5,
2781 'from_financial_account_id' => 6,
2782 'total_amount' => 50,
2783 'status_id' => 1,
2784 );
2785 $trxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['id'], 'DESC');
2786 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams, $compareParams);
2787 $fitemParams = array(
2788 'entity_id' => $trxnId['financialTrxnId'],
2789 'entity_table' => 'civicrm_financial_trxn',
2790 );
2791 $compareParams = array(
2792 'amount' => 50,
2793 'status_id' => 1,
2794 'financial_account_id' => 5,
2795 );
2796 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $fitemParams, $compareParams);
2797 }
2798 // This checks that empty Sales tax rows are not being created. If for any reason it needs to be removed the
2799 // line should be copied into all the functions that call this function & evaluated there
2800 // Be really careful not to remove or bypass this without ensuring stray rows do not re-appear
2801 // when calling completeTransaction or repeatTransaction.
2802 $this->callAPISuccessGetCount('FinancialItem', array('description' => 'Sales Tax', 'amount' => 0), 0);
2803 }
2804
2805 /**
2806 * Return financial type id on basis of name
2807 *
2808 * @param string $name Financial type m/c name
2809 *
2810 * @return int
2811 */
2812 public function getFinancialTypeId($name) {
2813 return CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $name, 'id', 'name');
2814 }
2815
2816 /**
2817 * Cleanup function for contents of $this->ids.
2818 *
2819 * This is a best effort cleanup to use in tear downs etc.
2820 *
2821 * It will not fail if the data has already been removed (some tests may do
2822 * their own cleanup).
2823 */
2824 protected function cleanUpSetUpIDs() {
2825 foreach ($this->setupIDs as $entity => $id) {
2826 try {
2827 civicrm_api3($entity, 'delete', array('id' => $id, 'skip_undelete' => 1));
2828 }
2829 catch (CiviCRM_API3_Exception $e) {
2830 // This is a best-effort cleanup function, ignore.
2831 }
2832 }
2833 }
2834
2835 /**
2836 * Create Financial Type.
2837 *
2838 * @param array $params
2839 *
2840 * @return array
2841 */
2842 protected function createFinancialType($params = array()) {
2843 $params = array_merge($params,
2844 array(
2845 'name' => 'Financial-Type -' . substr(sha1(rand()), 0, 7),
2846 'is_active' => 1,
2847 )
2848 );
2849 return $this->callAPISuccess('FinancialType', 'create', $params);
2850 }
2851
2852 /**
2853 * Create Payment Instrument.
2854 *
2855 * @param array $params
2856 * @param string $financialAccountName
2857 *
2858 * @return int
2859 */
2860 protected function createPaymentInstrument($params = array(), $financialAccountName = 'Donation') {
2861 $params = array_merge(array(
2862 'label' => 'Payment Instrument -' . substr(sha1(rand()), 0, 7),
2863 'option_group_id' => 'payment_instrument',
2864 'is_active' => 1,
2865 ), $params);
2866 $newPaymentInstrument = $this->callAPISuccess('OptionValue', 'create', $params)['id'];
2867
2868 $relationTypeID = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
2869
2870 $financialAccountParams = [
2871 'entity_table' => 'civicrm_option_value',
2872 'entity_id' => $newPaymentInstrument,
2873 'account_relationship' => $relationTypeID,
2874 'financial_account_id' => $this->callAPISuccess('FinancialAccount', 'getValue', ['name' => $financialAccountName, 'return' => 'id']),
2875 ];
2876 CRM_Financial_BAO_FinancialTypeAccount::add($financialAccountParams);
2877
2878 return CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $params['label']);
2879 }
2880
2881 /**
2882 * Enable Tax and Invoicing
2883 */
2884 protected function enableTaxAndInvoicing($params = array()) {
2885 // Enable component contribute setting
2886 $contributeSetting = array_merge($params,
2887 array(
2888 'invoicing' => 1,
2889 'invoice_prefix' => 'INV_',
2890 'credit_notes_prefix' => 'CN_',
2891 'due_date' => 10,
2892 'due_date_period' => 'days',
2893 'notes' => '',
2894 'is_email_pdf' => 1,
2895 'tax_term' => 'Sales Tax',
2896 'tax_display_settings' => 'Inclusive',
2897 )
2898 );
2899 return Civi::settings()->set('contribution_invoice_settings', $contributeSetting);
2900 }
2901
2902 /**
2903 * Enable Tax and Invoicing
2904 */
2905 protected function disableTaxAndInvoicing($params = array()) {
2906 if (!empty(\Civi::$statics['CRM_Core_PseudoConstant']) && isset(\Civi::$statics['CRM_Core_PseudoConstant']['taxRates'])) {
2907 unset(\Civi::$statics['CRM_Core_PseudoConstant']['taxRates']);
2908 }
2909 // Enable component contribute setting
2910 $contributeSetting = array_merge($params,
2911 array(
2912 'invoicing' => 0,
2913 )
2914 );
2915 return Civi::settings()->set('contribution_invoice_settings', $contributeSetting);
2916 }
2917
2918 /**
2919 * Add Sales Tax relation for financial type with financial account.
2920 *
2921 * @param int $financialTypeId
2922 *
2923 * @return obj
2924 */
2925 protected function relationForFinancialTypeWithFinancialAccount($financialTypeId) {
2926 $params = array(
2927 'name' => 'Sales tax account ' . substr(sha1(rand()), 0, 4),
2928 'financial_account_type_id' => key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Liability' ")),
2929 'is_deductible' => 1,
2930 'is_tax' => 1,
2931 'tax_rate' => 10,
2932 'is_active' => 1,
2933 );
2934 $account = CRM_Financial_BAO_FinancialAccount::add($params);
2935 $entityParams = array(
2936 'entity_table' => 'civicrm_financial_type',
2937 'entity_id' => $financialTypeId,
2938 'account_relationship' => key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")),
2939 );
2940
2941 // set tax rate (as 10) for provided financial type ID to static variable, later used to fetch tax rates of all financial types
2942 \Civi::$statics['CRM_Core_PseudoConstant']['taxRates'][$financialTypeId] = 10;
2943
2944 //CRM-20313: As per unique index added in civicrm_entity_financial_account table,
2945 // first check if there's any record on basis of unique key (entity_table, account_relationship, entity_id)
2946 $dao = new CRM_Financial_DAO_EntityFinancialAccount();
2947 $dao->copyValues($entityParams);
2948 $dao->find();
2949 if ($dao->fetch()) {
2950 $entityParams['id'] = $dao->id;
2951 }
2952 $entityParams['financial_account_id'] = $account->id;
2953
2954 return CRM_Financial_BAO_FinancialTypeAccount::add($entityParams);
2955 }
2956
2957 /**
2958 * Create price set with contribution test for test setup.
2959 *
2960 * This could be merged with 4.5 function setup in api_v3_ContributionPageTest::setUpContributionPage
2961 * on parent class at some point (fn is not in 4.4).
2962 *
2963 * @param $entity
2964 * @param array $params
2965 */
2966 public function createPriceSetWithPage($entity = NULL, $params = array()) {
2967 $membershipTypeID = $this->membershipTypeCreate(array('name' => 'Special'));
2968 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', array(
2969 'title' => "Test Contribution Page",
2970 'financial_type_id' => 1,
2971 'currency' => 'NZD',
2972 'goal_amount' => 50,
2973 'is_pay_later' => 1,
2974 'is_monetary' => TRUE,
2975 'is_email_receipt' => FALSE,
2976 ));
2977 $priceSet = $this->callAPISuccess('price_set', 'create', array(
2978 'is_quick_config' => 0,
2979 'extends' => 'CiviMember',
2980 'financial_type_id' => 1,
2981 'title' => 'my Page',
2982 ));
2983 $priceSetID = $priceSet['id'];
2984
2985 CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
2986 $priceField = $this->callAPISuccess('price_field', 'create', array(
2987 'price_set_id' => $priceSetID,
2988 'label' => 'Goat Breed',
2989 'html_type' => 'Radio',
2990 ));
2991 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
2992 'price_set_id' => $priceSetID,
2993 'price_field_id' => $priceField['id'],
2994 'label' => 'Long Haired Goat',
2995 'amount' => 20,
2996 'financial_type_id' => 'Donation',
2997 'membership_type_id' => $membershipTypeID,
2998 'membership_num_terms' => 1,
2999 ));
3000 $this->_ids['price_field_value'] = array($priceFieldValue['id']);
3001 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3002 'price_set_id' => $priceSetID,
3003 'price_field_id' => $priceField['id'],
3004 'label' => 'Shoe-eating Goat',
3005 'amount' => 10,
3006 'financial_type_id' => 'Donation',
3007 'membership_type_id' => $membershipTypeID,
3008 'membership_num_terms' => 2,
3009 ));
3010 $this->_ids['price_field_value'][] = $priceFieldValue['id'];
3011
3012 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', array(
3013 'price_set_id' => $priceSetID,
3014 'price_field_id' => $priceField['id'],
3015 'label' => 'Shoe-eating Goat',
3016 'amount' => 10,
3017 'financial_type_id' => 'Donation',
3018 ));
3019 $this->_ids['price_field_value']['cont'] = $priceFieldValue['id'];
3020
3021 $this->_ids['price_set'] = $priceSetID;
3022 $this->_ids['contribution_page'] = $contributionPageResult['id'];
3023 $this->_ids['price_field'] = array($priceField['id']);
3024
3025 $this->_ids['membership_type'] = $membershipTypeID;
3026 }
3027
3028 /**
3029 * Only specified contact returned.
3030 * @implements CRM_Utils_Hook::aclWhereClause
3031 * @param $type
3032 * @param $tables
3033 * @param $whereTables
3034 * @param $contactID
3035 * @param $where
3036 */
3037 public function aclWhereMultipleContacts($type, &$tables, &$whereTables, &$contactID, &$where) {
3038 $where = " contact_a.id IN (" . implode(', ', $this->allowedContacts) . ")";
3039 }
3040
3041 /**
3042 * @implements CRM_Utils_Hook::selectWhereClause
3043 *
3044 * @param string $entity
3045 * @param array $clauses
3046 */
3047 public function selectWhereClauseHook($entity, &$clauses) {
3048 if ($entity == 'Event') {
3049 $clauses['event_type_id'][] = "IN (2, 3, 4)";
3050 }
3051 }
3052
3053 /**
3054 * An implementation of hook_civicrm_post used with all our test cases.
3055 *
3056 * @param $op
3057 * @param string $objectName
3058 * @param int $objectId
3059 * @param $objectRef
3060 */
3061 public function onPost($op, $objectName, $objectId, &$objectRef) {
3062 if ($op == 'create' && $objectName == 'Individual') {
3063 CRM_Core_DAO::executeQuery(
3064 "UPDATE civicrm_contact SET nick_name = 'munged' WHERE id = %1",
3065 array(
3066 1 => array($objectId, 'Integer'),
3067 )
3068 );
3069 }
3070
3071 if ($op == 'edit' && $objectName == 'Participant') {
3072 $params = array(
3073 1 => array($objectId, 'Integer'),
3074 );
3075 $query = "UPDATE civicrm_participant SET source = 'Post Hook Update' WHERE id = %1";
3076 CRM_Core_DAO::executeQuery($query, $params);
3077 }
3078 }
3079
3080 /**
3081 * Instantiate form object.
3082 *
3083 * We need to instantiate the form to run preprocess, which means we have to trick it about the request method.
3084 *
3085 * @param string $class
3086 * Name of form class.
3087 *
3088 * @return \CRM_Core_Form
3089 */
3090 public function getFormObject($class) {
3091 $form = new $class();
3092 $_SERVER['REQUEST_METHOD'] = 'GET';
3093 $form->controller = new CRM_Core_Controller();
3094 return $form;
3095 }
3096
3097 /**
3098 * Get possible thousand separators.
3099 *
3100 * @return array
3101 */
3102 public function getThousandSeparators() {
3103 return array(array('.'), array(','));
3104 }
3105
3106 /**
3107 * Set the separators for thousands and decimal points.
3108 *
3109 * @param string $thousandSeparator
3110 */
3111 protected function setCurrencySeparators($thousandSeparator) {
3112 Civi::settings()->set('monetaryThousandSeparator', $thousandSeparator);
3113 Civi::settings()
3114 ->set('monetaryDecimalPoint', ($thousandSeparator === ',' ? '.' : ','));
3115 }
3116
3117 /**
3118 * Format money as it would be input.
3119 *
3120 * @param string $amount
3121 *
3122 * @return string
3123 */
3124 protected function formatMoneyInput($amount) {
3125 return CRM_Utils_Money::format($amount, NULL, '%a');
3126 }
3127
3128 /**
3129 * Get the contribution object.
3130 *
3131 * @param int $contributionID
3132 *
3133 * @return \CRM_Contribute_BAO_Contribution
3134 */
3135 protected function getContributionObject($contributionID) {
3136 $contributionObj = new CRM_Contribute_BAO_Contribution();
3137 $contributionObj->id = $contributionID;
3138 $contributionObj->find(TRUE);
3139 return $contributionObj;
3140 }
3141
3142 /**
3143 * Enable multilingual.
3144 */
3145 public function enableMultilingual() {
3146 $this->callAPISuccess('Setting', 'create', array(
3147 'lcMessages' => 'en_US',
3148 'languageLimit' => array(
3149 'en_US' => 1,
3150 ),
3151 ));
3152
3153 CRM_Core_I18n_Schema::makeMultilingual('en_US');
3154
3155 global $dbLocale;
3156 $dbLocale = '_en_US';
3157 }
3158
3159 }