<?php
/**
 * @version $Id: Global.class.php 679 2012-08-20 12:41:35Z hodaka $
 * @package myuploader
 */

if (!defined('XOOPS_ROOT_PATH')) exit();

class Myuploader_Global
{
    var $mDirname = null;
    var $mXoopsModule = null;
    var $mAssetManager = null;
    var $mModuleConfig = null;
    var $mTargetDir = null;
    var $mLib = null;

    var $mModuleGperm = null;
    var $mGroups = null;

    /**
     * @public
     */
    function Myuploader_Global($dirname)
    {
        $this->mDirname = $dirname;

        // module info
        $root = XCube_Root::getSingleton();
        $xoopsModule =& $root->mContext->mXoopsModule;
        if(is_object($xoopsModule) && $xoopsModule->get('dirname') == $dirname) {
            $this->mXoopsModule = $xoopsModule;
        } else {
            $module_handler =& xoops_gethandler('module');
            $this->mXoopsModule =& $module_handler->getByDirname($dirname);
            if(!is_object($this->mXoopsModule) || !$this->mXoopsModule->getVar('isactive')) {
                XCube_DelegateUtils::call('Legacy.Event.Exception.XoopsModuleNotFound', $dirname);
                $root->mController->executeRedirect(XOOPS_URL . '/', 1, 'Module is not found or is not active.');
                die();
            }
        }

        // get asset manager
        XCube_DelegateUtils::call('Module.myuploader.Event.GetAssetManager', new XCube_Ref($this->mAssetManager), $dirname);

        // groups
        $this->mGroups = $this->_getGroups();

        // module group permisiion
        $this->mModuleGperm = $this->_loadGroupPerm();

        // module config
        $config_handler =& xoops_gethandler('config');
        $this->mModuleConfig =& $config_handler->getConfigsByCat(0, $this->mXoopsModule->get('mid'));
        $this->mTargetDir = !empty($this->mModuleConfig['upload_dir'])? preg_replace("|^(.+)/$|", '$1', XOOPS_ROOT_PATH.$this->mModuleConfig['upload_dir']) : XOOPS_UPLOAD_PATH.'/myuploader';
        $this->mLib = !empty($this->mModuleConfig['image_lib'])? $this->mModuleConfig['image_lib'] : 'none';
    }

    function &getInstance($dirname) {
        static $instance = array();
        if(!isset($instance[$dirname])) {
            $instance[$dirname] = new Myuploader_Global($dirname);
        }

        return $instance[$dirname];
    }

    function _getGroups() {
        $root = XCube_Root::getSingleton();
        if(is_object($root->mContext->mXoopsUser)) {
            $groups = $root->mContext->mXoopsUser->getGroups();
        } else {
            $groups = array(XOOPS_GROUP_ANONYMOUS);
        }
        return $groups;
    }

    function _loadGroupPerm() {
        $root = XCube_Root::getSingleton();
        $gperm_handler =& xoops_gethandler('groupperm');
        $criteria = new criteriaCompo(new criteria('gperm_modid', $this->mXoopsModule->get('mid')));
        $criteria->add(new criteria('gperm_name', "('cat_view', 'cat_upload', 'html_allowed')", 'IN'));
        $criteria->setSort('gperm_name');
        $criteria->addSort('gperm_itemid');
        $criteria->addSort('gperm_groupid');
        $objs =& $gperm_handler->getObjects($criteria);
        $moduleGperm = array();

        foreach($objs as $obj) {
            $moduleGperm[$obj->get('gperm_name')][$obj->get('gperm_itemid')][] = $obj->get('gperm_groupid');
        }
        return $moduleGperm;
    }

    function &getAllCategories() {
        static $__categories__ = array();
        if(empty($__categories__[$this->mDirname])) {
            $__categories__[$this->mDirname] =& $this->_loadCategories();
        }
        return $__categories__[$this->mDirname];
    }

    function &_loadCategories(){
        $category_handler =& $this->mAssetManager->getObject('handler', 'category');
        $criteria = new criteriaCompo();
        $criteria->setSort('cat_weight');
        $categories =& $category_handler->getObjects($criteria, true);
        return $categories;
    }

