Merge pull request #13068 from alifrumin/formLink
[civicrm-core.git] / CRM / Financial / BAO / FinancialType.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33 class CRM_Financial_BAO_FinancialType extends CRM_Financial_DAO_FinancialType {
34
35 /**
36 * Static cache holder of available financial types for this session
37 */
38 static $_availableFinancialTypes = array();
39 /**
40 * Static cache holder of status of ACL-FT enabled/disabled for this session
41 */
42 static $_statusACLFt = array();
43
44 /**
45 * Class constructor.
46 */
47 public function __construct() {
48 parent::__construct();
49 }
50
51 /**
52 * Fetch object based on array of properties.
53 *
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.
58 *
59 * @return CRM_Financial_DAO_FinancialType
60 */
61 public static function retrieve(&$params, &$defaults) {
62 $financialType = new CRM_Financial_DAO_FinancialType();
63 $financialType->copyValues($params);
64 if ($financialType->find(TRUE)) {
65 CRM_Core_DAO::storeValues($financialType, $defaults);
66 return $financialType;
67 }
68 return NULL;
69 }
70
71 /**
72 * Update the is_active flag in the db.
73 *
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.
78 *
79 * @return bool
80 */
81 public static function setIsActive($id, $is_active) {
82 return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_FinancialType', $id, 'is_active', $is_active);
83 }
84
85 /**
86 * Add the financial types.
87 *
88 * @param array $params
89 * Reference array contains the values submitted by the form.
90 * @param array $ids
91 * Reference array contains the id.
92 *
93 * @return object
94 */
95 public static function add(&$params, &$ids = array()) {
96 if (empty($params['id'])) {
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);
100 }
101
102 // action is taken depending upon the mode
103 $financialType = new CRM_Financial_DAO_FinancialType();
104 $financialType->copyValues($params);
105 if (!empty($ids['financialType'])) {
106 $financialType->id = CRM_Utils_Array::value('financialType', $ids);
107 if (self::isACLFinancialTypeStatus()) {
108 $prevName = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $financialType->id, 'name');
109 if ($prevName != $params['name']) {
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.
113 Then after making the change of name, reset the permissions to the way they were."), ts('Warning'), 'warning');
114 }
115 }
116 }
117 $financialType->save();
118 // CRM-12470
119 if (empty($ids['financialType']) && empty($params['id'])) {
120 $titles = CRM_Financial_BAO_FinancialTypeAccount::createDefaultFinancialAccounts($financialType);
121 $financialType->titles = $titles;
122 }
123 return $financialType;
124 }
125
126 /**
127 * Delete financial Types.
128 *
129 * @param int $financialTypeId
130 *
131 * @return array|bool
132 */
133 public static function del($financialTypeId) {
134 $financialType = new CRM_Financial_DAO_FinancialType();
135 $financialType->id = $financialTypeId;
136 $financialType->find(TRUE);
137 // tables to ignore checks for financial_type_id
138 $ignoreTables = array('CRM_Financial_DAO_EntityFinancialAccount');
139
140 // TODO: if (!$financialType->find(true)) {
141
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();
146 foreach ($occurrences as $occurrence) {
147 $className = get_class($occurrence);
148 if (!in_array($className, $tables) && !in_array($className, $ignoreTables)) {
149 $tables[] = $className;
150 }
151 }
152 if (!empty($tables)) {
153 $message = ts('The following tables have an entry for this financial type: %1', array('%1' => implode(', ', $tables)));
154
155 $errors = array();
156 $errors['is_error'] = 1;
157 $errors['error_message'] = $message;
158 return $errors;
159 }
160 }
161
162 // delete from financial Type table
163 $financialType->delete();
164
165 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
166 $entityFinancialType->entity_id = $financialTypeId;
167 $entityFinancialType->entity_table = 'civicrm_financial_type';
168 $entityFinancialType->delete();
169 return FALSE;
170 }
171
172 /**
173 * fetch financial type having relationship as Income Account is.
174 *
175 *
176 * @return array
177 * all financial type with income account is relationship
178 */
179 public static function getIncomeFinancialType() {
180 // Financial Type
181 $financialType = CRM_Contribute_PseudoConstant::financialType();
182 $revenueFinancialType = array();
183 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
184 CRM_Core_PseudoConstant::populate(
185 $revenueFinancialType,
186 'CRM_Financial_DAO_EntityFinancialAccount',
187 $all = TRUE,
188 $retrieve = 'entity_id',
189 $filter = NULL,
190 "account_relationship = $relationTypeId AND entity_table = 'civicrm_financial_type' "
191 );
192
193 foreach ($financialType as $key => $financialTypeName) {
194 if (!in_array($key, $revenueFinancialType)
195 || (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
196 && !CRM_Core_Permission::check('add contributions of type ' . $financialTypeName))
197 ) {
198 unset($financialType[$key]);
199 }
200 }
201 return $financialType;
202 }
203
204 /**
205 * Add permissions for financial types.
206 *
207 * @param array $permissions
208 * @param array $descriptions
209 *
210 * @return bool
211 */
212 public static function permissionedFinancialTypes(&$permissions, $descriptions) {
213 if (!self::isACLFinancialTypeStatus()) {
214 return FALSE;
215 }
216 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
217 $prefix = ts('CiviCRM') . ': ';
218 $actions = array('add', 'view', 'edit', 'delete');
219 foreach ($financialTypes as $id => $type) {
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'),
239 );
240 }
241 }
242
243 /**
244 * Wrapper aroung getAvailableFinancialTypes to get all including disabled FinancialTypes
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 */
252 public static function getAllAvailableFinancialTypes($action = CRM_Core_Action::VIEW, $resetCache = FALSE) {
253 // Flush pseudoconstant cache
254 CRM_Contribute_PseudoConstant::flush('financialType');
255 $thisIsAUselessVariableButSolvesPHPError = NULL;
256 $financialTypes = self::getAvailableFinancialTypes($thisIsAUselessVariableButSolvesPHPError, $action, $resetCache, TRUE);
257 return $financialTypes;
258 }
259
260 /**
261 * Wrapper aroung getAvailableFinancialTypes to get all FinancialTypes Excluding Disabled ones.
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 */
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;
273 }
274
275 /**
276 * Get available Financial Types.
277 *
278 * @param array $financialTypes
279 * (reference ) an array of financial types
280 * @param int|string $action
281 * the type of action, can be add, view, edit, delete
282 * @param bool $resetCache
283 * load values from static cache
284 * @param bool $includeDisabled
285 * Whether we should load in disabled FinancialTypes or Not
286 *
287 * @return array
288 */
289 public static function getAvailableFinancialTypes(&$financialTypes = NULL, $action = CRM_Core_Action::VIEW, $resetCache = FALSE, $includeDisabled = FALSE) {
290 if (empty($financialTypes)) {
291 $financialTypes = CRM_Contribute_PseudoConstant::financialType(NULL, $includeDisabled);
292 }
293 if (!self::isACLFinancialTypeStatus()) {
294 return $financialTypes;
295 }
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 );
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 }
308 }
309 \Civi::$statics[__CLASS__]['available_types_' . $action] = $financialTypes;
310 }
311 $financialTypes = \Civi::$statics[__CLASS__]['available_types_' . $action];
312 return \Civi::$statics[__CLASS__]['available_types_' . $action];
313 }
314
315 /**
316 * Get available Membership Types.
317 *
318 * @param array $membershipTypes
319 * (reference ) an array of membership types
320 * @param int|string $action
321 * the type of action, can be add, view, edit, delete
322 *
323 * @return array
324 */
325 public static function getAvailableMembershipTypes(&$membershipTypes = NULL, $action = CRM_Core_Action::VIEW) {
326 if (empty($membershipTypes)) {
327 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
328 }
329 if (!self::isACLFinancialTypeStatus()) {
330 return $membershipTypes;
331 }
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 );
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);
341 if (!CRM_Core_Permission::check($actions[$action] . ' contributions of type ' . $finType)) {
342 unset($membershipTypes[$memTypeId]);
343 }
344 }
345 return $membershipTypes;
346 }
347
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) {
363 $contributionBAO = new CRM_Contribute_BAO_Contribution();
364 $whereClauses = array_merge($whereClauses, $contributionBAO->addSelectWhereClause());
365
366 }
367
368 /**
369 * Function to build a permissioned sql where clause based on available financial types.
370 *
371 * @param array $whereClauses
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 */
379 public static function buildPermissionedClause(&$whereClauses, $component = NULL, $alias = NULL) {
380 // @todo the relevant addSelectWhere clause should be called.
381 if (!self::isACLFinancialTypeStatus()) {
382 return FALSE;
383 }
384 if (is_array($whereClauses)) {
385 $types = self::getAllEnabledAvailableFinancialTypes();
386 if (empty($types)) {
387 $whereClauses[] = ' ' . $alias . '.financial_type_id IN (0)';
388 }
389 else {
390 $whereClauses[] = ' ' . $alias . '.financial_type_id IN (' . implode(',', array_keys($types)) . ')';
391 }
392 }
393 else {
394 if ($component == 'contribution') {
395 $types = self::getAllEnabledAvailableFinancialTypes();
396 $column = "financial_type_id";
397 }
398 if ($component == 'membership') {
399 self::getAvailableMembershipTypes($types, CRM_Core_Action::VIEW);
400 $column = "membership_type_id";
401 }
402 if (!empty($whereClauses)) {
403 $whereClauses .= ' AND ';
404 }
405 if (empty($types)) {
406 $whereClauses .= " civicrm_{$component}.{$column} IN (0)";
407 return;
408 }
409 $whereClauses .= " civicrm_{$component}.{$column} IN (" . implode(',', array_keys($types)) . ")";
410 }
411 }
412
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 *
422 * @return bool
423 */
424 public static function checkPermissionedLineItems($id, $op, $force = TRUE) {
425 if (!self::isACLFinancialTypeStatus()) {
426 return TRUE;
427 }
428 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($id);
429 $flag = FALSE;
430 foreach ($lineItems as $items) {
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 }
436 $flag = FALSE;
437 break;
438 }
439 else {
440 $flag = TRUE;
441 }
442 }
443 return $flag;
444 }
445
446 /**
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 }
465 $financialTypes = CRM_Financial_BAO_FinancialType::getAllAvailableFinancialTypes(CRM_Core_Action::UPDATE);
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.
473 *
474 * @return bool
475 */
476 public static function isACLFinancialTypeStatus() {
477 if (!isset(\Civi::$statics[__CLASS__]['is_acl_enabled'])) {
478 \Civi::$statics[__CLASS__]['is_acl_enabled'] = FALSE;
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 }
485 }
486 }
487 return \Civi::$statics[__CLASS__]['is_acl_enabled'];
488 }
489
490 }