13

I want to create a Zend Controller for ACL management so my problem is: How can I get all Module names, Control names and Action names in a Zend application to build a ACL Control?

I use Zend_Navigation and if the resource don't exist in your ACL Zend_Navigation is thrown a exception. And I want to use a database to deny and allow access. So I must build the database first. And if I must do that by hand it's a pain to do that.

3
  • 2
    Why is it necessary to have ALL actions & controller names? Just think of a whitelist: only actions or controllers which are in a special group are allowed to be accessed. All others aren't.
    – powtac
    Commented May 20, 2009 at 13:56
  • You should have made this an answer, as you're correct. A whitelist is really the best way to proceed with controller/action based ACL Commented May 21, 2009 at 9:43
  • 2
    There is only one problem if you use Zend_Navigation and the resource don't exist in your ACL there is thrown a exception. And I want to use a database to deny and allow access. So I must build the database first. And if I must that do by hand it's a pain to do that. Commented May 21, 2009 at 15:51

4 Answers 4

25

This may be an old question but this is how I am doing this...

//        $front = Zend_Controller_Front::getInstance(); // use this line instead on a model class
    $front = $this->getFrontController(); // this in controller
    $acl   = array();

    foreach ($front->getControllerDirectory() as $module => $path) {
        foreach (scandir($path) as $file) {

            if (strstr($file, "Controller.php") !== false) {

                include_once $path . DIRECTORY_SEPARATOR . $file;
                $class = substr($file,0,strpos($file,".php"));

                if (is_subclass_of($class, 'Zend_Controller_Action')) {

                    $controller = strtolower(substr($file, 0, strpos($file, "Controller")));
                    $methods = array();

                    foreach (get_class_methods($class) as $method) {
                        if (strstr($method,"Action") != false) {
                            array_push($methods,substr($method,0,strpos($method,"Action")));
                        }
                    }
                }

                $acl[$module][$controller] = $methods;
            }
        }
    }
3
  • A tiny tweak : "$actions[] = $action;" -> "$actions[] = substr($action, 0, -6);" was helpful in my case. It got rid of "Action" from string.
    – understack
    Commented May 23, 2011 at 8:31
  • It seems if this function is called from a controller itself, then that controller and all its action's are missing from $acl.
    – understack
    Commented May 23, 2011 at 13:00
  • 1
    You actually should be able to put the inner foreach() and the line after it outside of the other loops, because when it's done like here, you would lookup every included class multiple times.
    – Dominik
    Commented Apr 28, 2012 at 15:14
7

I have created a function that can get all the actions, controllers and modules from a zend application. Here it is:

$module_dir = substr(str_replace("\\","/",$this->getFrontController()->getModuleDirectory()),0,strrpos(str_replace("\\","/",$this->getFrontController()->getModuleDirectory()),'/'));
    $temp = array_diff( scandir( $module_dir), Array( ".", "..", ".svn"));
    $modules = array();
    $controller_directorys = array();
    foreach ($temp as $module) {
        if (is_dir($module_dir . "/" . $module)) {
            array_push($modules,$module);
            array_push($controller_directorys, str_replace("\\","/",$this->getFrontController()->getControllerDirectory($module)));
        }
    }

    foreach ($controller_directorys as $dir) {
        foreach (scandir($dir) as $dirstructure) {
            if (is_file($dir  . "/" . $dirstructure)) {
                if (strstr($dirstructure,"Controller.php") != false) {
                    include_once($dir . "/" . $dirstructure);
                }
            }

        }
    }

    $default_module = $this->getFrontController()->getDefaultModule();

    $db_structure = array();

    foreach(get_declared_classes() as $c){
        if(is_subclass_of($c, 'Zend_Controller_Action')){
            $functions = array();
            foreach (get_class_methods($c) as $f) {
                if (strstr($f,"Action") != false) {
                    array_push($functions,substr($f,0,strpos($f,"Action")));
                }
            }
            $c = strtolower(substr($c,0,strpos($c,"Controller")));

            if (strstr($c,"_") != false) {
                $db_structure[substr($c,0,strpos($c,"_"))][substr($c,strpos($c,"_") + 1)] = $functions;
            }else{
                $db_structure[$default_module][$c] = $functions;
            }
        }
    }       
}
1

