Remove freeb and some other legacy code.
[openemr.git] / gacl / gacl.class.php
blob2ba49004404d6f39eeffeed6c17a6dabef9ef2c9
1 <?php
2 // $Id$
4 /**
5 * phpGACL - Generic Access Control List
6 * Copyright (C) 2002,2003 Mike Benoit
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 * For questions, help, comments, discussion, etc., please join the
23 * phpGACL mailing list. http://sourceforge.net/mail/?group_id=57103
25 * You may contact the author of phpGACL by e-mail at:
26 * ipso@snappymail.ca
28 * The latest version of phpGACL can be obtained from:
29 * http://phpgacl.sourceforge.net/
31 * @package phpGACL
35 * Path to ADODB.
38 if ( !defined('ADODB_DIR') ) {
39 define('ADODB_DIR', dirname(__FILE__).'/../vendor/adodb/adodb-php');
42 //openemr configuration file - bm - 05-2009
43 // to collect sql database login info and the utf8 flag
44 include_once(dirname(__FILE__).'/../library/sqlconf.php');
46 /**
47 * phpGACL main class
49 * Class gacl should be used in applications where only querying the phpGACL
50 * database is required.
52 * @package phpGACL
53 * @author Mike Benoit <ipso@snappymail.ca>
55 class gacl {
57 --- phpGACL Configuration path/file ---
59 var $config_file = '';
62 --- Private properties ---
64 /** @var boolean Enables Debug output if true */
65 var $_debug = FALSE;
68 --- Database configuration. ---
70 /** @var string Prefix for all the phpgacl tables in the database */
71 var $_db_table_prefix = 'gacl_';
73 /** @var string The database type, based on available ADODB connectors - mysql, postgres7, sybase, oci8po See here for more: http://php.weblogs.com/adodb_manual#driverguide */
74 var $_db_type = 'mysqli';
76 /** @var string The database server */
77 var $_db_host = '';
79 /** @var string The database user name */
80 var $_db_user = '';
82 /** @var string The database user password */
83 var $_db_password = '';
85 /** @var string The database name */
86 var $_db_name = '';
88 /** @var object An ADODB database connector object */
89 var $_db = '';
91 /** @var boolean The utf8 encoding flag - bm 05-2009 */
92 var $_db_utf8_flag = '';
95 * NOTE: This cache must be manually cleaned each time ACL's are modified.
96 * Alternatively you could wait for the cache to expire.
99 /** @var boolean Caches queries if true */
100 var $_caching = FALSE;
102 /** @var boolean Force cache to expire */
103 var $_force_cache_expire = TRUE;
105 /** @var string The directory for cache file to eb written (ensure write permission are set) */
106 var $_cache_dir = '/tmp/phpgacl_cache'; // NO trailing slash
108 /** @var int The time for the cache to expire in seconds - 600 == Ten Minutes */
109 var $_cache_expire_time=600;
111 /** @var string A switch to put acl_check into '_group_' mode */
112 var $_group_switch = '_group_';
115 * Constructor
116 * @param array An arry of options to oeverride the class defaults
118 function __construct($options = NULL) {
120 $available_options = array('db','debug','items_per_page','max_select_box_items','max_search_return_items','db_table_prefix','db_type','db_host','db_user','db_password','db_name','caching','force_cache_expire','cache_dir','cache_expire_time');
122 //Values supplied in $options array overwrite those in the config file.
123 if ( file_exists($this->config_file) ) {
124 $config = parse_ini_file($this->config_file);
126 if ( is_array($config) ) {
127 $gacl_options = array_merge($config, $options);
130 unset($config);
133 if (is_array($options)) {
134 foreach ($options as $key => $value) {
135 $this->debug_text("Option: $key");
137 if (in_array($key, $available_options) ) {
138 $this->debug_text("Valid Config options: $key");
139 $property = '_'.$key;
140 $this->$property = $value;
141 } else {
142 $this->debug_text("ERROR: Config option: $key is not a valid option");
147 //collect openemr sql info from include at top of script - bm 05-2009
148 global $sqlconf, $disable_utf8_flag;
149 $this->_db_host = $sqlconf["host"];
150 $this->_db_user = $sqlconf["login"];
151 $this->_db_password = $sqlconf["pass"];
152 $this->_db_name = $sqlconf["dbase"];
153 if (!$disable_utf8_flag) {
154 $utf8_flag = true;
156 else {
157 $utf8_flag = false;
159 $this->_db_utf8_flag = $utf8_flag;
161 require_once( ADODB_DIR .'/adodb.inc.php');
162 require_once( ADODB_DIR .'/adodb-pager.inc.php');
164 if (is_object($this->_db)) {
165 $this->db = &$this->_db;
166 } else {
167 $this->db = ADONewConnection($this->_db_type);
168 //Use NUM for slight performance/memory reasons.
169 $this->db->SetFetchMode(ADODB_FETCH_NUM);
171 // Port to be used in connection
172 $this->db->port = $sqlconf["port"];
174 $this->db->PConnect($this->_db_host, $this->_db_user, $this->_db_password, $this->_db_name);
176 // Modified 5/2009 by BM for UTF-8 project
177 if ($this->_db_utf8_flag) {
178 $success_flag = $this->db->Execute("SET NAMES 'utf8'");
179 if (!$success_flag) {
180 error_log("PHP custom error: from gacl gacl/gacl.class.php - Unable to set up UTF8 encoding with mysql database".$this->db->ErrorMsg(), 0);
183 // ---------------------------------------
185 //Turn off STRICT SQL
186 $sql_strict_set_success = $this->db->Execute("SET sql_mode = ''");
187 if (!$sql_strict_set_success) {
188 error_log("Unable to set strict sql setting: ".$this->db->ErrorMsg(), 0);
193 $this->db->debug = $this->_debug;
195 if ( $this->_caching == TRUE ) {
196 if (!class_exists('Hashed_Cache_Lite')) {
197 require_once(dirname(__FILE__) .'/Cache_Lite/Hashed_Cache_Lite.php');
201 * Cache options. We default to the highest performance. If you run in to cache corruption problems,
202 * Change all the 'false' to 'true', this will slow things down slightly however.
205 $cache_options = array(
206 'caching' => $this->_caching,
207 'cacheDir' => $this->_cache_dir.'/',
208 'lifeTime' => $this->_cache_expire_time,
209 'fileLocking' => TRUE,
210 'writeControl' => FALSE,
211 'readControl' => FALSE,
212 'memoryCaching' => TRUE,
213 'automaticSerialization' => FALSE
215 $this->Cache_Lite = new Hashed_Cache_Lite($cache_options);
218 return true;
222 * Prints debug text if debug is enabled.
223 * @param string THe text to output
224 * @return boolean Always returns true
226 function debug_text($text) {
228 if ($this->_debug) {
229 echo "$text<br>\n";
232 return true;
236 * Prints database debug text if debug is enabled.
237 * @param string The name of the function calling this method
238 * @return string Returns an error message
240 function debug_db($function_name = '') {
241 if ($function_name != '') {
242 $function_name .= ' (): ';
245 return $this->debug_text ($function_name .'database error: '. $this->db->ErrorMsg() .' ('. $this->db->ErrorNo() .')');
250 * Check if the current user has a given type or types of access to an access control object.
252 * Implemented as a wrapper of acl_query().
253 * This function exists simply to return TRUE/FALSE accordingly.
255 * @param string $aco_section_value The ACO section value
256 * @param string $aco_value The ACO value
257 * @param string $aro_section_value The ARO section value
258 * @param string $aro_value The ARO value
259 * @param string $axo_section_value The AXO section value (optional)
260 * @param string $axo_value The AXO section value (optional)
261 * @param integer $root_aro_group The group id of the ARO (optional)
262 * @param integer $root_axo_group The group id of the AXO (optional)
263 * @return boolean true if the check succeeds, false if not.
265 function acl_check($aco_section_value, $aco_value, $aro_section_value, $aro_value, $axo_section_value=NULL, $axo_value=NULL, $root_aro_group=NULL, $root_axo_group=NULL) {
266 $acl_result = $this->acl_query($aco_section_value, $aco_value, $aro_section_value, $aro_value, $axo_section_value, $axo_value, $root_aro_group, $root_axo_group);
268 return $acl_result['allow'];
272 * Wraps the actual acl_query() function.
274 * Quick access to the return value of an ACL.
275 * @param string The ACO section value
276 * @param string The ACO value
277 * @param string The ARO section value
278 * @param string The ARO section
279 * @param string The AXO section value (optional)
280 * @param string The AXO section value (optional)
281 * @param integer The group id of the ARO (optional)
282 * @param integer The group id of the AXO (optional)
283 * @return string The return value of the ACL
285 function acl_return_value($aco_section_value, $aco_value, $aro_section_value, $aro_value, $axo_section_value=NULL, $axo_value=NULL, $root_aro_group=NULL, $root_axo_group=NULL) {
286 $acl_result = $this->acl_query($aco_section_value, $aco_value, $aro_section_value, $aro_value, $axo_section_value, $axo_value, $root_aro_group, $root_axo_group);
288 return $acl_result['return_value'];
292 * Handles ACL lookups over arrays of AROs
293 * @param string The ACO section value
294 * @param string The ACO value
295 * @param array An named array of arrays, each element in the format aro_section_value=>array(aro_value1,aro_value1,...)
296 * @return mixed The same data format as inputted.
297 \*======================================================================*/
298 function acl_check_array($aco_section_value, $aco_value, $aro_array) {
300 Input Array:
301 Section => array(Value, Value, Value),
302 Section => array(Value, Value, Value)
306 if (!is_array($aro_array)) {
307 $this->debug_text("acl_query_array(): ARO Array must be passed");
308 return false;
311 foreach($aro_array as $aro_section_value => $aro_value_array) {
312 foreach ($aro_value_array as $aro_value) {
313 $this->debug_text("acl_query_array(): ARO Section Value: $aro_section_value ARO VALUE: $aro_value");
315 if( $this->acl_check($aco_section_value, $aco_value, $aro_section_value, $aro_value) ) {
316 $this->debug_text("acl_query_array(): ACL_CHECK True");
317 $retarr[$aro_section_value][] = $aro_value;
318 } else {
319 $this->debug_text("acl_query_array(): ACL_CHECK False");
324 return $retarr;
329 * The Main function that does the actual ACL lookup.
331 * @param string The ACO section value
332 * @param string The ACO value
333 * @param string The ARO section value
334 * @param string The ARO value
335 * @param string The AXO section value (optional)
336 * @param string The AXO value (optional)
337 * @param string The value of the ARO group (optional)
338 * @param string The value of the AXO group (optional)
339 * @param boolean Debug the operation if true (optional)
340 * @param boolean Option to return all applicable ACL's rather than just one. (optional) (Added by OpenEMR)
341 * @return array Returns as much information as possible about the ACL so other functions can trim it down and omit unwanted data.
343 function acl_query($aco_section_value, $aco_value, $aro_section_value, $aro_value, $axo_section_value=NULL, $axo_value=NULL, $root_aro_group=NULL, $root_axo_group=NULL, $debug=NULL, $return_all=FALSE) {
345 $cache_id = 'acl_query_'.$aco_section_value.'-'.$aco_value.'-'.$aro_section_value.'-'.$aro_value.'-'.$axo_section_value.'-'.$axo_value.'-'.$root_aro_group.'-'.$root_axo_group.'-'.$debug.'-'.$return_all;
347 $retarr = $this->get_cache($cache_id);
349 if (!$retarr) {
351 * Grab all groups mapped to this ARO/AXO
353 $aro_group_ids = $this->acl_get_groups($aro_section_value, $aro_value, $root_aro_group, 'ARO');
355 if (is_array($aro_group_ids) AND !empty($aro_group_ids)) {
356 $sql_aro_group_ids = implode(',', $aro_group_ids);
359 if ($axo_section_value != '' AND $axo_value != '') {
360 $axo_group_ids = $this->acl_get_groups($axo_section_value, $axo_value, $root_axo_group, 'AXO');
362 if (is_array($axo_group_ids) AND !empty($axo_group_ids)) {
363 $sql_axo_group_ids = implode(',', $axo_group_ids);
368 * This query is where all the magic happens.
369 * The ordering is very important here, as well very tricky to get correct.
370 * Currently there can be duplicate ACLs, or ones that step on each other toes. In this case, the ACL that was last updated/created
371 * is used; unless the $return_all parameter is set to TRUE, then will return the entire array of applicable ACL information (this
372 * option was added by OpenEMR)
374 * This is probably where the most optimizations can be made.
377 $order_by = array();
379 $query = '
380 SELECT a.id,a.allow,a.return_value
381 FROM '. $this->_db_table_prefix .'acl a
382 LEFT JOIN '. $this->_db_table_prefix .'aco_map ac ON ac.acl_id=a.id';
384 if ($aro_section_value != $this->_group_switch) {
385 $query .= '
386 LEFT JOIN '. $this->_db_table_prefix .'aro_map ar ON ar.acl_id=a.id';
389 if ($axo_section_value != $this->_group_switch) {
390 $query .= '
391 LEFT JOIN '. $this->_db_table_prefix .'axo_map ax ON ax.acl_id=a.id';
395 * if there are no aro groups, don't bother doing the join.
397 if (isset($sql_aro_group_ids)) {
398 $query .= '
399 LEFT JOIN '. $this->_db_table_prefix .'aro_groups_map arg ON arg.acl_id=a.id
400 LEFT JOIN '. $this->_db_table_prefix .'aro_groups rg ON rg.id=arg.group_id';
403 // this join is necessary to weed out rules associated with axo groups
404 $query .= '
405 LEFT JOIN '. $this->_db_table_prefix .'axo_groups_map axg ON axg.acl_id=a.id';
408 * if there are no axo groups, don't bother doing the join.
409 * it is only used to rank by the level of the group.
411 if (isset($sql_axo_group_ids)) {
412 $query .= '
413 LEFT JOIN '. $this->_db_table_prefix .'axo_groups xg ON xg.id=axg.group_id';
416 //Move the below line to the LEFT JOIN above for PostgreSQL's sake.
417 //AND ac.acl_id=a.id
418 $query .= '
419 WHERE a.enabled=1
420 AND (ac.section_value='. $this->db->quote($aco_section_value) .' AND ac.value='. $this->db->quote($aco_value) .')';
422 // if we are querying an aro group
423 if ($aro_section_value == $this->_group_switch) {
424 // if acl_get_groups did not return an array
425 if ( !isset ($sql_aro_group_ids) ) {
426 $this->debug_text ('acl_query(): Invalid ARO Group: '. $aro_value);
427 return FALSE;
430 $query .= '
431 AND rg.id IN ('. $sql_aro_group_ids .')';
433 $order_by[] = '(rg.rgt-rg.lft) ASC';
434 } else {
435 $query .= '
436 AND ((ar.section_value='. $this->db->quote($aro_section_value) .' AND ar.value='. $this->db->quote($aro_value) .')';
438 if ( isset ($sql_aro_group_ids) ) {
439 $query .= ' OR rg.id IN ('. $sql_aro_group_ids .')';
441 $order_by[] = '(CASE WHEN ar.value IS NULL THEN 0 ELSE 1 END) DESC';
442 $order_by[] = '(rg.rgt-rg.lft) ASC';
445 $query .= ')';
449 // if we are querying an axo group
450 if ($axo_section_value == $this->_group_switch) {
451 // if acl_get_groups did not return an array
452 if ( !isset ($sql_axo_group_ids) ) {
453 $this->debug_text ('acl_query(): Invalid AXO Group: '. $axo_value);
454 return FALSE;
457 $query .= '
458 AND xg.id IN ('. $sql_axo_group_ids .')';
460 $order_by[] = '(xg.rgt-xg.lft) ASC';
461 } else {
462 $query .= '
463 AND (';
465 if ($axo_section_value == '' AND $axo_value == '') {
466 $query .= '(ax.section_value IS NULL AND ax.value IS NULL)';
467 } else {
468 $query .= '(ax.section_value='. $this->db->quote($axo_section_value) .' AND ax.value='. $this->db->quote($axo_value) .')';
471 if (isset($sql_axo_group_ids)) {
472 $query .= ' OR xg.id IN ('. $sql_axo_group_ids .')';
474 $order_by[] = '(CASE WHEN ax.value IS NULL THEN 0 ELSE 1 END) DESC';
475 $order_by[] = '(xg.rgt-xg.lft) ASC';
476 } else {
477 $query .= ' AND axg.group_id IS NULL';
480 $query .= ')';
484 * The ordering is always very tricky and makes all the difference in the world.
485 * Order (ar.value IS NOT NULL) DESC should put ACLs given to specific AROs
486 * ahead of any ACLs given to groups. This works well for exceptions to groups.
487 * If the $return_all parameter is set to TRUE, then will return the entire
488 * array of applicable ACL information (this option was added by OpenEMR)
491 $order_by[] = 'a.updated_date DESC';
493 $query .= '
494 ORDER BY '. implode (',', $order_by) . '
497 // we are only interested in the first row unless $return_all is set
498 if ($return_all) {
499 $rs = $this->db->Execute($query);
501 else {
502 $rs = $this->db->SelectLimit($query, 1);
505 if (!is_object($rs)) {
506 $this->debug_db('acl_query');
507 return FALSE;
510 if ($return_all) {
511 while ($arr = $rs->FetchRow()) {
512 $row[] = $arr;
515 else {
516 $row = $rs->FetchRow();
521 * Return ACL ID. This is the key to "hooking" extras like pricing assigned to ACLs etc... Very useful.
523 if (isset($row) && is_array($row)) {
525 if ($return_all) {
526 foreach ($row as $single_row) {
527 $allow = FALSE;
528 if ( isset($single_row[1]) AND $single_row[1] == 1 ) {
529 $allow = TRUE;
531 $retarr[] = array('acl_id' => &$single_row[0], 'return_value' => &$single_row[2], 'allow' => $allow);
534 else {
535 $allow = FALSE;
536 if ( isset($row[1]) AND $row[1] == 1 ) {
537 $allow = TRUE;
539 $retarr = array('acl_id' => &$row[0], 'return_value' => &$row[2], 'allow' => $allow);
541 } else {
542 if ($return_all) {
543 // Permission denied.
544 $retarr[] = array('acl_id' => NULL, 'return_value' => NULL, 'allow' => FALSE);
546 else {
547 // Permission denied.
548 $retarr = array('acl_id' => NULL, 'return_value' => NULL, 'allow' => FALSE);
553 * Return the query that we ran if in debug mode.
555 if ($debug == TRUE) {
556 $retarr['query'] = &$query;
559 //Cache data.
560 $this->put_cache($retarr, $cache_id);
563 if ($return_all)
565 $this->debug_text("<b>acl_query():</b> ACO Section: $aco_section_value ACO Value: $aco_value ARO Section: $aro_section_value ARO Value $aro_value ACL ID: OMITTED due to return_all");
567 else
569 $this->debug_text("<b>acl_query():</b> ACO Section: $aco_section_value ACO Value: $aco_value ARO Section: $aro_section_value ARO Value $aro_value ACL ID: ". $retarr['acl_id'] .' Result: '. $retarr['allow']);
572 return $retarr;
576 * Grabs all groups mapped to an ARO. You can also specify a root_group for subtree'ing.
577 * @param string The section value or the ARO or ACO
578 * @param string The value of the ARO or ACO
579 * @param integer The group id of the group to start at (optional)
580 * @param string The type of group, either ARO or AXO (optional)
582 function acl_get_groups($section_value, $value, $root_group=NULL, $group_type='ARO') {
584 switch(strtolower($group_type)) {
585 case 'axo':
586 $group_type = 'axo';
587 $object_table = $this->_db_table_prefix .'axo';
588 $group_table = $this->_db_table_prefix .'axo_groups';
589 $group_map_table = $this->_db_table_prefix .'groups_axo_map';
590 break;
591 default:
592 $group_type = 'aro';
593 $object_table = $this->_db_table_prefix .'aro';
594 $group_table = $this->_db_table_prefix .'aro_groups';
595 $group_map_table = $this->_db_table_prefix .'groups_aro_map';
596 break;
599 //$profiler->startTimer( "acl_get_groups()");
601 //Generate unique cache id.
602 $cache_id = 'acl_get_groups_'.$section_value.'-'.$value.'-'.$root_group.'-'.$group_type;
604 $retarr = $this->get_cache($cache_id);
606 if (!$retarr) {
608 // Make sure we get the groups
609 $query = '
610 SELECT DISTINCT g2.id';
612 if ($section_value == $this->_group_switch) {
613 $query .= '
614 FROM ' . $group_table . ' g1,' . $group_table . ' g2';
616 $where = '
617 WHERE g1.value=' . $this->db->quote( $value );
618 } else {
619 $query .= '
620 FROM '. $object_table .' o,'. $group_map_table .' gm,'. $group_table .' g1,'. $group_table .' g2';
622 $where = '
623 WHERE (o.section_value='. $this->db->quote($section_value) .' AND o.value='. $this->db->quote($value) .')
624 AND gm.'. $group_type .'_id=o.id
625 AND g1.id=gm.group_id';
629 * If root_group_id is specified, we have to narrow this query down
630 * to just groups deeper in the tree then what is specified.
631 * This essentially creates a virtual "subtree" and ignores all outside groups.
632 * Useful for sites like sourceforge where you may seperate groups by "project".
634 if ( $root_group != '') {
635 //It is important to note the below line modifies the tables being selected.
636 //This is the reason for the WHERE variable.
637 $query .= ','. $group_table .' g3';
639 $where .= '
640 AND g3.value='. $this->db->quote( $root_group ) .'
641 AND ((g2.lft BETWEEN g3.lft AND g1.lft) AND (g2.rgt BETWEEN g1.rgt AND g3.rgt))';
642 } else {
643 $where .= '
644 AND (g2.lft <= g1.lft AND g2.rgt >= g1.rgt)';
647 $query .= $where;
649 // $this->debug_text($query);
650 $rs = $this->db->Execute($query);
652 if (!is_object($rs)) {
653 $this->debug_db('acl_get_groups');
654 return FALSE;
657 $retarr = array();
659 //Unbuffered query?
660 while (!$rs->EOF) {
661 $retarr[] = reset($rs->fields);
662 $rs->MoveNext();
665 //Cache data.
666 $this->put_cache($retarr, $cache_id);
669 return $retarr;
673 * Uses PEAR's Cache_Lite package to grab cached arrays, objects, variables etc...
674 * using unserialize() so it can handle more then just text string.
675 * @param string The id of the cached object
676 * @return mixed The cached object, otherwise FALSE if the object identifier was not found
678 function get_cache($cache_id) {
680 if ( $this->_caching == TRUE ) {
681 $this->debug_text("get_cache(): on ID: $cache_id");
683 if ( is_string($this->Cache_Lite->get($cache_id) ) ) {
684 return unserialize($this->Cache_Lite->get($cache_id) );
688 return false;
692 * Uses PEAR's Cache_Lite package to write cached arrays, objects, variables etc...
693 * using serialize() so it can handle more then just text string.
694 * @param mixed A variable to cache
695 * @param string The id of the cached variable
697 function put_cache($data, $cache_id) {
699 if ( $this->_caching == TRUE ) {
700 $this->debug_text("put_cache(): Cache MISS on ID: $cache_id");
702 return $this->Cache_Lite->save(serialize($data), $cache_id);
705 return false;