Index: trunk/lib/ACL.inc.php
===================================================================
--- trunk/lib/ACL.inc.php	(revision 171)
+++ trunk/lib/ACL.inc.php	(revision 171)
@@ -0,0 +1,444 @@
+<?php
+/*
+* ACL.inc.php
+* 
+* Uses the ARO/ACO/AXO model of Access Control Lists.
+* Includes a command-line tool for managing rights.
+* 
+* Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information.
+* @author   Quinn Comendant <quinn@strangecode.com>
+* @version  1.0
+* @since    14 Jun 2006 22:35:11
+*/
+
+class ACL {
+
+    // Configuration parameters for this object.
+    var $_params = array(
+
+        // Automatically create table and verify columns. Better set to false after site launch.
+        'create_table' => false,
+    );
+
+    /**
+     * Prefs constructor.
+     */
+    function ACL()
+    {
+		$app =& App::getInstance();
+
+        // Get create tables config from global context.
+        if (!is_null($app->getParam('db_create_tables'))) {
+            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
+        }
+    }
+
+    /**
+     * This method enforces the singleton pattern for this class.
+     *
+     * @return  object  Reference to the global ACL object.
+     * @access  public
+     * @static
+     */
+    function &getInstance()
+    {
+        static $instance = null;
+
+        if ($instance === null) {
+            $instance = new ACL();
+        }
+
+        return $instance;
+    }
+
+    /**
+     * Set (or overwrite existing) parameters by passing an array of new parameters.
+     *
+     * @access public
+     *
+     * @param  array    $params     Array of parameters (key => val pairs).
+     */
+    function setParam($params)
+    {
+		$app =& App::getInstance();
+    
+        if (isset($params) && is_array($params)) {
+            // Merge new parameters with old overriding only those passed.
+            $this->_params = array_merge($this->_params, $params);
+        } else {
+            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
+        }
+    }
+
+    /**
+     * Return the value of a parameter, if it exists.
+     *
+     * @access public
+     * @param string $param        Which parameter to return.
+     * @return mixed               Configured parameter value.
+     */
+    function getParam($param)
+    {
+		$app =& App::getInstance();
+    
+        if (isset($this->_params[$param])) {
+            return $this->_params[$param];
+        } else {
+            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
+            return null;
+        }
+    }
+
+    /**
+     * Setup the database table for this class.
+     *
+     * @access  public
+     * @author  Quinn Comendant <quinn@strangecode.com>
+     * @since   04 Jun 2006 16:41:42
+     */
+    function initDB($recreate_db=false)
+    {
+		$app =& App::getInstance();
+		$db =& DB::getInstance();
+
+        static $_db_tested = false;
+
+        if ($recreate_db || !$_db_tested && $this->getParam('create_table')) {
+
+            if ($recreate_db) {
+                $db->query("DROP TABLE IF EXISTS acl_tbl");
+                $db->query("DROP TABLE IF EXISTS aro_tbl");
+                $db->query("DROP TABLE IF EXISTS aco_tbl");
+                $db->query("DROP TABLE IF EXISTS axo_tbl");
+                $app->logMsg(sprintf('Dropping and recreating tables acl_tbl, aro_tbl, aco_tbl, axo_tbl.', null), LOG_DEBUG, __FILE__, __LINE__);
+            }
+            
+            // acl_tbl
+            $db->query("CREATE TABLE IF NOT EXISTS acl_tbl (
+                    aro_id SMALLINT(11) UNSIGNED NOT NULL DEFAULT '0',
+                    aco_id SMALLINT(11) UNSIGNED NOT NULL DEFAULT '0',
+                    axo_id SMALLINT(11) UNSIGNED NOT NULL DEFAULT '0',
+                    access ENUM('allow', 'deny') DEFAULT NULL,
+                    added_datetime DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
+                    UNIQUE KEY (aro_id, aco_id, axo_id),
+                    KEY (access)
+                ) ENGINE=MyISAM
+            ");
+            if (!$db->columnExists('acl_tbl', array(
+                'aro_id',
+                'aco_id',
+                'axo_id',
+                'access',
+                'added_datetime',
+            ), false, false)) {
+                $app->logMsg(sprintf('Database table acl_tbl has invalid columns. Please update this table manually.', null), LOG_ALERT, __FILE__, __LINE__);
+                trigger_error(sprintf('Database table acl_tbl has invalid columns. Please update this table manually.', null), E_USER_ERROR);
+            }
+
+            // The tuples of objects.
+            foreach (array('aro', 'aco', 'axo') as $a_o) {
+                // Each of these uses Modified Preorder Tree Traversal to maintain a tree-structure in a flat format.
+                // See: http://www.sitepoint.com/print/hierarchical-data-database
+                $db->query("CREATE TABLE IF NOT EXISTS {$a_o}_tbl (
+                        {$a_o}_id SMALLINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
+                        name VARCHAR(32) NOT NULL DEFAULT '',
+                        lft MEDIUMINT(9) UNSIGNED NOT NULL DEFAULT '0',
+                        rgt MEDIUMINT(9) UNSIGNED NOT NULL DEFAULT '0',
+                        added_datetime DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
+                        UNIQUE name (name),
+                        KEY transversal (lft, rgt)
+                    ) ENGINE=MyISAM;
+                ");
+
+                $qid = $db->query("SELECT 1 FROM {$a_o}_tbl WHERE name = 'root'");
+                if (mysql_num_rows($qid) == 0) {
+                    // Insert root node data.
+                    $qid = $db->query("REPLACE INTO {$a_o}_tbl (name, lft, rgt, added_datetime) VALUES ('root', 1, 2, NOW())");                    
+                }
+
+                if (!$db->columnExists("{$a_o}_tbl", array(
+                    "{$a_o}_id",
+                    'name',
+                    'lft',
+                    'rgt',
+                    'added_datetime',
+                ), false, false)) {
+                    $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', "{$a_o}_tbl"), LOG_ALERT, __FILE__, __LINE__);
+                    trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', "{$a_o}_tbl"), E_USER_ERROR);
+                }
+            }
+        }
+        $_db_tested = true;
+    }
+
+    /*
+    * 
+    *
+    * @access   public
+    * @param    
+    * @return   
+    * @author   Quinn Comendant <quinn@strangecode.com>
+    * @version  1.0
+    * @since    14 Jun 2006 22:39:29
+    */
+    function add($name, $parent=null, $type)
+    {
+        $app =& App::getInstance();
+        $db =& DB::getInstance();
+        
+        $this->initDB();
+        
+        switch ($type) {
+        case 'aro' :
+            $tbl = 'aro_tbl';
+            break;
+        case 'aco' :
+            $tbl = 'aco_tbl';
+            break;
+        case 'axo' :
+            $tbl = 'axo_tbl';
+            break;
+        default :
+            $app->logMsg(sprintf('Invalid access object type: %s', $type), LOG_ERR, __FILE__, __LINE__);
+            return false;
+            break;
+        }
+        
+        // If $parent is null, use root object.
+        if (is_null($parent)) {
+            $parent = 'root';
+        }
+        
+        // Ensure node and parent name aren't empty.
+        if ('' == trim($name) || '' == trim($parent)) {
+            $app->logMsg(sprintf('Cannot add node, parent (%s) or name (%s) missing.', $name, $parent), LOG_WARNING, __FILE__, __LINE__);
+            return false;
+        }
+        
+        // Ensure node is unique.
+        $qid = $db->query("SELECT 1 FROM $tbl WHERE name = '" . $db->escapeString($name) . "'");
+        if (mysql_num_rows($qid) > 0) {
+            $app->logMsg(sprintf('Cannot add %s node, name exists: %s', $type, $name), LOG_WARNING, __FILE__, __LINE__);
+            return false;
+        }
+        
+        // Select the rgt of $parent.
+        $qid = $db->query("SELECT rgt FROM $tbl WHERE name = '" . $db->escapeString($parent) . "'");
+        if (!list($rgt) = mysql_fetch_row($qid)) {
+            $app->logMsg(sprintf('Cannot add %s node to nonexistant parent: %s', $type, $parent), LOG_WARNING, __FILE__, __LINE__);
+            return false;
+        }
+        // Update transversal numbers for all nodes to the rgt of $parent.
+        $db->query("UPDATE $tbl SET lft = lft + 2 WHERE lft >= $rgt");
+        $db->query("UPDATE $tbl SET rgt = rgt + 2 WHERE rgt >= $rgt");
+        
+        // Insert new node just below parent. Lft is parent's old rgt.
+        $db->query("
+            INSERT INTO $tbl (name, lft, rgt, added_datetime) 
+            VALUES ('" . $db->escapeString($name) . "', $rgt, $rgt + 1, NOW())
+        ");
+
+        $app->logMsg(sprintf('Added %s node %s to parent %s.', $type, $name, $parent), LOG_DEBUG, __FILE__, __LINE__);
+        return mysql_insert_id($db->getDBH());
+    }
+
+    // Alias functions for the different object types.
+    function addARO($name, $parent=null)
+    {
+        return $this->add($name, $parent, 'aro');
+    }
+    function addACO($name, $parent=null)
+    {
+        return $this->add($name, $parent, 'aco');
+    }
+    function addAXO($name, $parent=null)
+    {
+        return $this->add($name, $parent, 'axo');
+    }
+
+    /*
+    * 
+    *
+    * @access   public
+    * @param    
+    * @return   
+    * @author   Quinn Comendant <quinn@strangecode.com>
+    * @version  1.0
+    * @since    14 Jun 2006 22:39:29
+    */
+    function remove($name, $type)
+    {
+        $app =& App::getInstance();
+        $db =& DB::getInstance();
+        
+        $this->initDB();
+
+        switch ($type) {
+        case 'aro' :
+            $tbl = 'aro_tbl';
+            break;
+        case 'aco' :
+            $tbl = 'aco_tbl';
+            break;
+        case 'axo' :
+            $tbl = 'axo_tbl';
+            break;
+        default :
+            $app->logMsg(sprintf('Invalid access object type: %s', $type), LOG_ERR, __FILE__, __LINE__);
+            return false;
+            break;
+        }
+        
+        // Ensure node name isn't empty.
+        if ('' == trim($name)) {
+            $app->logMsg(sprintf('Cannot add node, name missing.', null), LOG_WARNING, __FILE__, __LINE__);
+            return false;
+        }
+        
+        // Select the lft of $name
+        $qid = $db->query("SELECT lft, rgt FROM $tbl WHERE name = '" . $db->escapeString($name) . "'");
+        if (!list($lft, $rgt) = mysql_fetch_row($qid)) {
+            $app->logMsg(sprintf('Cannot delete nonexistant %s name: %s', $type, $name), LOG_WARNING, __FILE__, __LINE__);
+            return false;
+        }
+        
+        // Remove node and all children of node.
+        $db->query("DELETE FROM $tbl WHERE lft BETWEEN $lft AND $rgt");
+        $num_deleted_nodes = mysql_affected_rows($db->getDBH());
+
+        // Update transversal numbers for all nodes to the rgt of $parent, taking in to account the absence of it's children.
+        $db->query("UPDATE $tbl SET lft = lft - ($rgt - $lft + 1) WHERE lft > $lft");
+        $db->query("UPDATE $tbl SET rgt = rgt - ($rgt - $lft + 1) WHERE rgt > $rgt");
+
+        $app->logMsg(sprintf('Removed %s node %s along with %s children.', $type, $name, $num_deleted_nodes), LOG_DEBUG, __FILE__, __LINE__);
+        return true;
+    }
+    
+    // Alias functions for the different object types.
+    function removeUser($name, $parent=null)
+    {
+        return $this->remove($name, $parent, 'aro');
+    }
+    function removeAction($name, $parent=null)
+    {
+        return $this->remove($name, $parent, 'aco');
+    }
+    function removeObject($name, $parent=null)
+    {
+        return $this->remove($name, $parent, 'axo');
+    }
+    
+    /*
+    * 
+    *
+    * @access   public
+    * @param    
+    * @return   
+    * @author   Quinn Comendant <quinn@strangecode.com>
+    * @version  1.0
+    * @since    15 Jun 2006 01:58:48
+    */
+    function grant($aro=null, $aco=null, $axo=null, $access='allow')
+    {
+        $app =& App::getInstance();
+        $db =& DB::getInstance();
+
+        $this->initDB();
+
+        // If any access objects are null, assume using root values.
+        $aro = is_null($aro) ? 'root' : $aro;
+        $aco = is_null($aco) ? 'root' : $aco;
+        $axo = is_null($axo) ? 'root' : $axo;
+        
+        // Ensure values exist.
+        $qid = $db->query("SELECT aro_tbl.aro_id FROM aro_tbl WHERE aro_tbl.name = '" . $db->escapeString($aro) . "'");
+        if (!list($aro_id) = mysql_fetch_row($qid)) {
+            $app->logMsg(sprintf('Grant failed, aro_tbl.name %s does not exist.', $aro), LOG_WARNING, __FILE__, __LINE__);
+            return false;
+        }
+        $qid = $db->query("SELECT aco_tbl.aco_id FROM aco_tbl WHERE aco_tbl.name = '" . $db->escapeString($aco) . "'");
+        if (!list($aco_id) = mysql_fetch_row($qid)) {
+            $app->logMsg(sprintf('Grant failed, aco_tbl.name %s does not exist.', $aco), LOG_WARNING, __FILE__, __LINE__);
+            return false;
+        }
+        $qid = $db->query("SELECT axo_tbl.axo_id FROM axo_tbl WHERE axo_tbl.name = '" . $db->escapeString($axo) . "'");
+        if (!list($axo_id) = mysql_fetch_row($qid)) {
+            $app->logMsg(sprintf('Grant failed, axo_tbl.name %s does not exist.', $axo), LOG_WARNING, __FILE__, __LINE__);
+            return false;
+        }
+
+        // Access must be 'allow' or 'deny'.
+        $allow = 'allow' == $access ? 'allow' : 'deny';
+        
+        $db->query("REPLACE INTO acl_tbl VALUES ('$aro_id', '$aco_id', '$axo_id', '$allow', NOW())");
+        
+        return true;
+    }
+
+    /*
+    * 
+    *
+    * @access   public
+    * @param    
+    * @return   
+    * @author   Quinn Comendant <quinn@strangecode.com>
+    * @version  1.0
+    * @since    15 Jun 2006 04:35:54
+    */
+    function revoke($aro=null, $aco=null, $axo=null)
+    {
+        return $this->grant($aro, $aco, $axo, 'deny');
+    }
+    
+    /*
+    * 
+    *
+    * @access   public
+    * @param    
+    * @return   
+    * @author   Quinn Comendant <quinn@strangecode.com>
+    * @version  1.0
+    * @since    15 Jun 2006 03:58:23
+    */
+    function check($aro, $aco=null, $axo=null)
+    {
+        $app =& App::getInstance();
+        $db =& DB::getInstance();
+        
+        $this->initDB();
+
+        // If any access objects are null, assume using root values.
+        $aro = is_null($aro) ? 'root' : $aro;
+        $aco = is_null($aco) ? 'root' : $aco;
+        $axo = is_null($axo) ? 'root' : $axo;
+
+        $qid = $db->query("
+            SELECT acl_tbl.access
+            FROM acl_tbl
+            LEFT JOIN aro_tbl ON (acl_tbl.aro_id = aro_tbl.aro_id)
+            LEFT JOIN aco_tbl ON (acl_tbl.aco_id = aco_tbl.aco_id)
+            LEFT JOIN axo_tbl ON (acl_tbl.axo_id = axo_tbl.axo_id)
+            WHERE aro_tbl.lft <= (SELECT lft FROM aro_tbl WHERE name = '" . $db->escapeString($aro) . "')
+            AND aco_tbl.lft <= (SELECT lft FROM aco_tbl WHERE name = '" . $db->escapeString($aco) . "')
+            AND axo_tbl.lft <= (SELECT lft FROM axo_tbl WHERE name = '" . $db->escapeString($axo) . "')
+            ORDER BY aro_tbl.aro_id DESC, aco_tbl.aco_id DESC, axo_tbl.axo_id DESC
+            LIMIT 1
+        ");
+        if (!list($access) = mysql_fetch_row($qid)) {
+            $app->logMsg(sprintf('Access denyed: %s -> %s -> %s. No records found.', $aro, $aco, $axo), LOG_DEBUG, __FILE__, __LINE__);
+            return false;
+        }
+        
+        if ('allow' == $access) {
+            $app->logMsg(sprintf('Access granted: %s -> %s -> %s.', $aro, $aco, $axo), LOG_DEBUG, __FILE__, __LINE__);
+            return true;
+        } else {
+            $app->logMsg(sprintf('Access denyed: %s -> %s -> %s.', $aro, $aco, $axo), LOG_DEBUG, __FILE__, __LINE__);
+            return false;
+        }
+    }
+
+} // End class.
+
+
+?>
