4c3c5ce83355c968f769d7153c2f05b7835473a7
[civicrm-core.git] / CRM / Financial / BAO / FinancialType.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 */
33 class CRM_Financial_BAO_FinancialType extends CRM_Financial_DAO_FinancialType {
34
35 /**
36 * Static holder for the default LT.
37 */
38 static $_defaultContributionType = NULL;
39 /**
40 * Static cache holder of available financial types for this session
41 */
42 static $_availableFinancialTypes = array();
43 /**
44 * Static cache holder of status of ACL-FT enabled/disabled for this session
45 */
46 static $_statusACLFt = array();
47
48 /**
49 * Class constructor.
50 */
51 public function __construct() {
52 parent::__construct();
53 }
54
55 /**
56 * Fetch object based on array of properties.
57 *
58 * @param array $params
59 * (reference ) an assoc array of name/value pairs.
60 * @param array $defaults
61 * (reference ) an assoc array to hold the flattened values.
62 *
63 * @return CRM_Contribute_BAO_ContributionType
64 */
65 public static function retrieve(&$params, &$defaults) {
66 $financialType = new CRM_Financial_DAO_FinancialType();
67 $financialType->copyValues($params);
68 if ($financialType->find(TRUE)) {
69 CRM_Core_DAO::storeValues($financialType, $defaults);
70 return $financialType;
71 }
72 return NULL;
73 }
74
75 /**
76 * Update the is_active flag in the db.
77 *
78 * @param int $id
79 * Id of the database record.
80 * @param bool $is_active
81 * Value we want to set the is_active field.
82 *
83 * @return Object
84 * DAO object on success, null otherwise
85 */
86 public static function setIsActive($id, $is_active) {
87 return CRM_Core_DAO::setFieldValue('CRM_Financial_DAO_FinancialType', $id, 'is_active', $is_active);
88 }
89
90 /**
91 * Add the financial types.
92 *
93 * @param array $params
94 * Reference array contains the values submitted by the form.
95 * @param array $ids
96 * Reference array contains the id.
97 *
98 * @return object
99 */
100 public static function add(&$params, &$ids = array()) {
101 if (empty($params['id'])) {
102 $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
103 $params['is_deductible'] = CRM_Utils_Array::value('is_deductible', $params, FALSE);
104 $params['is_reserved'] = CRM_Utils_Array::value('is_reserved', $params, FALSE);
105 }
106
107 // action is taken depending upon the mode
108 $financialType = new CRM_Financial_DAO_FinancialType();
109 $financialType->copyValues($params);
110 if (!empty($ids['financialType'])) {
111 $financialType->id = CRM_Utils_Array::value('financialType', $ids);
112 if (self::isACLFinancialTypeStatus()) {
113 $prevName = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $financialType->id, 'name');
114 if ($prevName != $params['name']) {
115 CRM_Core_Session::setStatus(ts("Changing the name of a Financial Type will result in losing the current permissions associated with that Financial Type.
116 Before making this change you should likely note the existing permissions at Administer > Users and Permissions > Permissions (Access Control),
117 then clicking the Access Control link for your Content Management System, then noting down the permissions for 'CiviCRM: {financial type name} view', etc.
118 Then after making the change of name, reset the permissions to the way they were."), ts('Warning'), 'warning');
119 }
120 }
121 }
122 $financialType->save();
123 // CRM-12470
124 if (empty($ids['financialType']) && empty($params['id'])) {
125 $titles = CRM_Financial_BAO_FinancialTypeAccount::createDefaultFinancialAccounts($financialType);
126 $financialType->titles = $titles;
127 }
128 return $financialType;
129 }
130
131 /**
132 * Delete financial Types.
133 *
134 * @param int $financialTypeId
135 *
136 * @return array|bool
137 */
138 public static function del($financialTypeId) {
139 $financialType = new CRM_Financial_DAO_FinancialType();
140 $financialType->id = $financialTypeId;
141 $financialType->find(TRUE);
142 // tables to ingore checks for financial_type_id
143 $ignoreTables = array('CRM_Financial_DAO_EntityFinancialAccount');
144
145 // TODO: if (!$financialType->find(true)) {
146
147 // ensure that we have no objects that have an FK to this financial type id TODO: that cannot be null
148 $occurrences = $financialType->findReferences();
149 if ($occurrences) {
150 $tables = array();
151 foreach ($occurrences as $occurrence) {
152 $className = get_class($occurrence);
153 if (!in_array($className, $tables) && !in_array($className, $ignoreTables)) {
154 $tables[] = $className;
155 }
156 }
157 if (!empty($tables)) {
158 $message = ts('The following tables have an entry for this financial type: %1', array('%1' => implode(', ', $tables)));
159
160 $errors = array();
161 $errors['is_error'] = 1;
162 $errors['error_message'] = $message;
163 return $errors;
164 }
165 }
166
167 // delete from financial Type table
168 $financialType->delete();
169
170 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
171 $entityFinancialType->entity_id = $financialTypeId;
172 $entityFinancialType->entity_table = 'civicrm_financial_type';
173 $entityFinancialType->delete();
174 return FALSE;
175 }
176
177 /**
178 * fetch financial type having relationship as Income Account is.
179 *
180 *
181 * @return array
182 * all financial type with income account is relationship
183 */
184 public static function getIncomeFinancialType() {
185 // Financial Type
186 $financialType = CRM_Contribute_PseudoConstant::financialType();
187 $revenueFinancialType = array();
188 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
189 CRM_Core_PseudoConstant::populate(
190 $revenueFinancialType,
191 'CRM_Financial_DAO_EntityFinancialAccount',
192 $all = TRUE,
193 $retrieve = 'entity_id',
194 $filter = NULL,
195 "account_relationship = $relationTypeId AND entity_table = 'civicrm_financial_type' "
196 );
197
198 foreach ($financialType as $key => $financialTypeName) {
199 if (!in_array($key, $revenueFinancialType)
200 || (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
201 && !CRM_Core_Permission::check('add contributions of type ' . $financialTypeName))
202 ) {
203 unset($financialType[$key]);
204 }
205 }
206 return $financialType;
207 }
208
209 /**
210 * Add permissions for financial types.
211 *
212 * @param array $permissions
213 * @param array $descriptions
214 *
215 * @return bool
216 */
217 public static function permissionedFinancialTypes(&$permissions, $descriptions) {
218 if (!self::isACLFinancialTypeStatus()) {
219 return FALSE;
220 }
221 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
222 $prefix = ts('CiviCRM') . ': ';
223 $actions = array('add', 'view', 'edit', 'delete');
224 foreach ($financialTypes as $id => $type) {
225 foreach ($actions as $action) {
226 if ($descriptions) {
227 $permissions[$action . ' contributions of type ' . $type] = array(
228 $prefix . ts($action . ' contributions of type ') . $type,
229 ts(ucfirst($action) . ' contributions of type ') . $type,
230 );
231 }
232 else {
233 $permissions[$action . ' contributions of type ' . $type] = $prefix . ts($action . ' contributions of type ') . $type;
234 }
235 }
236 }
237 if (!$descriptions) {
238 $permissions['administer CiviCRM Financial Types'] = $prefix . ts('administer CiviCRM Financial Types');
239 }
240 else {
241 $permissions['administer CiviCRM Financial Types'] = array(
242 $prefix . ts('administer CiviCRM Financial Types'),
243 ts('Administer access to Financial Types'),
244 );
245 }
246 }
247
248 /**
249 * Get available Financial Types.
250 *
251 * @param array $financialTypes
252 * (reference ) an array of financial types
253 * @param int|string $action
254 * the type of action, can be add, view, edit, delete
255 * @param bool $resetCache
256 * load values from static cache
257 *
258 * @return array
259 */
260 public static function getAvailableFinancialTypes(&$financialTypes = NULL, $action = CRM_Core_Action::VIEW, $resetCache = FALSE) {
261 if (empty($financialTypes)) {
262 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
263 }
264 if (!self::isACLFinancialTypeStatus()) {
265 return $financialTypes;
266 }
267 $actions = array(
268 CRM_Core_Action::VIEW => 'view',
269 CRM_Core_Action::UPDATE => 'edit',
270 CRM_Core_Action::ADD => 'add',
271 CRM_Core_Action::DELETE => 'delete',
272 );
273 // check cached value
274 if (CRM_Utils_Array::value($action, self::$_availableFinancialTypes) && !$resetCache) {
275 $financialTypes = self::$_availableFinancialTypes[$action];
276 return self::$_availableFinancialTypes[$action];
277 }
278 foreach ($financialTypes as $finTypeId => $type) {
279 if (!CRM_Core_Permission::check($actions[$action] . ' contributions of type ' . $type)) {
280 unset($financialTypes[$finTypeId]);
281 }
282 }
283 self::$_availableFinancialTypes[$action] = $financialTypes;
284 return $financialTypes;
285 }
286
287 /**
288 * Get available Membership Types.
289 *
290 * @param array $membershipTypes
291 * (reference ) an array of membership types
292 * @param int|string $action
293 * the type of action, can be add, view, edit, delete
294 *
295 * @return array
296 */
297 public static function getAvailableMembershipTypes(&$membershipTypes = NULL, $action = CRM_Core_Action::VIEW) {
298 if (empty($membershipTypes)) {
299 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
300 }
301 if (!self::isACLFinancialTypeStatus()) {
302 return $membershipTypes;
303 }
304 $actions = array(
305 CRM_Core_Action::VIEW => 'view',
306 CRM_Core_Action::UPDATE => 'edit',
307 CRM_Core_Action::ADD => 'add',
308 CRM_Core_Action::DELETE => 'delete',
309 );
310 foreach ($membershipTypes as $memTypeId => $type) {
311 $finTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memTypeId, 'financial_type_id');
312 $finType = CRM_Contribute_PseudoConstant::financialType($finTypeId);
313 if (!CRM_Core_Permission::check($actions[$action] . ' contributions of type ' . $finType)) {
314 unset($membershipTypes[$memTypeId]);
315 }
316 }
317 return $membershipTypes;
318 }
319
320 /**
321 * Function to build a permissioned sql where clause based on available financial types.
322 *
323 * @param array $whereClauses
324 * (reference ) an array of clauses
325 * @param string $component
326 * the type of component
327 * @param string $alias
328 * the alias to use
329 *
330 */
331 public static function buildPermissionedClause(&$whereClauses, $component = NULL, $alias = NULL) {
332 if (!self::isACLFinancialTypeStatus()) {
333 return FALSE;
334 }
335 if (is_array($whereClauses)) {
336 self::getAvailableFinancialTypes($types);
337 if (empty($types)) {
338 $whereClauses[] = ' ' . $alias . '.financial_type_id IN (0)';
339 }
340 else {
341 $whereClauses[] = ' ' . $alias . '.financial_type_id IN (' . implode(',', array_keys($types)) . ')';
342 }
343 }
344 else {
345 if ($component == 'contribution') {
346 self::getAvailableFinancialTypes($types);
347 $column = "financial_type_id";
348 }
349 if ($component == 'membership') {
350 self::getAvailableMembershipTypes($types, CRM_Core_Action::VIEW);
351 $column = "membership_type_id";
352 }
353 if (!empty($whereClauses)) {
354 $whereClauses .= ' AND ';
355 }
356 if (empty($types)) {
357 $whereClauses .= " civicrm_{$component}.{$column} IN (0)";
358 return;
359 }
360 $whereClauses .= " civicrm_{$component}.{$column} IN (" . implode(',', array_keys($types)) . ")";
361 }
362 }
363
364 /**
365 * Function to check if lineitems present in a contribution have permissioned FTs.
366 *
367 * @param int $id
368 * contribution id
369 * @param string $op
370 * the mode of operation, can be add, view, edit, delete
371 * @param bool $force
372 *
373 */
374 public static function checkPermissionedLineItems($id, $op, $force = TRUE) {
375 if (!self::isACLFinancialTypeStatus()) {
376 return TRUE;
377 }
378 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($id);
379 $flag = FALSE;
380 foreach ($lineItems as $items) {
381 if (!CRM_Core_Permission::check($op . ' contributions of type ' . CRM_Contribute_PseudoConstant::financialType($items['financial_type_id']))) {
382 if ($force) {
383 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
384 break;
385 }
386 $flag = FALSE;
387 break;
388 }
389 else {
390 $flag = TRUE;
391 }
392 }
393 return $flag;
394 }
395
396 /**
397 * Check if FT-ACL is turned on or off
398 *
399 * @return bool
400 */
401 public static function isACLFinancialTypeStatus() {
402 if (array_key_exists('acl_financial_type', self::$_statusACLFt)) {
403 return self::$_statusACLFt['acl_financial_type'];
404 }
405 $contributeSettings = CRM_Core_BAO_Setting::getItem(
406 CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'
407 );
408 self::$_statusACLFt['acl_financial_type'] = FALSE;
409 if (CRM_Utils_Array::value('acl_financial_type', $contributeSettings)) {
410 self::$_statusACLFt['acl_financial_type'] = TRUE;
411 }
412 return self::$_statusACLFt['acl_financial_type'];
413 }
414
415 }