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