Support for larger size codes (such as SNOMED US Extension codes)
[openemr.git] / gacl / gacl.class.php
blob48fc9b7b99f2ebe667a95375476edee05ac5664c
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.
37 if ( !defined('ADODB_DIR') ) {
38 define('ADODB_DIR', dirname(__FILE__).'/adodb');
41 //openemr configuration file - bm - 05-2009
42 // to collect sql database login info and the utf8 flag
43 include_once(dirname(__FILE__).'/../library/sqlconf.php');
45 /**
46 * phpGACL main class
48 * Class gacl should be used in applications where only querying the phpGACL
49 * database is required.
51 * @package phpGACL
52 * @author Mike Benoit <ipso@snappymail.ca>
54 class gacl {
56 --- phpGACL Configuration path/file ---
58 var $config_file = '';
61 --- Private properties ---
63 /** @var boolean Enables Debug output if true */
64 var $_debug = FALSE;
67 --- Database configuration. ---
69 /** @var string Prefix for all the phpgacl tables in the database */
70 var $_db_table_prefix = 'gacl_';
72 /** @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 */
73 var $_db_type = 'mysql';
75 /** @var string The database server */
76 var $_db_host = '';
78 /** @var string The database user name */
79 var $_db_user = '';
81 /** @var string The database user password */
82 var $_db_password = '';
84 /** @var string The database name */
85 var $_db_name = '';
87 /** @var object An ADODB database connector object */
88 var $_db = '';
90 /** @var boolean The utf8 encoding flag - bm 05-2009 */
91 var $_db_utf8_flag = '';
94 * NOTE: This cache must be manually cleaned each time ACL's are modified.
95 * Alternatively you could wait for the cache to expire.
98 /** @var boolean Caches queries if true */
99 var $_caching = FALSE;
101 /** @var boolean Force cache to expire */
102 var $_force_cache_expire = TRUE;
104 /** @var string The directory for cache file to eb written (ensure write permission are set) */
105 var $_cache_dir = '/tmp/phpgacl_cache'; // NO trailing slash
107 /** @var int The time for the cache to expire in seconds - 600 == Ten Minutes */
108 var $_cache_expire_time=600;
110 /** @var string A switch to put acl_check into '_group_' mode */
111 var $_group_switch = '_group_';
114 * Constructor
115 * @param array An arry of options to oeverride the class defaults
117 function gacl($options = NULL) {
119 $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');
121 //Values supplied in $options array overwrite those in the config file.
122 if ( file_exists($this->config_file) ) {
123 $config = parse_ini_file($this->config_file);
125 if ( is_array($config) ) {
126 $gacl_options = array_merge($config, $options);
129 unset($config);
132 if (is_array($options)) {
133 foreach ($options as $key => $value) {
134 $this->debug_text("Option: $key");
136 if (in_array($key, $available_options) ) {
137 $this->debug_text("Valid Config options: $key");
138 $property = '_'.$key;
139 $this->$property = $value;
140 } else {
141 $this->debug_text("ERROR: Config option: $key is not a valid option");
146 //collect openemr sql info from include at top of script - bm 05-2009
147 global $sqlconf, $disable_utf8_flag;
148 $this->_db_host = $sqlconf["host"];
149 $this->_db_user = $sqlconf["login"];
150 $this->_db_password = $sqlconf["pass"];
151 $this->_db_name = $sqlconf["dbase"];
152 if (!$disable_utf8_flag) {
153 $utf8_flag = true;
155 else {
156 $utf8_flag = false;
158 $this->_db_utf8_flag = $utf8_flag;
160 require_once( ADODB_DIR .'/adodb.inc.php');
161 require_once( ADODB_DIR .'/adodb-pager.inc.php');
163 if (is_object($this->_db)) {
164 $this->db = &$this->_db;
165 } else {
166 $this->db = ADONewConnection($this->_db_type);
167 //Use NUM for slight performance/memory reasons.
168 $this->db->SetFetchMode(ADODB_FETCH_NUM);
169 $this->db->PConnect($this->_db_host, $this->_db_user, $this->_db_password, $this->_db_name);
171 // Modified 5/2009 by BM for UTF-8 project
172 if ($this->_db_utf8_flag) {
173 $success_flag = $this->db->Execute("SET NAMES 'utf8'");
174 if (!$success_flag) {
175 error_log("PHP custom error: from gacl gacl/gacl.class.php - Unable to set up UTF8 encoding with mysql database".$this->db->ErrorMsg(), 0);
178 // ---------------------------------------
181 $this->db->debug = $this->_debug;
183 if ( $this->_caching == TRUE ) {
184 if (!class_exists('Hashed_Cache_Lite')) {
185 require_once(dirname(__FILE__) .'/Cache_Lite/Hashed_Cache_Lite.php');
189 * Cache options. We default to the highest performance. If you run in to cache corruption problems,
190 * Change all the 'false' to 'true', this will slow things down slightly however.
193 $cache_options = array(
194 'caching' => $this->_caching,
195 'cacheDir' => $this->_cache_dir.'/',
196 'lifeTime' => $this->_cache_expire_time,
197 'fileLocking' => TRUE,
198 'writeControl' => FALSE,
199 'readControl' => FALSE,
200 'memoryCaching' => TRUE,
201 'automaticSerialization' => FALSE
203 $this->Cache_Lite = new Hashed_Cache_Lite($cache_options);
206 return true;
210 * Prints debug text if debug is enabled.
211 * @param string THe text to output
212 * @return boolean Always returns true
214 function debug_text($text) {
216 if ($this->_debug) {
217 echo "$text<br>\n";
220 return true;
224 * Prints database debug text if debug is enabled.
225 * @param string The name of the function calling this method
226 * @return string Returns an error message
228 function debug_db($function_name = '') {
229 if ($function_name != '') {
230 $function_name .= ' (): ';
233 return $this->debug_text ($function_name .'database error: '. $this->db->ErrorMsg() .' ('. $this->db->ErrorNo() .')');
237 * Wraps the actual acl_query() function.
239 * It is simply here to return TRUE/FALSE accordingly.
240 * @param string The ACO section value
241 * @param string The ACO value
242 * @param string The ARO section value
243 * @param string The ARO section
244 * @param string The AXO section value (optional)
245 * @param string The AXO section value (optional)
246 * @param integer The group id of the ARO ??Mike?? (optional)
247 * @param integer The group id of the AXO ??Mike?? (optional)
248 * @return boolean TRUE if the check succeeds, false if not.
250 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) {
251 $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);
253 return $acl_result['allow'];
257 * Wraps the actual acl_query() function.
259 * Quick access to the return value of an ACL.
260 * @param string The ACO section value
261 * @param string The ACO value
262 * @param string The ARO section value
263 * @param string The ARO section
264 * @param string The AXO section value (optional)
265 * @param string The AXO section value (optional)
266 * @param integer The group id of the ARO (optional)
267 * @param integer The group id of the AXO (optional)
268 * @return string The return value of the ACL
270 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) {
271 $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);
273 return $acl_result['return_value'];
277 * Handles ACL lookups over arrays of AROs
278 * @param string The ACO section value
279 * @param string The ACO value
280 * @param array An named array of arrays, each element in the format aro_section_value=>array(aro_value1,aro_value1,...)
281 * @return mixed The same data format as inputted.
282 \*======================================================================*/
283 function acl_check_array($aco_section_value, $aco_value, $aro_array) {
285 Input Array:
286 Section => array(Value, Value, Value),
287 Section => array(Value, Value, Value)
291 if (!is_array($aro_array)) {
292 $this->debug_text("acl_query_array(): ARO Array must be passed");
293 return false;
296 foreach($aro_array as $aro_section_value => $aro_value_array) {
297 foreach ($aro_value_array as $aro_value) {
298 $this->debug_text("acl_query_array(): ARO Section Value: $aro_section_value ARO VALUE: $aro_value");
300 if( $this->acl_check($aco_section_value, $aco_value, $aro_section_value, $aro_value) ) {
301 $this->debug_text("acl_query_array(): ACL_CHECK True");
302 $retarr[$aro_section_value][] = $aro_value;
303 } else {
304 $this->debug_text("acl_query_array(): ACL_CHECK False");
309 return $retarr;
314 * The Main function that does the actual ACL lookup.
315 * @param string The ACO section value
316 * @param string The ACO value
317 * @param string The ARO section value
318 * @param string The ARO section
319 * @param string The AXO section value (optional)
320 * @param string The AXO section value (optional)
321 * @param string The value of the ARO group (optional)
322 * @param string The value of the AXO group (optional)
323 * @param boolean Debug the operation if true (optional)
324 * @param boolean Option to return all applicable ACL's rather than just one. (optional) (Added by OpenEMR)
325 * @return array Returns as much information as possible about the ACL so other functions can trim it down and omit unwanted data.
327 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) {
329 $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;
331 $retarr = $this->get_cache($cache_id);
333 if (!$retarr) {
335 * Grab all groups mapped to this ARO/AXO
337 $aro_group_ids = $this->acl_get_groups($aro_section_value, $aro_value, $root_aro_group, 'ARO');
339 if (is_array($aro_group_ids) AND !empty($aro_group_ids)) {
340 $sql_aro_group_ids = implode(',', $aro_group_ids);
343 if ($axo_section_value != '' AND $axo_value != '') {
344 $axo_group_ids = $this->acl_get_groups($axo_section_value, $axo_value, $root_axo_group, 'AXO');
346 if (is_array($axo_group_ids) AND !empty($axo_group_ids)) {
347 $sql_axo_group_ids = implode(',', $axo_group_ids);
352 * This query is where all the magic happens.
353 * The ordering is very important here, as well very tricky to get correct.
354 * Currently there can be duplicate ACLs, or ones that step on each other toes. In this case, the ACL that was last updated/created
355 * is used; unless the $return_all parameter is set to TRUE, then will return the entire array of applicable ACL information (this
356 * option was added by OpenEMR)
358 * This is probably where the most optimizations can be made.
361 $order_by = array();
363 $query = '
364 SELECT a.id,a.allow,a.return_value
365 FROM '. $this->_db_table_prefix .'acl a
366 LEFT JOIN '. $this->_db_table_prefix .'aco_map ac ON ac.acl_id=a.id';
368 if ($aro_section_value != $this->_group_switch) {
369 $query .= '
370 LEFT JOIN '. $this->_db_table_prefix .'aro_map ar ON ar.acl_id=a.id';
373 if ($axo_section_value != $this->_group_switch) {
374 $query .= '
375 LEFT JOIN '. $this->_db_table_prefix .'axo_map ax ON ax.acl_id=a.id';
379 * if there are no aro groups, don't bother doing the join.
381 if (isset($sql_aro_group_ids)) {
382 $query .= '
383 LEFT JOIN '. $this->_db_table_prefix .'aro_groups_map arg ON arg.acl_id=a.id
384 LEFT JOIN '. $this->_db_table_prefix .'aro_groups rg ON rg.id=arg.group_id';
387 // this join is necessary to weed out rules associated with axo groups
388 $query .= '
389 LEFT JOIN '. $this->_db_table_prefix .'axo_groups_map axg ON axg.acl_id=a.id';
392 * if there are no axo groups, don't bother doing the join.
393 * it is only used to rank by the level of the group.
395 if (isset($sql_axo_group_ids)) {
396 $query .= '
397 LEFT JOIN '. $this->_db_table_prefix .'axo_groups xg ON xg.id=axg.group_id';
400 //Move the below line to the LEFT JOIN above for PostgreSQL's sake.
401 //AND ac.acl_id=a.id
402 $query .= '
403 WHERE a.enabled=1
404 AND (ac.section_value='. $this->db->quote($aco_section_value) .' AND ac.value='. $this->db->quote($aco_value) .')';
406 // if we are querying an aro group
407 if ($aro_section_value == $this->_group_switch) {
408 // if acl_get_groups did not return an array
409 if ( !isset ($sql_aro_group_ids) ) {
410 $this->debug_text ('acl_query(): Invalid ARO Group: '. $aro_value);
411 return FALSE;
414 $query .= '
415 AND rg.id IN ('. $sql_aro_group_ids .')';
417 $order_by[] = '(rg.rgt-rg.lft) ASC';
418 } else {
419 $query .= '
420 AND ((ar.section_value='. $this->db->quote($aro_section_value) .' AND ar.value='. $this->db->quote($aro_value) .')';
422 if ( isset ($sql_aro_group_ids) ) {
423 $query .= ' OR rg.id IN ('. $sql_aro_group_ids .')';
425 $order_by[] = '(CASE WHEN ar.value IS NULL THEN 0 ELSE 1 END) DESC';
426 $order_by[] = '(rg.rgt-rg.lft) ASC';
429 $query .= ')';
433 // if we are querying an axo group
434 if ($axo_section_value == $this->_group_switch) {
435 // if acl_get_groups did not return an array
436 if ( !isset ($sql_axo_group_ids) ) {
437 $this->debug_text ('acl_query(): Invalid AXO Group: '. $axo_value);
438 return FALSE;
441 $query .= '
442 AND xg.id IN ('. $sql_axo_group_ids .')';
444 $order_by[] = '(xg.rgt-xg.lft) ASC';
445 } else {
446 $query .= '
447 AND (';
449 if ($axo_section_value == '' AND $axo_value == '') {
450 $query .= '(ax.section_value IS NULL AND ax.value IS NULL)';
451 } else {
452 $query .= '(ax.section_value='. $this->db->quote($axo_section_value) .' AND ax.value='. $this->db->quote($axo_value) .')';
455 if (isset($sql_axo_group_ids)) {
456 $query .= ' OR xg.id IN ('. $sql_axo_group_ids .')';
458 $order_by[] = '(CASE WHEN ax.value IS NULL THEN 0 ELSE 1 END) DESC';
459 $order_by[] = '(xg.rgt-xg.lft) ASC';
460 } else {
461 $query .= ' AND axg.group_id IS NULL';
464 $query .= ')';
468 * The ordering is always very tricky and makes all the difference in the world.
469 * Order (ar.value IS NOT NULL) DESC should put ACLs given to specific AROs
470 * ahead of any ACLs given to groups. This works well for exceptions to groups.
471 * If the $return_all parameter is set to TRUE, then will return the entire
472 * array of applicable ACL information (this option was added by OpenEMR)
475 $order_by[] = 'a.updated_date DESC';
477 $query .= '
478 ORDER BY '. implode (',', $order_by) . '
481 // we are only interested in the first row unless $return_all is set
482 if ($return_all) {
483 $rs = $this->db->Execute($query);
485 else {
486 $rs = $this->db->SelectLimit($query, 1);
489 if (!is_object($rs)) {
490 $this->debug_db('acl_query');
491 return FALSE;
494 if ($return_all) {
495 while ($arr =& $rs->fetchRow()) {
496 $row[] = $arr;
499 else {
500 $row =& $rs->FetchRow();
505 * Return ACL ID. This is the key to "hooking" extras like pricing assigned to ACLs etc... Very useful.
507 if (is_array($row)) {
509 if ($return_all) {
510 foreach ($row as $single_row) {
511 if ( isset($single_row[1]) AND $single_row[1] == 1 ) {
512 $allow = TRUE;
513 } else {
514 $allow = FALSE;
516 $retarr[] = array('acl_id' => &$single_row[0], 'return_value' => &$single_row[2], 'allow' => $allow);
519 else {
520 if ( isset($row[1]) AND $row[1] == 1 ) {
521 $allow = TRUE;
522 } else {
523 $allow = FALSE;
525 $retarr = array('acl_id' => &$row[0], 'return_value' => &$row[2], 'allow' => $allow);
527 } else {
528 if ($return_all) {
529 // Permission denied.
530 $retarr[] = array('acl_id' => NULL, 'return_value' => NULL, 'allow' => FALSE);
532 else {
533 // Permission denied.
534 $retarr = array('acl_id' => NULL, 'return_value' => NULL, 'allow' => FALSE);
539 * Return the query that we ran if in debug mode.
541 if ($debug == TRUE) {
542 $retarr['query'] = &$query;
545 //Cache data.
546 $this->put_cache($retarr, $cache_id);
549 $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']);
550 return $retarr;
554 * Grabs all groups mapped to an ARO. You can also specify a root_group for subtree'ing.
555 * @param string The section value or the ARO or ACO
556 * @param string The value of the ARO or ACO
557 * @param integer The group id of the group to start at (optional)
558 * @param string The type of group, either ARO or AXO (optional)
560 function acl_get_groups($section_value, $value, $root_group=NULL, $group_type='ARO') {
562 switch(strtolower($group_type)) {
563 case 'axo':
564 $group_type = 'axo';
565 $object_table = $this->_db_table_prefix .'axo';
566 $group_table = $this->_db_table_prefix .'axo_groups';
567 $group_map_table = $this->_db_table_prefix .'groups_axo_map';
568 break;
569 default:
570 $group_type = 'aro';
571 $object_table = $this->_db_table_prefix .'aro';
572 $group_table = $this->_db_table_prefix .'aro_groups';
573 $group_map_table = $this->_db_table_prefix .'groups_aro_map';
574 break;
577 //$profiler->startTimer( "acl_get_groups()");
579 //Generate unique cache id.
580 $cache_id = 'acl_get_groups_'.$section_value.'-'.$value.'-'.$root_group.'-'.$group_type;
582 $retarr = $this->get_cache($cache_id);
584 if (!$retarr) {
586 // Make sure we get the groups
587 $query = '
588 SELECT DISTINCT g2.id';
590 if ($section_value == $this->_group_switch) {
591 $query .= '
592 FROM ' . $group_table . ' g1,' . $group_table . ' g2';
594 $where = '
595 WHERE g1.value=' . $this->db->quote( $value );
596 } else {
597 $query .= '
598 FROM '. $object_table .' o,'. $group_map_table .' gm,'. $group_table .' g1,'. $group_table .' g2';
600 $where = '
601 WHERE (o.section_value='. $this->db->quote($section_value) .' AND o.value='. $this->db->quote($value) .')
602 AND gm.'. $group_type .'_id=o.id
603 AND g1.id=gm.group_id';
607 * If root_group_id is specified, we have to narrow this query down
608 * to just groups deeper in the tree then what is specified.
609 * This essentially creates a virtual "subtree" and ignores all outside groups.
610 * Useful for sites like sourceforge where you may seperate groups by "project".
612 if ( $root_group != '') {
613 //It is important to note the below line modifies the tables being selected.
614 //This is the reason for the WHERE variable.
615 $query .= ','. $group_table .' g3';
617 $where .= '
618 AND g3.value='. $this->db->quote( $root_group ) .'
619 AND ((g2.lft BETWEEN g3.lft AND g1.lft) AND (g2.rgt BETWEEN g1.rgt AND g3.rgt))';
620 } else {
621 $where .= '
622 AND (g2.lft <= g1.lft AND g2.rgt >= g1.rgt)';
625 $query .= $where;
627 // $this->debug_text($query);
628 $rs = $this->db->Execute($query);
630 if (!is_object($rs)) {
631 $this->debug_db('acl_get_groups');
632 return FALSE;
635 $retarr = array();
637 //Unbuffered query?
638 while (!$rs->EOF) {
639 $retarr[] = reset($rs->fields);
640 $rs->MoveNext();
643 //Cache data.
644 $this->put_cache($retarr, $cache_id);
647 return $retarr;
651 * Uses PEAR's Cache_Lite package to grab cached arrays, objects, variables etc...
652 * using unserialize() so it can handle more then just text string.
653 * @param string The id of the cached object
654 * @return mixed The cached object, otherwise FALSE if the object identifier was not found
656 function get_cache($cache_id) {
658 if ( $this->_caching == TRUE ) {
659 $this->debug_text("get_cache(): on ID: $cache_id");
661 if ( is_string($this->Cache_Lite->get($cache_id) ) ) {
662 return unserialize($this->Cache_Lite->get($cache_id) );
666 return false;
670 * Uses PEAR's Cache_Lite package to write cached arrays, objects, variables etc...
671 * using serialize() so it can handle more then just text string.
672 * @param mixed A variable to cache
673 * @param string The id of the cached variable
675 function put_cache($data, $cache_id) {
677 if ( $this->_caching == TRUE ) {
678 $this->debug_text("put_cache(): Cache MISS on ID: $cache_id");
680 return $this->Cache_Lite->save(serialize($data), $cache_id);
683 return false;