I actually found the best way to have an easily available reflection reference was to recursively tokenise the correct directories and then build an xml document as a result. Caching the xml document for speed and using xpath for retrieving the data.

The plugin builds the reflection xml and caches it for later. I've taken this code out of its original implementation, so its more to give you a feel rather than copy and paste.

Of course, a database works just as well here. But if you're trying to limit your queries per page, a cached xml doc works pretty well.

class My_Reflection_Plugin extends My_Controller_Plugin_Abstract
{
    public function routeShutdown(Zend_Controller_Request_Abstract $request)
    {
        $cache = $this -> getCacheManager() -> getCache('general');

        if (!$xml = $cache->load("Reflection"))
        {
            $paths = array(
                PATH_APPLICATION . "/Core",
                PATH_SITE . "/Project"
            );

            foreach ($paths as $path)
            {
                $this -> inspectDir($path);
            }

            $cache -> save($this->getReflectionXML(), "Reflection");
        }
        else
        {
            $this -> getReflectionXML($xml);
        }
    }

    private function inspectDir($path)
    {
        $rdi = new RecursiveDirectoryIterator($path);
        $rii = new RecursiveIteratorIterator($rdi);
        $filtered = new My_Reflection_Filter($rii);

        iterator_apply($filtered, array($this, 'process'), array($filtered));
    }

    private function process($it = false)
    {
        $this -> getReflectionXML() -> addItem($it -> current());

        return true;
    }
}

Tokenisation happens inside the filter:

class My_Reflection_Filter extends FilterIterator
{
    public function accept()
    {
        $file = $this->getInnerIterator()->current();

        // If we somehow have something other than an SplFileInfo object, just
        // return false
        if (!$file instanceof SplFileInfo) {
            return false;
        }

        // If we have a directory, it's not a file, so return false
        if (!$file->isFile()) {
            return false;
        }

        // If not a PHP file, skip
        if ($file->getBasename('.php') == $file->getBasename()) {
            return false;
        }

        // Resource forks are no good either.
        if (substr($file->getBaseName(), 0, 2) == '._')
        {
            return false;
        }

        $contents = file_get_contents($file->getRealPath());
        $tokens   = token_get_all($contents);

        $file->className = NULL;
        $file->classExtends = NULL;
        $file->classImplements = array();

        $last = null;
        while (count($tokens) > 0)
        {
            $token = array_shift($tokens);

            if (!is_array($token))
            {
                continue;
            }

            list($id, $content, $line) = $token;

            switch ($id)
            {
                case T_ABSTRACT:
                case T_CLASS:
                case T_INTERFACE:
                        $last = 'object';
                    break;
                case T_EXTENDS:
                        $last = "extends";
                    break;
                case T_IMPLEMENTS:
                        $last = "implements";
                    break;
                case T_STRING:
                        switch ($last)
                        {
                            case "object":
                                    $file -> className = $content;
                                break;
                            case "extends":
                                    $file -> classExtends = $content;
                                break;
                            case "implements":
                                    $file -> classImplements[] = $content;
                                break;
                        }
                    break;
                case T_WHITESPACE:
                        // Do nothing, whitespace should be ignored but it shouldnt reset $last.
                    break;
                default:
                        // If its not directly following a keyword specified by $last, reset last to nothing.
                        $last = null;
                    break;
            }
        }

        return true;
    }
}

Once you have your reflection xml populated with whatever information you need out of the class, your acl plugin can come after it and query that information with xpath.

0

I don't think there is a solution for this in Zend. You will have to do it yourself...

One way to do it, is to list all classes, and check if the classes extend (for example) the Zend_Controller_Action class...

check the php functions get_declared_classes and is_subclass_of

foreach(get_declared_classes() as $c){
  if(is_subclass_of($c, 'Zend_Controller_Action')){
     ...
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.