Merge pull request #12613 from JMAConsulting/core-issue-297
[civicrm-core.git] / CRM / Financial / BAO / FinancialType.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 * Function to build a permissioned sql where clause based on available financial types.
350 *
351 * @param array $whereClauses
352 * (reference ) an array of clauses
353 * @param string $component
354 * the type of component
355 * @param string $alias
356 * the alias to use
357 *
358 */
359 public static function buildPermissionedClause(&$whereClauses, $component = NULL, $alias = NULL) {
360 if (!self::isACLFinancialTypeStatus()) {
361 return FALSE;
362 }
363 if (is_array($whereClauses)) {
364 $types = self::getAllEnabledAvailableFinancialTypes();
365 if (empty($types)) {
366 $whereClauses[] = ' ' . $alias . '.financial_type_id IN (0)';
367 }
368 else {
369 $whereClauses[] = ' ' . $alias . '.financial_type_id IN (' . implode(',', array_keys($types)) . ')';
370 }
371 }
372 else {
373 if ($component == 'contribution') {
374 $types = self::getAllEnabledAvailableFinancialTypes();
375 $column = "financial_type_id";
376 }
377 if ($component == 'membership') {
378 self::getAvailableMembershipTypes($types, CRM_Core_Action::VIEW);
379 $column = "membership_type_id";
380 }
381 if (!empty($whereClauses)) {
382 $whereClauses .= ' AND ';
383 }
384 if (empty($types)) {
385 $whereClauses .= " civicrm_{$component}.{$column} IN (0)";
386 return;
387 }
388 $whereClauses .= " civicrm_{$component}.{$column} IN (" . implode(',', array_keys($types)) . ")";
389 }
390 }
391
392 /**
393 * Function to check if lineitems present in a contribution have permissioned FTs.
394 *
395 * @param int $id
396 * contribution id
397 * @param string $op
398 * the mode of operation, can be add, view, edit, delete
399 * @param bool $force
400 *
401 * @return bool
402 */
403 public static function checkPermissionedLineItems($id, $op, $force = TRUE) {
404 if (!self::isACLFinancialTypeStatus()) {
405 return TRUE;
406 }
407 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($id);
408 $flag = FALSE;
409 foreach ($lineItems as $items) {
410 if (!CRM_Core_Permission::check($op . ' contributions of type ' . CRM_Contribute_PseudoConstant::financialType($items['financial_type_id']))) {
411 if ($force) {
412 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
413 break;
414 }
415 $flag = FALSE;
416 break;
417 }
418 else {
419 $flag = TRUE;
420 }
421 }
422 return $flag;
423 }
424
425 /**
426 * Check if the logged in user has permission to edit the given financial type.
427 *
428 * This is called when determining if they can edit things like option values
429 * in price sets. At the moment it is not possible to change an option value from
430 * a type you do not have permission to to a type that you do.
431 *
432 * @todo it is currently not possible to edit disabled types if you have ACLs on.
433 * Do ACLs still apply once disabled? That question should be resolved if tackling
434 * that gap.
435 *
436 * @param int $financialTypeID
437 *
438 * @return bool
439 */
440 public static function checkPermissionToEditFinancialType($financialTypeID) {
441 if (!self::isACLFinancialTypeStatus()) {
442 return TRUE;
443 }
444 $financialTypes = CRM_Financial_BAO_FinancialType::getAllAvailableFinancialTypes(CRM_Core_Action::UPDATE);
445 return isset($financialTypes[$financialTypeID]);
446 }
447
448 /**
449 * Check if FT-ACL is turned on or off.
450 *
451 * @todo rename this function e.g isFinancialTypeACLsEnabled.
452 *
453 * @return bool
454 */
455 public static function isACLFinancialTypeStatus() {
456 if (!isset(\Civi::$statics[__CLASS__]['is_acl_enabled'])) {
457 \Civi::$statics[__CLASS__]['is_acl_enabled'] = FALSE;
458 $contributeSettings = Civi::settings()->get('contribution_invoice_settings');
459 if (CRM_Utils_Array::value('acl_financial_type', $contributeSettings)) {
460 \Civi::$statics[__CLASS__]['is_acl_enabled'] = TRUE;
461 }
462 }
463 return \Civi::$statics[__CLASS__]['is_acl_enabled'];
464 }
465
466 }