<?php
require_once 'Sabai/Application/ControllerFilter.php';

class plugg_xoops_permission_filter extends Sabai_Application_ControllerFilter
{
    public function before(Sabai_Application_Context $context, Sabai_Application $application)
    {
        if (empty($GLOBALS['xoopsUser']) || $context->user->isSuperUser()) {
            return;
        }
        // Check if the User plugin is installed
        if (!$plugin = $application->pluginManager->getPlugin('user')) {
            return false;
        }
        // Load roles and set permissions
        $xoops_groups = $GLOBALS['xoopsUser']->getGroups();
        $perm_name = $GLOBALS['xoopsModule']->getVar('dirname') . '_role';
        $module_id = $GLOBALS['xoopsModule']->getVar('mid');
        if (!$role_ids = xoops_gethandler('groupperm')->getItemIds($perm_name, $xoops_groups, $module_id)) {
            return;
        }
        $roles = $plugin->getModel()->Role->fetchByCriteria(Sabai_Model_Criteria::createIn('role_id', $role_ids));
        foreach ($roles as $role) {
            foreach ($role->getPermissions() as $perm_name) {
                $context->user->addPermission($perm_name);
            }
        }
    }
    
    public function after(Sabai_Application_Context $context, Sabai_Application $application)
    {
    }
}