Merge pull request #13833 from civicrm/5.12
[civicrm-core.git] / CRM / Financial / BAO / FinancialType.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
006389de 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035 32 */
6a488035
TO
33class CRM_Financial_BAO_FinancialType extends CRM_Financial_DAO_FinancialType {
34
7f2b2c0d 35 /**
58c3bf5f 36 * Static cache holder of available financial types for this session
7f2b2c0d 37 */
58c3bf5f 38 static $_availableFinancialTypes = array();
5c4bbd48
PN
39 /**
40 * Static cache holder of status of ACL-FT enabled/disabled for this session
41 */
42 static $_statusACLFt = array();
6a488035
TO
43
44 /**
fe482240 45 * Class constructor.
6a488035 46 */
045f52a3 47 public function __construct() {
481a74f4 48 parent::__construct();
6a488035
TO
49 }
50
51 /**
fe482240 52 * Fetch object based on array of properties.
6a488035 53 *
ed5dd492
TO
54 * @param array $params
55 * (reference ) an assoc array of name/value pairs.
56 * @param array $defaults
57 * (reference ) an assoc array to hold the flattened values.
6a488035 58 *
de22d771 59 * @return CRM_Financial_DAO_FinancialType
6a488035 60 */
045f52a3 61 public static function retrieve(&$params, &$defaults) {
481a74f4
TO
62 $financialType = new CRM_Financial_DAO_FinancialType();
63 $financialType->copyValues($params);
045f52a3 64 if ($financialType->find(TRUE)) {
481a74f4 65 CRM_Core_DAO::storeValues($financialType, $defaults);
6a488035
TO
66 return $financialType;
67 }
045f52a3 68 return NULL;
6a488035
TO
69 }
70
71 /**
fe482240 72 * Update the is_active flag in the db.
6a488035 73 *
ed5dd492
TO
74 * @param int $id
75 * Id of the database record.
76 * @param bool $is_active
77 * Value we want to set the is_active field.
6a488035 78 *
de22d771 79 * @return bool
6a488035 80 */
045f52a3 81 public static function setIsActive($id, $is_active) {
481a74f4 82 return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_FinancialType', $id, 'is_active', $is_active);
6a488035
TO
83 }
84
85 /**
fe482240 86 * Add the financial types.
6a488035 87 *
ed5dd492
TO
88 * @param array $params
89 * Reference array contains the values submitted by the form.
90 * @param array $ids
91 * Reference array contains the id.
6a488035 92 *
6a488035
TO
93 * @return object
94 */
00be9182 95 public static function add(&$params, &$ids = array()) {
22e263ad 96 if (empty($params['id'])) {
045f52a3
TO
97 $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
98 $params['is_deductible'] = CRM_Utils_Array::value('is_deductible', $params, FALSE);
99 $params['is_reserved'] = CRM_Utils_Array::value('is_reserved', $params, FALSE);
bc2bc079 100 }
6a488035
TO
101
102 // action is taken depending upon the mode
ddaa8ef1
PN
103 $financialType = new CRM_Financial_DAO_FinancialType();
104 $financialType->copyValues($params);
a7488080 105 if (!empty($ids['financialType'])) {
6a488035 106 $financialType->id = CRM_Utils_Array::value('financialType', $ids);
7fc5cde0
E
107 if (self::isACLFinancialTypeStatus()) {
108 $prevName = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $financialType->id, 'name');
109 if ($prevName != $params['name']) {
16118599
E
110 CRM_Core_Session::setStatus(ts("Changing the name of a Financial Type will result in losing the current permissions associated with that Financial Type.
111 Before making this change you should likely note the existing permissions at Administer > Users and Permissions > Permissions (Access Control),
112 then clicking the Access Control link for your Content Management System, then noting down the permissions for 'CiviCRM: {financial type name} view', etc.
7fc5cde0
E
113 Then after making the change of name, reset the permissions to the way they were."), ts('Warning'), 'warning');
114 }
115 }
6a488035 116 }
ddaa8ef1
PN
117 $financialType->save();
118 // CRM-12470
bc2bc079 119 if (empty($ids['financialType']) && empty($params['id'])) {
ddaa8ef1
PN
120 $titles = CRM_Financial_BAO_FinancialTypeAccount::createDefaultFinancialAccounts($financialType);
121 $financialType->titles = $titles;
122 }
6a488035
TO
123 return $financialType;
124 }
125
126 /**
fe482240 127 * Delete financial Types.
6a488035 128 *
c490a46a 129 * @param int $financialTypeId
77b97be7
EM
130 *
131 * @return array|bool
6a488035 132 */
00be9182 133 public static function del($financialTypeId) {
481a74f4 134 $financialType = new CRM_Financial_DAO_FinancialType();
71e5aa5c 135 $financialType->id = $financialTypeId;
045f52a3 136 $financialType->find(TRUE);
de22d771 137 // tables to ignore checks for financial_type_id
cf1d2db7 138 $ignoreTables = array('CRM_Financial_DAO_EntityFinancialAccount');
8ef12e64 139
cded2ebf 140 // TODO: if (!$financialType->find(true)) {
6a488035 141
71e5aa5c
ARW
142 // ensure that we have no objects that have an FK to this financial type id TODO: that cannot be null
143 $occurrences = $financialType->findReferences();
144 if ($occurrences) {
145 $tables = array();
b44e3f84
DS
146 foreach ($occurrences as $occurrence) {
147 $className = get_class($occurrence);
3611044f 148 if (!in_array($className, $tables) && !in_array($className, $ignoreTables)) {
045f52a3 149 $tables[] = $className;
cf1d2db7 150 }
71e5aa5c 151 }
cf1d2db7
PN
152 if (!empty($tables)) {
153 $message = ts('The following tables have an entry for this financial type: %1', array('%1' => implode(', ', $tables)));
6a488035 154
cf1d2db7
PN
155 $errors = array();
156 $errors['is_error'] = 1;
157 $errors['error_message'] = $message;
158 return $errors;
159 }
6a488035
TO
160 }
161
cded2ebf 162 // delete from financial Type table
6a488035
TO
163 $financialType->delete();
164
481a74f4 165 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
6a488035
TO
166 $entityFinancialType->entity_id = $financialTypeId;
167 $entityFinancialType->entity_table = 'civicrm_financial_type';
71e5aa5c 168 $entityFinancialType->delete();
6a488035
TO
169 return FALSE;
170 }
8ef12e64 171
6a488035 172 /**
fe482240 173 * fetch financial type having relationship as Income Account is.
6a488035
TO
174 *
175 *
a6c01b45
CW
176 * @return array
177 * all financial type with income account is relationship
6a488035 178 */
00be9182 179 public static function getIncomeFinancialType() {
6a488035
TO
180 // Financial Type
181 $financialType = CRM_Contribute_PseudoConstant::financialType();
182 $revenueFinancialType = array();
f743a6eb 183 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
8ef12e64 184 CRM_Core_PseudoConstant::populate(
6a488035
TO
185 $revenueFinancialType,
186 'CRM_Financial_DAO_EntityFinancialAccount',
045f52a3 187 $all = TRUE,
8ef12e64 188 $retrieve = 'entity_id',
045f52a3 189 $filter = NULL,
8ef12e64 190 "account_relationship = $relationTypeId AND entity_table = 'civicrm_financial_type' "
6a488035 191 );
8ef12e64 192
6a488035 193 foreach ($financialType as $key => $financialTypeName) {
8173dae3 194 if (!in_array($key, $revenueFinancialType)
4323dc6c
PN
195 || (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
196 && !CRM_Core_Permission::check('add contributions of type ' . $financialTypeName))
197 ) {
6a488035 198 unset($financialType[$key]);
a8b59c2c 199 }
6a488035
TO
200 }
201 return $financialType;
202 }
96025800 203
4aed5ac0 204 /**
ad37ac8e 205 * Add permissions for financial types.
4aed5ac0 206 *
8173dae3 207 * @param array $permissions
ad37ac8e 208 * @param array $descriptions
209 *
210 * @return bool
4aed5ac0 211 */
cb2f7dd1 212 public static function permissionedFinancialTypes(&$permissions, $descriptions) {
2435064f 213 if (!self::isACLFinancialTypeStatus()) {
92420262 214 return FALSE;
2435064f 215 }
4aed5ac0
E
216 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
217 $prefix = ts('CiviCRM') . ': ';
cb2f7dd1 218 $actions = array('add', 'view', 'edit', 'delete');
4aed5ac0 219 foreach ($financialTypes as $id => $type) {
cb2f7dd1
PN
220 foreach ($actions as $action) {
221 if ($descriptions) {
222 $permissions[$action . ' contributions of type ' . $type] = array(
223 $prefix . ts($action . ' contributions of type ') . $type,
224 ts(ucfirst($action) . ' contributions of type ') . $type,
225 );
226 }
227 else {
228 $permissions[$action . ' contributions of type ' . $type] = $prefix . ts($action . ' contributions of type ') . $type;
229 }
230 }
231 }
232 if (!$descriptions) {
233 $permissions['administer CiviCRM Financial Types'] = $prefix . ts('administer CiviCRM Financial Types');
234 }
235 else {
236 $permissions['administer CiviCRM Financial Types'] = array(
237 $prefix . ts('administer CiviCRM Financial Types'),
238 ts('Administer access to Financial Types'),
92420262 239 );
4aed5ac0 240 }
4aed5ac0 241 }
bb08e888 242
d73f286e 243 /**
160a7ef5 244 * Wrapper aroung getAvailableFinancialTypes to get all including disabled FinancialTypes
d73f286e
SL
245 * @param int|string $action
246 * the type of action, can be add, view, edit, delete
247 * @param bool $resetCache
248 * load values from static cache
249 *
250 * @return array
251 */
354355bc 252 public static function getAllAvailableFinancialTypes($action = CRM_Core_Action::VIEW, $resetCache = FALSE) {
d73f286e
SL
253 // Flush pseudoconstant cache
254 CRM_Contribute_PseudoConstant::flush('financialType');
354355bc
SL
255 $thisIsAUselessVariableButSolvesPHPError = NULL;
256 $financialTypes = self::getAvailableFinancialTypes($thisIsAUselessVariableButSolvesPHPError, $action, $resetCache, TRUE);
257 return $financialTypes;
d73f286e
SL
258 }
259
260 /**
160a7ef5 261 * Wrapper aroung getAvailableFinancialTypes to get all FinancialTypes Excluding Disabled ones.
d73f286e
SL
262 * @param int|string $action
263 * the type of action, can be add, view, edit, delete
264 * @param bool $resetCache
265 * load values from static cache
266 *
267 * @return array
268 */
354355bc
SL
269 public static function getAllEnabledAvailableFinancialTypes($action = CRM_Core_Action::VIEW, $resetCache = FALSE) {
270 $thisIsAUselessVariableButSolvesPHPError = NULL;
271 $financialTypes = self::getAvailableFinancialTypes($thisIsAUselessVariableButSolvesPHPError, $action, $resetCache);
272 return $financialTypes;
d73f286e
SL
273 }
274
85b3d95d
E
275 /**
276 * Get available Financial Types.
277 *
278 * @param array $financialTypes
279 * (reference ) an array of financial types
ad37ac8e 280 * @param int|string $action
85b3d95d
E
281 * the type of action, can be add, view, edit, delete
282 * @param bool $resetCache
283 * load values from static cache
d73f286e
SL
284 * @param bool $includeDisabled
285 * Whether we should load in disabled FinancialTypes or Not
85b3d95d
E
286 *
287 * @return array
288 */
d73f286e 289 public static function getAvailableFinancialTypes(&$financialTypes = NULL, $action = CRM_Core_Action::VIEW, $resetCache = FALSE, $includeDisabled = FALSE) {
84e489b7 290 if (empty($financialTypes)) {
d73f286e 291 $financialTypes = CRM_Contribute_PseudoConstant::financialType(NULL, $includeDisabled);
84e489b7 292 }
2435064f
PN
293 if (!self::isACLFinancialTypeStatus()) {
294 return $financialTypes;
dec56960 295 }
573fd305
PN
296 $actions = array(
297 CRM_Core_Action::VIEW => 'view',
298 CRM_Core_Action::UPDATE => 'edit',
299 CRM_Core_Action::ADD => 'add',
300 CRM_Core_Action::DELETE => 'delete',
301 );
dbaa9d7d 302
303 if (!isset(\Civi::$statics[__CLASS__]['available_types_' . $action])) {
304 foreach ($financialTypes as $finTypeId => $type) {
305 if (!CRM_Core_Permission::check($actions[$action] . ' contributions of type ' . $type)) {
306 unset($financialTypes[$finTypeId]);
307 }
bb08e888 308 }
dbaa9d7d 309 \Civi::$statics[__CLASS__]['available_types_' . $action] = $financialTypes;
bb08e888 310 }
dbaa9d7d 311 $financialTypes = \Civi::$statics[__CLASS__]['available_types_' . $action];
312 return \Civi::$statics[__CLASS__]['available_types_' . $action];
bb08e888 313 }
dec56960 314
85b3d95d
E
315 /**
316 * Get available Membership Types.
317 *
318 * @param array $membershipTypes
319 * (reference ) an array of membership types
ad37ac8e 320 * @param int|string $action
85b3d95d
E
321 * the type of action, can be add, view, edit, delete
322 *
323 * @return array
324 */
573fd305 325 public static function getAvailableMembershipTypes(&$membershipTypes = NULL, $action = CRM_Core_Action::VIEW) {
27e7373d
E
326 if (empty($membershipTypes)) {
327 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
328 }
2435064f
PN
329 if (!self::isACLFinancialTypeStatus()) {
330 return $membershipTypes;
331 }
573fd305
PN
332 $actions = array(
333 CRM_Core_Action::VIEW => 'view',
334 CRM_Core_Action::UPDATE => 'edit',
335 CRM_Core_Action::ADD => 'add',
336 CRM_Core_Action::DELETE => 'delete',
337 );
27e7373d
E
338 foreach ($membershipTypes as $memTypeId => $type) {
339 $finTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memTypeId, 'financial_type_id');
340 $finType = CRM_Contribute_PseudoConstant::financialType($finTypeId);
573fd305 341 if (!CRM_Core_Permission::check($actions[$action] . ' contributions of type ' . $finType)) {
27e7373d
E
342 unset($membershipTypes[$memTypeId]);
343 }
344 }
345 return $membershipTypes;
346 }
81318f84 347
c77f8667 348 /**
349 * This function adds the Financial ACL clauses to the where clause.
350 *
351 * This is currently somewhat mocking the native hook implementation
352 * for the acls that are in core. If the financialaclreport extension is installed
353 * core acls are not applied as that would result in them being applied twice.
354 *
355 * Long term we should either consolidate the financial acls in core or use only the extension.
356 * Both require substantial clean up before implementing and by the time the code is clean enough to
357 * take the final step we should
358 * be able to implement by removing one half of the other of this function.
359 *
360 * @param array $whereClauses
361 */
362 public static function addACLClausesToWhereClauses(&$whereClauses) {
61076736 363 $contributionBAO = new CRM_Contribute_BAO_Contribution();
364 $whereClauses = array_merge($whereClauses, $contributionBAO->addSelectWhereClause());
c77f8667 365
c77f8667 366 }
367
85b3d95d
E
368 /**
369 * Function to build a permissioned sql where clause based on available financial types.
370 *
4a2b8550 371 * @param array $whereClauses
85b3d95d
E
372 * (reference ) an array of clauses
373 * @param string $component
374 * the type of component
375 * @param string $alias
376 * the alias to use
377 *
378 */
1f76c4cd 379 public static function buildPermissionedClause(&$whereClauses, $component = NULL, $alias = NULL) {
49f92712 380 // @todo the relevant addSelectWhere clause should be called.
2435064f
PN
381 if (!self::isACLFinancialTypeStatus()) {
382 return FALSE;
383 }
be274d8a 384 if (is_array($whereClauses)) {
d51d109d 385 $types = self::getAllEnabledAvailableFinancialTypes();
f71679cf 386 if (empty($types)) {
8173dae3 387 $whereClauses[] = ' ' . $alias . '.financial_type_id IN (0)';
f71679cf
E
388 }
389 else {
a8b59c2c 390 $whereClauses[] = ' ' . $alias . '.financial_type_id IN (' . implode(',', array_keys($types)) . ')';
f71679cf 391 }
be274d8a
E
392 }
393 else {
394 if ($component == 'contribution') {
160a7ef5 395 $types = self::getAllEnabledAvailableFinancialTypes();
be274d8a
E
396 $column = "financial_type_id";
397 }
398 if ($component == 'membership') {
761b9c8e 399 self::getAvailableMembershipTypes($types, CRM_Core_Action::VIEW);
be274d8a 400 $column = "membership_type_id";
25cc088b 401 }
761b9c8e 402 if (!empty($whereClauses)) {
f25c0c04 403 $whereClauses .= ' AND ';
761b9c8e 404 }
25cc088b 405 if (empty($types)) {
761b9c8e 406 $whereClauses .= " civicrm_{$component}.{$column} IN (0)";
25cc088b 407 return;
be274d8a 408 }
761b9c8e 409 $whereClauses .= " civicrm_{$component}.{$column} IN (" . implode(',', array_keys($types)) . ")";
81318f84 410 }
81318f84 411 }
59ccc8cd 412
85b3d95d
E
413 /**
414 * Function to check if lineitems present in a contribution have permissioned FTs.
415 *
416 * @param int $id
417 * contribution id
418 * @param string $op
419 * the mode of operation, can be add, view, edit, delete
420 * @param bool $force
421 *
dbb0d30b 422 * @return bool
85b3d95d 423 */
59ccc8cd 424 public static function checkPermissionedLineItems($id, $op, $force = TRUE) {
895d596d
E
425 if (!self::isACLFinancialTypeStatus()) {
426 return TRUE;
427 }
59ccc8cd 428 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($id);
b0c2be34 429 $flag = FALSE;
8173dae3 430 foreach ($lineItems as $items) {
59ccc8cd
E
431 if (!CRM_Core_Permission::check($op . ' contributions of type ' . CRM_Contribute_PseudoConstant::financialType($items['financial_type_id']))) {
432 if ($force) {
433 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
434 break;
435 }
b0c2be34
E
436 $flag = FALSE;
437 break;
59ccc8cd
E
438 }
439 else {
b0c2be34 440 $flag = TRUE;
59ccc8cd
E
441 }
442 }
b0c2be34 443 return $flag;
59ccc8cd 444 }
85b3d95d 445
2435064f 446 /**
23dba589
SL
447 * Check if the logged in user has permission to edit the given financial type.
448 *
449 * This is called when determining if they can edit things like option values
450 * in price sets. At the moment it is not possible to change an option value from
451 * a type you do not have permission to to a type that you do.
452 *
453 * @todo it is currently not possible to edit disabled types if you have ACLs on.
454 * Do ACLs still apply once disabled? That question should be resolved if tackling
455 * that gap.
456 *
457 * @param int $financialTypeID
458 *
459 * @return bool
460 */
461 public static function checkPermissionToEditFinancialType($financialTypeID) {
462 if (!self::isACLFinancialTypeStatus()) {
463 return TRUE;
464 }
160a7ef5 465 $financialTypes = CRM_Financial_BAO_FinancialType::getAllAvailableFinancialTypes(CRM_Core_Action::UPDATE);
23dba589
SL
466 return isset($financialTypes[$financialTypeID]);
467 }
468
469 /**
470 * Check if FT-ACL is turned on or off.
471 *
472 * @todo rename this function e.g isFinancialTypeACLsEnabled.
2435064f 473 *
8173dae3 474 * @return bool
2435064f
PN
475 */
476 public static function isACLFinancialTypeStatus() {
dbaa9d7d 477 if (!isset(\Civi::$statics[__CLASS__]['is_acl_enabled'])) {
478 \Civi::$statics[__CLASS__]['is_acl_enabled'] = FALSE;
2fc43bbd 479 $realSetting = \Civi::$statics[__CLASS__]['is_acl_enabled'] = Civi::settings()->get('acl_financial_type');
480 if (!$realSetting) {
481 $contributeSettings = Civi::settings()->get('contribution_invoice_settings');
482 if (CRM_Utils_Array::value('acl_financial_type', $contributeSettings)) {
483 \Civi::$statics[__CLASS__]['is_acl_enabled'] = TRUE;
484 }
dbaa9d7d 485 }
2435064f 486 }
dbaa9d7d 487 return \Civi::$statics[__CLASS__]['is_acl_enabled'];
2435064f 488 }
a8b59c2c 489
6a488035 490}