source: trunk/lib/ACL.inc.php @ 505

Last change on this file since 505 was 502, checked in by anonymous, 9 years ago

Many minor fixes during pulso development

File size: 30.0 KB
RevLine 
[171]1<?php
[362]2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
[396]5 * Copyright 2001-2012 Strangecode, LLC
[457]6 *
[362]7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
[457]13 *
[362]14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
[457]18 *
[362]19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
[171]23/*
24* ACL.inc.php
[457]25*
[171]26* Uses the ARO/ACO/AXO model of Access Control Lists.
[173]27* Uses Modified Preorder Tree Traversal to maintain a tree-structure.
28* See: http://www.sitepoint.com/print/hierarchical-data-database
[174]29* Includes a command-line tool for managing rights (codebase/bin/acl.cli.php).
[362]30*
[457]31*
[171]32* @author   Quinn Comendant <quinn@strangecode.com>
33* @version  1.0
34* @since    14 Jun 2006 22:35:11
35*/
36
[172]37require_once dirname(__FILE__) . '/Cache.inc.php';
38
[502]39class ACL
40{
[171]41
[468]42    // A place to keep an object instance for the singleton pattern.
[484]43    protected static $instance = null;
[468]44
[171]45    // Configuration parameters for this object.
[484]46    protected $_params = array(
[334]47        // If false nothing will be cached or retrieved. Useful for testing realtime data requests.
[172]48        'enable_cache' => true,
[171]49
50        // Automatically create table and verify columns. Better set to false after site launch.
51        'create_table' => false,
[502]52
53        // Maximum allowed length of names.
54        // This value can be increased only if {aro,aco,axo}_tbl.name VARCHAR length is increased.
55        'name_max_length' => 32.
[171]56    );
57
58    /**
[174]59     * Constructor.
[171]60     */
[468]61    public function __construct()
[171]62    {
[479]63        $app =& App::getInstance();
[171]64
[172]65        // Configure the cache object.
66        $this->cache = new Cache('acl');
67        $this->cache->setParam(array('enabled' => true));
68
[171]69        // Get create tables config from global context.
70        if (!is_null($app->getParam('db_create_tables'))) {
71            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
72        }
73    }
74
75    /**
76     * This method enforces the singleton pattern for this class.
77     *
78     * @return  object  Reference to the global ACL object.
79     * @access  public
80     * @static
81     */
[468]82    public static function &getInstance()
[171]83    {
[468]84        if (self::$instance === null) {
85            self::$instance = new self();
[171]86        }
87
[468]88        return self::$instance;
[171]89    }
90
91    /**
92     * Set (or overwrite existing) parameters by passing an array of new parameters.
93     *
94     * @access public
95     *
96     * @param  array    $params     Array of parameters (key => val pairs).
97     */
[468]98    public function setParam($params)
[171]99    {
[479]100        $app =& App::getInstance();
[457]101
[171]102        if (isset($params) && is_array($params)) {
103            // Merge new parameters with old overriding only those passed.
104            $this->_params = array_merge($this->_params, $params);
105        } else {
106            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
107        }
108    }
109
110    /**
111     * Return the value of a parameter, if it exists.
112     *
113     * @access public
114     * @param string $param        Which parameter to return.
115     * @return mixed               Configured parameter value.
116     */
[468]117    public function getParam($param)
[171]118    {
[479]119        $app =& App::getInstance();
[457]120
[478]121        if (array_key_exists($param, $this->_params)) {
[171]122            return $this->_params[$param];
123        } else {
[420]124            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
[171]125            return null;
126        }
127    }
128
129    /**
[174]130     * Setup the database tables for this class.
[171]131     *
132     * @access  public
133     * @author  Quinn Comendant <quinn@strangecode.com>
134     * @since   04 Jun 2006 16:41:42
135     */
[468]136    public function initDB($recreate_db=false)
[171]137    {
[479]138        $app =& App::getInstance();
139        $db =& DB::getInstance();
[171]140
141        static $_db_tested = false;
142
143        if ($recreate_db || !$_db_tested && $this->getParam('create_table')) {
144
145            if ($recreate_db) {
146                $db->query("DROP TABLE IF EXISTS acl_tbl");
147                $db->query("DROP TABLE IF EXISTS aro_tbl");
148                $db->query("DROP TABLE IF EXISTS aco_tbl");
149                $db->query("DROP TABLE IF EXISTS axo_tbl");
[201]150                $app->logMsg(sprintf('Dropping and recreating tables acl_tbl, aro_tbl, aco_tbl, axo_tbl.', null), LOG_INFO, __FILE__, __LINE__);
[171]151            }
[457]152
[171]153            // acl_tbl
[173]154            $db->query("
155                CREATE TABLE IF NOT EXISTS acl_tbl (
[502]156                    aro_id SMALLINT UNSIGNED NOT NULL DEFAULT '0',
157                    aco_id SMALLINT UNSIGNED NOT NULL DEFAULT '0',
158                    axo_id SMALLINT UNSIGNED NOT NULL DEFAULT '0',
[171]159                    access ENUM('allow', 'deny') DEFAULT NULL,
160                    added_datetime DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
161                    UNIQUE KEY (aro_id, aco_id, axo_id),
162                    KEY (access)
163                ) ENGINE=MyISAM
164            ");
165            if (!$db->columnExists('acl_tbl', array(
166                'aro_id',
167                'aco_id',
168                'axo_id',
169                'access',
170                'added_datetime',
171            ), false, false)) {
172                $app->logMsg(sprintf('Database table acl_tbl has invalid columns. Please update this table manually.', null), LOG_ALERT, __FILE__, __LINE__);
173                trigger_error(sprintf('Database table acl_tbl has invalid columns. Please update this table manually.', null), E_USER_ERROR);
[173]174            } else {
175                // Insert root node data if nonexistant, dely all by default.
176                $qid = $db->query("SELECT 1 FROM acl_tbl");
177                if (mysql_num_rows($qid) == 0) {
[457]178                    $qid = $db->query("REPLACE INTO acl_tbl VALUES ('1', '1', '1', 'deny', NOW())");
179                }
[171]180            }
181
[173]182            // aro_tbl, aco_tbl, axo_tbl
[171]183            foreach (array('aro', 'aco', 'axo') as $a_o) {
[173]184                $db->query("
185                    CREATE TABLE IF NOT EXISTS {$a_o}_tbl (
[171]186                        {$a_o}_id SMALLINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
[502]187                        name VARCHAR(" . $this->getParam('name_max_length') . ") NOT NULL DEFAULT '',
188                        lft MEDIUMINT UNSIGNED NOT NULL DEFAULT '0',
189                        rgt MEDIUMINT UNSIGNED NOT NULL DEFAULT '0',
[171]190                        added_datetime DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
[173]191                        UNIQUE KEY name (name(15)),
[171]192                        KEY transversal (lft, rgt)
193                    ) ENGINE=MyISAM;
194                ");
195
196                if (!$db->columnExists("{$a_o}_tbl", array(
197                    "{$a_o}_id",
198                    'name',
199                    'lft',
200                    'rgt',
201                    'added_datetime',
202                ), false, false)) {
203                    $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', "{$a_o}_tbl"), LOG_ALERT, __FILE__, __LINE__);
204                    trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', "{$a_o}_tbl"), E_USER_ERROR);
[173]205                } else {
[334]206                    // Insert root node data if nonexistent.
[173]207                    $qid = $db->query("SELECT 1 FROM {$a_o}_tbl WHERE name = 'root'");
208                    if (mysql_num_rows($qid) == 0) {
[457]209                        $qid = $db->query("REPLACE INTO {$a_o}_tbl (name, lft, rgt, added_datetime) VALUES ('root', 1, 2, NOW())");
210                    }
[171]211                }
[173]212
[171]213            }
214        }
215        $_db_tested = true;
[172]216        return true;
[171]217    }
218
219    /*
[174]220    * Add a node to one of the aro/aco/axo tables.
[171]221    *
222    * @access   public
[174]223    * @param    string $name A unique identifier for the new node.
224    * @param    string $parent The name of the parent under-which to attach the new node.
225    * @param    string $type The tree to add to, one of: aro, aco, axo.
226    * @return   bool | int False on error, or the last_insert_id primary key of the new node.
[171]227    * @author   Quinn Comendant <quinn@strangecode.com>
228    * @version  1.0
229    * @since    14 Jun 2006 22:39:29
230    */
[468]231    public function add($name, $parent=null, $type)
[171]232    {
233        $app =& App::getInstance();
234        $db =& DB::getInstance();
[457]235
[171]236        $this->initDB();
[457]237
[171]238        switch ($type) {
239        case 'aro' :
240            $tbl = 'aro_tbl';
241            break;
242        case 'aco' :
243            $tbl = 'aco_tbl';
244            break;
245        case 'axo' :
246            $tbl = 'axo_tbl';
247            break;
248        default :
249            $app->logMsg(sprintf('Invalid access object type: %s', $type), LOG_ERR, __FILE__, __LINE__);
250            return false;
251            break;
252        }
[457]253
[171]254        // If $parent is null, use root object.
255        if (is_null($parent)) {
256            $parent = 'root';
257        }
[457]258
[171]259        // Ensure node and parent name aren't empty.
260        if ('' == trim($name) || '' == trim($parent)) {
261            $app->logMsg(sprintf('Cannot add node, parent (%s) or name (%s) missing.', $name, $parent), LOG_WARNING, __FILE__, __LINE__);
262            return false;
263        }
[457]264
[502]265        // Ensure node node name fits in the column size.
266        // This value can be increased if {aro,aco.axo}_tbl.name VARCHAR length is increased.
267        if (strlen(trim($name)) > $this->getParam('name_max_length')) {
268            $app->logMsg(sprintf('Cannot add node, %s character limit exceeded for name "%s"', $this->getParam('name_max_length'), $name, $parent), LOG_WARNING, __FILE__, __LINE__);
269            return false;
270        }
271
[171]272        // Ensure node is unique.
273        $qid = $db->query("SELECT 1 FROM $tbl WHERE name = '" . $db->escapeString($name) . "'");
274        if (mysql_num_rows($qid) > 0) {
[420]275            $app->logMsg(sprintf('Cannot add %s node, already exists: %s', $type, $name), LOG_INFO, __FILE__, __LINE__);
[171]276            return false;
277        }
[457]278
[171]279        // Select the rgt of $parent.
280        $qid = $db->query("SELECT rgt FROM $tbl WHERE name = '" . $db->escapeString($parent) . "'");
[174]281        if (!list($parent_rgt) = mysql_fetch_row($qid)) {
[334]282            $app->logMsg(sprintf('Cannot add %s node to nonexistent parent: %s', $type, $parent), LOG_WARNING, __FILE__, __LINE__);
[171]283            return false;
284        }
[174]285
[171]286        // Update transversal numbers for all nodes to the rgt of $parent.
[174]287        $db->query("UPDATE $tbl SET lft = lft + 2 WHERE lft >= $parent_rgt");
288        $db->query("UPDATE $tbl SET rgt = rgt + 2 WHERE rgt >= $parent_rgt");
[457]289
[171]290        // Insert new node just below parent. Lft is parent's old rgt.
291        $db->query("
[457]292            INSERT INTO $tbl (name, lft, rgt, added_datetime)
[174]293            VALUES ('" . $db->escapeString($name) . "', $parent_rgt, $parent_rgt + 1, NOW())
[171]294        ");
295
[201]296        $app->logMsg(sprintf('Added %s node %s to parent %s.', $type, $name, $parent), LOG_INFO, __FILE__, __LINE__);
[171]297        return mysql_insert_id($db->getDBH());
298    }
299
300    // Alias functions for the different object types.
[468]301    public function addRequestObject($name, $parent=null)
[171]302    {
303        return $this->add($name, $parent, 'aro');
304    }
[468]305    public function addControlObject($name, $parent=null)
[171]306    {
307        return $this->add($name, $parent, 'aco');
308    }
[468]309    public function addXtraObject($name, $parent=null)
[171]310    {
311        return $this->add($name, $parent, 'axo');
312    }
313
314    /*
[174]315    * Remove a node from one of the aro/aco/axo tables.
[171]316    *
317    * @access   public
[174]318    * @param    string $name The identifier for the node to remove.
319    * @param    string $type The tree to modify, one of: aro, aco, axo.
320    * @return   bool | int False on error, or true on success.
[171]321    * @author   Quinn Comendant <quinn@strangecode.com>
322    * @version  1.0
323    * @since    14 Jun 2006 22:39:29
324    */
[468]325    public function remove($name, $type)
[171]326    {
327        $app =& App::getInstance();
328        $db =& DB::getInstance();
[457]329
[171]330        $this->initDB();
331
332        switch ($type) {
333        case 'aro' :
334            $tbl = 'aro_tbl';
[174]335            $primary_key = 'aro_id';
[171]336            break;
337        case 'aco' :
338            $tbl = 'aco_tbl';
[174]339            $primary_key = 'aco_id';
[171]340            break;
341        case 'axo' :
342            $tbl = 'axo_tbl';
[174]343            $primary_key = 'axo_id';
[171]344            break;
345        default :
346            $app->logMsg(sprintf('Invalid access object type: %s', $type), LOG_ERR, __FILE__, __LINE__);
347            return false;
348            break;
349        }
[457]350
[171]351        // Ensure node name isn't empty.
352        if ('' == trim($name)) {
353            $app->logMsg(sprintf('Cannot add node, name missing.', null), LOG_WARNING, __FILE__, __LINE__);
354            return false;
355        }
[457]356
[174]357        // Select the lft and rgt of $name to use for selecting children and reordering transversals.
[171]358        $qid = $db->query("SELECT lft, rgt FROM $tbl WHERE name = '" . $db->escapeString($name) . "'");
359        if (!list($lft, $rgt) = mysql_fetch_row($qid)) {
[420]360            $app->logMsg(sprintf('Cannot delete nonexistent %s name: %s', $type, $name), LOG_WARNING, __FILE__, __LINE__);
[171]361            return false;
362        }
[457]363
[174]364        // Remove node and all children of node, as well as acl_tbl links.
365        $db->query("
[457]366            DELETE $tbl, acl_tbl
[174]367            FROM $tbl
368            LEFT JOIN acl_tbl ON ($tbl.$primary_key = acl_tbl.$primary_key)
369            WHERE $tbl.lft BETWEEN $lft AND $rgt
370        ");
[171]371        $num_deleted_nodes = mysql_affected_rows($db->getDBH());
372
373        // Update transversal numbers for all nodes to the rgt of $parent, taking in to account the absence of it's children.
374        $db->query("UPDATE $tbl SET lft = lft - ($rgt - $lft + 1) WHERE lft > $lft");
375        $db->query("UPDATE $tbl SET rgt = rgt - ($rgt - $lft + 1) WHERE rgt > $rgt");
376
[201]377        $app->logMsg(sprintf('Removed %s node %s along with %s children.', $type, $name, $num_deleted_nodes - 1), LOG_INFO, __FILE__, __LINE__);
[171]378        return true;
379    }
[457]380
[171]381    // Alias functions for the different object types.
[468]382    public function removeRequestObject($name)
[171]383    {
[174]384        return $this->remove($name, 'aro');
[171]385    }
[468]386    public function removeControlObject($name)
[171]387    {
[174]388        return $this->remove($name, 'aco');
[171]389    }
[468]390    public function removeXtraObject($name)
[171]391    {
[174]392        return $this->remove($name, 'axo');
[171]393    }
[174]394
395    /*
396    * Move a node to a new parent in one of the aro/aco/axo tables.
397    *
398    * @access   public
399    * @param    string $name The identifier for the node to remove.
400    * @param    string $new_parent The name of the parent under-which to attach the new node.
401    * @param    string $type The tree to modify, one of: aro, aco, axo.
402    * @return   bool | int False on error, or the last_insert_id primary key of the new node.
403    * @author   Quinn Comendant <quinn@strangecode.com>
404    * @version  1.0
405    * @since    14 Jun 2006 22:39:29
406    */
[468]407    public function move($name, $new_parent, $type)
[174]408    {
409        $app =& App::getInstance();
410        $db =& DB::getInstance();
[457]411
[174]412        $this->initDB();
413
414        switch ($type) {
415        case 'aro' :
416            $tbl = 'aro_tbl';
417            $primary_key = 'aro_id';
418            break;
419        case 'aco' :
420            $tbl = 'aco_tbl';
421            $primary_key = 'aco_id';
422            break;
423        case 'axo' :
424            $tbl = 'axo_tbl';
425            $primary_key = 'axo_id';
426            break;
427        default :
428            $app->logMsg(sprintf('Invalid access object type: %s', $type), LOG_ERR, __FILE__, __LINE__);
429            return false;
430            break;
431        }
[457]432
[189]433        // If $new_parent is null, use root object.
434        if (is_null($new_parent)) {
435            $new_parent = 'root';
[174]436        }
[457]437
[174]438        // Ensure node and parent name aren't empty.
[189]439        if ('' == trim($name) || '' == trim($new_parent)) {
440            $app->logMsg(sprintf('Cannot add node, parent (%s) or name (%s) missing.', $name, $new_parent), LOG_WARNING, __FILE__, __LINE__);
[174]441            return false;
442        }
[457]443
[174]444        // Select the lft and rgt of $name to use for selecting children and reordering transversals.
445        $qid = $db->query("SELECT lft, rgt FROM $tbl WHERE name = '" . $db->escapeString($name) . "'");
446        if (!list($lft, $rgt) = mysql_fetch_row($qid)) {
[420]447            $app->logMsg(sprintf('Cannot move nonexistent %s name: %s', $type, $name), LOG_WARNING, __FILE__, __LINE__);
[174]448            return false;
449        }
[457]450
[174]451        // Total number of transversal values (that is, the count of self plus all children times two).
452        $total_transversal_value = ($rgt - $lft + 1);
453
454        // Select the rgt of the new parent.
455        $qid = $db->query("SELECT rgt FROM $tbl WHERE name = '" . $db->escapeString($new_parent) . "'");
456        if (!list($new_parent_rgt) = mysql_fetch_row($qid)) {
[334]457            $app->logMsg(sprintf('Cannot move %s node to nonexistent parent: %s', $type, $new_parent), LOG_WARNING, __FILE__, __LINE__);
[174]458            return false;
459        }
[457]460
[174]461        // Ensure the new parent is not a child of the node being moved.
462        if ($new_parent_rgt <= $rgt && $new_parent_rgt >= $lft) {
463            $app->logMsg(sprintf('Cannot move %s node %s to parent %s because it is a child of itself.', $type, $name, $new_parent), LOG_WARNING, __FILE__, __LINE__);
464            return false;
465        }
[457]466
[174]467        // Collect unique ids of all nodes being moved. The transversal numbers will become duplicated so these will be needed to identify these.
468        $qid = $db->query("
469            SELECT $primary_key
470            FROM $tbl
471            WHERE lft BETWEEN $lft AND $rgt
472            AND rgt BETWEEN $lft AND $rgt
473        ");
474        $ids = array();
475        while (list($id) = mysql_fetch_row($qid)) {
476            $ids[] = $id;
477        }
478
479        // Update transversal numbers for all nodes to the rgt of the node being moved, taking in to account the absence of it's children.
480        // This will temporarily "remove" the node from the tree, and its transversal values will be duplicated.
481        $db->query("UPDATE $tbl SET lft = lft - $total_transversal_value WHERE lft > $rgt");
482        $db->query("UPDATE $tbl SET rgt = rgt - $total_transversal_value WHERE rgt > $rgt");
[189]483
[174]484        // Apply transformation to new parent rgt also.
485        $new_parent_rgt = $new_parent_rgt > $rgt ? $new_parent_rgt - $total_transversal_value : $new_parent_rgt;
[457]486
[174]487        // Update transversal values of moved node and children.
488        $db->query("
[457]489            UPDATE $tbl SET
[174]490                lft = lft - ($lft - $new_parent_rgt),
491                rgt = rgt - ($lft - $new_parent_rgt)
492            WHERE $primary_key IN ('" . join("','", $ids) . "')
493        ");
494
495        // Update transversal values of all nodes to the rgt of moved node.
496        $db->query("UPDATE $tbl SET lft = lft + $total_transversal_value WHERE lft >= $new_parent_rgt AND $primary_key NOT IN ('" . join("','", $ids) . "')");
497        $db->query("UPDATE $tbl SET rgt = rgt + $total_transversal_value WHERE rgt >= $new_parent_rgt AND $primary_key NOT IN ('" . join("','", $ids) . "')");
498
[201]499        $app->logMsg(sprintf('Moved %s node %s to new parent %s.', $type, $name, $new_parent), LOG_INFO, __FILE__, __LINE__);
[174]500        return true;
501    }
[457]502
[174]503    // Alias functions for the different object types.
[468]504    public function moveRequestObject($name, $new_parent=null)
[174]505    {
506        return $this->move($name, $new_parent, 'aro');
507    }
[468]508    public function moveControlObject($name, $new_parent=null)
[174]509    {
510        return $this->move($name, $new_parent, 'aco');
511    }
[468]512    public function moveXtraObject($name, $new_parent=null)
[174]513    {
514        return $this->move($name, $new_parent, 'axo');
515    }
[457]516
[171]517    /*
[174]518    * Add an entry to the acl_tbl to allow (or deny) a truple with the specified
519    * ARO -> ACO -> AXO entry.
[171]520    *
521    * @access   public
[175]522    * @param    string|null $aro Identifier of an existing ARO object (or null to use root).
523    * @param    string|null $aco Identifier of an existing ACO object (or null to use root).
524    * @param    string|null $axo Identifier of an existing AXO object (or null to use root).
[174]525    * @return   bool False on error, true on success.
[171]526    * @author   Quinn Comendant <quinn@strangecode.com>
527    * @version  1.0
528    * @since    15 Jun 2006 01:58:48
529    */
[468]530    public function grant($aro=null, $aco=null, $axo=null, $access='allow')
[171]531    {
532        $app =& App::getInstance();
533        $db =& DB::getInstance();
534
535        $this->initDB();
536
537        // If any access objects are null, assume using root values.
[173]538        // However if they're empty we don't want to escalate the grant command to root!
[171]539        $aro = is_null($aro) ? 'root' : $aro;
540        $aco = is_null($aco) ? 'root' : $aco;
541        $axo = is_null($axo) ? 'root' : $axo;
[457]542
[218]543        // Flush old cached values.
544        $cache_hash = $aro . '|' . $aco . '|' . $axo;
545        $this->cache->delete($cache_hash);
546
[171]547        // Ensure values exist.
548        $qid = $db->query("SELECT aro_tbl.aro_id FROM aro_tbl WHERE aro_tbl.name = '" . $db->escapeString($aro) . "'");
549        if (!list($aro_id) = mysql_fetch_row($qid)) {
[280]550            $app->logMsg(sprintf('Grant failed, aro_tbl.name = "%s" does not exist.', $aro), LOG_WARNING, __FILE__, __LINE__);
[171]551            return false;
552        }
553        $qid = $db->query("SELECT aco_tbl.aco_id FROM aco_tbl WHERE aco_tbl.name = '" . $db->escapeString($aco) . "'");
554        if (!list($aco_id) = mysql_fetch_row($qid)) {
[280]555            $app->logMsg(sprintf('Grant failed, aco_tbl.name = "%s" does not exist.', $aco), LOG_WARNING, __FILE__, __LINE__);
[171]556            return false;
557        }
558        $qid = $db->query("SELECT axo_tbl.axo_id FROM axo_tbl WHERE axo_tbl.name = '" . $db->escapeString($axo) . "'");
559        if (!list($axo_id) = mysql_fetch_row($qid)) {
[280]560            $app->logMsg(sprintf('Grant failed, axo_tbl.name = "%s" does not exist.', $axo), LOG_WARNING, __FILE__, __LINE__);
[171]561            return false;
562        }
563
564        // Access must be 'allow' or 'deny'.
565        $allow = 'allow' == $access ? 'allow' : 'deny';
[457]566
[171]567        $db->query("REPLACE INTO acl_tbl VALUES ('$aro_id', '$aco_id', '$axo_id', '$allow', NOW())");
[201]568        $app->logMsg(sprintf('Set %s: %s -> %s -> %s.', $allow, $aro, $aco, $axo), LOG_INFO, __FILE__, __LINE__);
[457]569
[171]570        return true;
571    }
572
573    /*
[174]574    * Add an entry to the acl_tbl to deny a truple with the specified
575    * ARO -> ACO -> AXO entry. This calls the ACL::grant function to create the entry
576    * but uses 'deny' as the fourth argument.
[171]577    *
578    * @access   public
[175]579    * @param    string|null $aro Identifier of an existing ARO object (or null to use root).
580    * @param    string|null $aco Identifier of an existing ACO object (or null to use root).
581    * @param    string|null $axo Identifier of an existing AXO object (or null to use root).
[174]582    * @return   bool False on error, true on success.
[171]583    * @author   Quinn Comendant <quinn@strangecode.com>
584    * @version  1.0
585    * @since    15 Jun 2006 04:35:54
586    */
[468]587    public function revoke($aro=null, $aco=null, $axo=null)
[171]588    {
589        return $this->grant($aro, $aco, $axo, 'deny');
590    }
[457]591
[171]592    /*
[175]593    * Delete an entry from the acl_tbl completely to allow other permissions to cascade down.
594    * Null values act as a "wildcard" and will cause ALL matches in that column to be deleted.
595    *
596    * @access   public
597    * @param    string|null $aro Identifier of an existing ARO object (or null for *).
598    * @param    string|null $aco Identifier of an existing ACO object (or null for *).
599    * @param    string|null $axo Identifier of an existing AXO object (or null for *).
600    * @return   bool False on error, true on success.
601    * @author   Quinn Comendant <quinn@strangecode.com>
602    * @version  1.0
603    * @since    20 Jun 2006 20:16:12
604    */
[468]605    public function delete($aro=null, $aco=null, $axo=null)
[175]606    {
607        $app =& App::getInstance();
608        $db =& DB::getInstance();
609
610        $this->initDB();
611
612        // If any access objects are null, assume using root values.
613        // However if they're empty we don't want to escalate the grant command to root!
614        $where = array();
615        $where[] = is_null($aro) ? "aro_tbl.name IS NOT NULL" : "aro_tbl.name = '" . $db->escapeString($aro) . "' ";
616        $where[] = is_null($aco) ? "aco_tbl.name IS NOT NULL" : "aco_tbl.name = '" . $db->escapeString($aco) . "' ";
617        $where[] = is_null($axo) ? "axo_tbl.name IS NOT NULL" : "axo_tbl.name = '" . $db->escapeString($axo) . "' ";
618
[218]619        // If any access objects are null, assume using root values.
620        // However if they're empty we don't want to escalate the grant command to root!
621        $aro = is_null($aro) ? 'root' : $aro;
622        $aco = is_null($aco) ? 'root' : $aco;
623        $axo = is_null($axo) ? 'root' : $axo;
[457]624
[218]625        // Flush old cached values.
626        $cache_hash = $aro . '|' . $aco . '|' . $axo;
627        $this->cache->delete($cache_hash);
628
[175]629        $final_where = join(' AND ', $where);
[247]630        if (mb_substr_count($final_where, 'IS NOT NULL') == 3) {
[175]631            // Null on all three tables will delete ALL entries including the root -> root -> root = deny.
[420]632            $app->logMsg('Cannot allow deletion of ALL acl entries.', LOG_WARNING, __FILE__, __LINE__);
[175]633            return false;
634        }
[457]635
[175]636        $qid = $db->query("
637            DELETE acl_tbl
638            FROM acl_tbl
639            LEFT JOIN aro_tbl ON (acl_tbl.aro_id = aro_tbl.aro_id)
640            LEFT JOIN aco_tbl ON (acl_tbl.aco_id = aco_tbl.aco_id)
641            LEFT JOIN axo_tbl ON (acl_tbl.axo_id = axo_tbl.axo_id)
642            WHERE $final_where
643        ");
644
645        $app->logMsg(sprintf('Deleted %s acl_tbl links: %s -> %s -> %s', mysql_affected_rows($db->getDBH()), $aro, $aco, $axo), LOG_INFO, __FILE__, __LINE__);
[457]646
[175]647        return true;
648    }
[457]649
[175]650    /*
[174]651    * Calculates the most specific cascading privilege found for a requested
[457]652    * ARO -> ACO -> AXO entry. Returns FALSE if the entry is denied. By default,
[209]653    * all entries are denied, unless some point in the hierarchy is set to "allow."
[171]654    *
655    * @access   public
[174]656    * @param    string $aro Identifier of an existing ARO object.
657    * @param    string $aco Identifier of an existing ACO object (or null to use root).
658    * @param    string $axo Identifier of an existing AXO object (or null to use root).
659    * @return   bool False if denied, true on allowed.
[171]660    * @author   Quinn Comendant <quinn@strangecode.com>
661    * @version  1.0
662    * @since    15 Jun 2006 03:58:23
663    */
[468]664    public function check($aro, $aco=null, $axo=null)
[171]665    {
666        $app =& App::getInstance();
667        $db =& DB::getInstance();
[457]668
[171]669        $this->initDB();
670
[173]671        // If any access objects are null or empty, assume using root values.
672        $aro = is_null($aro) || '' == trim($aro) ? 'root' : $aro;
673        $aco = is_null($aco) || '' == trim($aco) ? 'root' : $aco;
674        $axo = is_null($axo) || '' == trim($axo) ? 'root' : $axo;
[457]675
[172]676        $cache_hash = $aro . '|' . $aco . '|' . $axo;
677        if ($this->cache->exists($cache_hash) && true === $this->getParam('enable_cache')) {
678            // Access value is cached.
679            $access = $this->cache->get($cache_hash);
680        } else {
[396]681            // Retrieve access value from db.
[172]682            $qid = $db->query("
683                SELECT acl_tbl.access
684                FROM acl_tbl
685                LEFT JOIN aro_tbl ON (acl_tbl.aro_id = aro_tbl.aro_id)
686                LEFT JOIN aco_tbl ON (acl_tbl.aco_id = aco_tbl.aco_id)
687                LEFT JOIN axo_tbl ON (acl_tbl.axo_id = axo_tbl.axo_id)
[177]688                WHERE (aro_tbl.lft <= (SELECT lft FROM aro_tbl WHERE name = '" . $db->escapeString($aro) . "') AND aro_tbl.rgt >= (SELECT rgt FROM aro_tbl WHERE name = '" . $db->escapeString($aro) . "'))
689                AND (aco_tbl.lft <= (SELECT lft FROM aco_tbl WHERE name = '" . $db->escapeString($aco) . "') AND aco_tbl.rgt >= (SELECT rgt FROM aco_tbl WHERE name = '" . $db->escapeString($aco) . "'))
690                AND (axo_tbl.lft <= (SELECT lft FROM axo_tbl WHERE name = '" . $db->escapeString($axo) . "') AND axo_tbl.rgt >= (SELECT rgt FROM axo_tbl WHERE name = '" . $db->escapeString($axo) . "'))
[208]691                ORDER BY aro_tbl.lft DESC, aco_tbl.lft DESC, axo_tbl.lft DESC
[172]692                LIMIT 1
693            ");
694            if (!list($access) = mysql_fetch_row($qid)) {
[177]695                $this->cache->set($cache_hash, 'deny');
[334]696                $app->logMsg(sprintf('Access denied: %s -> %s -> %s. No records found.', $aro, $aco, $axo), LOG_DEBUG, __FILE__, __LINE__);
[172]697                return false;
698            }
699            $this->cache->set($cache_hash, $access);
[171]700        }
[457]701
[171]702        if ('allow' == $access) {
[201]703            $app->logMsg(sprintf('Access granted: %s -> %s -> %s.', $aro, $aco, $axo), LOG_DEBUG, __FILE__, __LINE__);
[171]704            return true;
705        } else {
[334]706            $app->logMsg(sprintf('Access denied: %s -> %s -> %s.', $aro, $aco, $axo), LOG_DEBUG, __FILE__, __LINE__);
[171]707            return false;
708        }
709    }
710
[457]711    /*
712    * Bounce user if they are denied access. Because this function calls dieURL() it must be called before any other HTTP header output.
713    *
714    * @access   public
715    * @param    string $aro Identifier of an existing ARO object.
716    * @param    string $aco Identifier of an existing ACO object (or null to use root).
717    * @param    string $axo Identifier of an existing AXO object (or null to use root).
718    * @param    string $message The text description of a message to raise.
719    * @param    int    $type    The type of message: MSG_NOTICE,
720    *                           MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
721    * @param    string $file    __FILE__.
722    * @param    string $line    __LINE__.
723    * @author   Quinn Comendant <quinn@strangecode.com>
724    * @version  1.0
725    * @since    20 Jan 2014 12:09:03
726    */
[468]727    public function requireAllow($aro, $aco=null, $axo=null, $message='', $type=MSG_NOTICE, $file=null, $line=null)
[457]728    {
[479]729        $app =& App::getInstance();
[457]730
731        if (!$this->check($aro, $aco, $axo)) {
[502]732            $message = '' == trim($message) ? sprintf(_("Sorry, you have insufficient privileges for <em>%s %s</em>."), $aco, $axo) : $message;
[457]733            $app->raiseMsg($message, $type, $file, $line);
734            $app->dieBoomerangURL();
735        }
736    }
737
[171]738} // End class.
Note: See TracBrowser for help on using the repository browser.