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