    function getViewable() {
        static $__viewable__ = array();
        if(empty($__viewable__[$this->mDirname])) {
            $__viewable__[$this->mDirname] = $this->catByGroups('cat_view');
        }
        return $__viewable__[$this->mDirname];
    }

    function getUploadable() {
        static $__uploadable__ = array();
        if(empty($__uploadable__[$this->mDirname])) {
            $__uploadable__[$this->mDirname] = $this->catByGroups('cat_upload');
        }
        return $__uploadable__[$this->mDirname];
    }

    function getHtmlAllowed() {
        static $__htmlalowed__ = array();
        if(empty($__htmlalowed__[$this->mDirname])) {
            $__htmlalowed__[$this->mDirname] = $this->catByGroups('html_allowed');
        }
        return $__htmlalowed__[$this->mDirname];
    }

    function catByGroups($names) {
        $cats = array();
        if(is_array($names)) {
            foreach($names as $name) {
                $cats = array_merge($cats, $this->_catByGroups($name));
            }
        } else {
            $cats = array_merge($cats, $this->_catByGroups($names));
        }

        return array_unique($cats);

    }

    function _catByGroups($name) {
        $array = array();
        $ret = array();
        $return = array();
        $allCategories =& $this->getAllCategories();

        if(isset($this->mModuleGperm[$name])) {
            foreach($this->mModuleGperm[$name] as $catid=>$groupids) {
                foreach($groupids as $groupid) {
                    $array[$groupid][] = $catid;
                }
//            $array[$groupid] = array_unique($array[$groupid]);
            }
        }

        if(count($array)) {
              foreach($this->mGroups as $group) {
                if(in_array($group, array_keys($array)))
                    $ret = array_merge($ret, $array[$group]);
            }
            array_unique($ret);
        }

        foreach(array_keys($allCategories) as $id) {
            if(in_array($id, $ret)) {
                $return[] = $id;
            }
        }
        return $return;
    }

    /**
     * @param array or string $names group permission name
     * @param void $catid category id
     * @return array $groups groups with the privilege name
     */
    function groupsByCat($names, $catid=null) {
        $groups = array();
        if(is_array($names)) {
            foreach($names as $name) {
                $groups = array_merge($groups, $this->_groupsByCat($name, $catid));
            }
        } else {
            $groups = array_merge($groups, $this->_groupsByCat($names, $catid));
        }
        return array_unique($groups);
    }

    function _groupsByCat($name, $catid) {
        $return = array();
        if(!empty($catid)) {
            if(isset($this->mModuleGperm[$name][intval($catid)])) {
                $return = array_merge($this->mModuleGperm[$name][intval($catid)]);
            }
        }
        return $return;
    }

    function getSubscribers() {
        static $__subscribers__ = array();

        if(!empty($__subscribers__[$this->mDirname])) {
            return $__subscribers__[$this->mDirname];
        }

        $__subscribers__[$this->mDirname] = array();

        $groups = array();
        if(isset($this->mModuleGperm['cat_upload'])) {
            foreach($this->mModuleGperm['cat_upload'] as $catids) {
                foreach($catids as $group) {
                   $groups[] = $group;
                }
            }
        }
        $groups = array_unique($groups);

        if(count($groups)) {
            $handler =& xoops_gethandler('membership');
            $criteria = new criteriaCompo();
            $criteria->add(new criteria('groupid', '('.implode(',', $groups).')', 'IN'));
            $objs =& $handler->getObjects($criteria);
            unset($criteria);
            $uids = array();
            foreach($objs as $obj) {
                $uids[] = $obj->get('uid');
            }
            $uids = array_unique($uids);

            if(count($uids)) {
                $uhandler =& xoops_gethandler('user');
                $criteria = new criteriaCompo();
                $criteria->add(new criteria('uid', '('.implode(',', $uids).')', 'IN'));
                $__subscribers__[$this->mDirname] =& $uhandler->getObjects($criteria, true);
            }
        }
        return $__subscribers__[$this->mDirname];
    }

}
?>