<?php namespace Phpcmf\Library\Member;

// 用户权限处理（内容相关权限已迁移至 Cms：home/module/category）
class Member_auth {

    public $auth;
    public $auth_type;
    public $is_category_public;

    public function __construct() {
        $this->auth = isset(\Phpcmf\Service::C()->member_cache['auth2'][SITE_ID]) ? \Phpcmf\Service::C()->member_cache['auth2'][SITE_ID] : [];
        $this->auth_type = isset(\Phpcmf\Service::C()->member_cache['auth_type']) ? \Phpcmf\Service::C()->member_cache['auth_type'] : 0;
    }

    // 当前登录会员的groupid值
    protected function _get_groupid($member) {

        $auth_type = is_numeric($this->auth_type) ? intval($this->auth_type) : 0;

        if ($auth_type == 1) {
            $groupid = $member && isset($member['groupid']) ? $member['groupid'] : [0];
            if (!$groupid) {
                return [0];
            }
        } elseif ($auth_type == 2) {
            $groupid = $member && isset($member['authid']) ? $member['authid'] : [0];
            if (!$groupid) {
                return [0];
            }
        } else {
            $groupid = ['public'];
        }

        return $groupid;
    }

    // 内容权限转发给 Cms（已迁至 Models/Member_auth.php）
    protected function _cms_auth() {
        $dir = dr_get_app_dir('cms');
        if ($dir && is_file($dir.'Models/Member_auth.php')) {
            return \Phpcmf\Service::M('member_auth', 'cms');
        }
        return null;
    }

    // 获取用户权限值
    public function member_auth($name, $member = []) {

        $values = [];
        $groupid = $this->_get_groupid($member);

        foreach ($groupid as $gid) {
            if (isset($this->auth[$gid]['member'][$name])) {
                $values[] = $this->auth[$gid]['member'][$name];
            }
        }

        return $values ? max($values) : null;
    }

    // 获取应用插件权限值
    public function app_auth($dir, $name, $member = []) {

        $values = [];
        $groupid = $this->_get_groupid($member);

        foreach ($groupid as $gid) {
            if (isset($this->auth[$gid]['app'][$dir][$name])) {
                $values[] = $this->auth[$gid]['app'][$dir][$name];
            }
        }

        return $values ? max($values) : null;
    }

    // 站点权限 → Cms
    public function home_auth($name, $member = []) {
        $cms = $this->_cms_auth();
        return $cms ? $cms->home_auth($name, $member) : null;
    }

    // 模块权限 → Cms
    public function module_auth($mid, $name, $member = []) {
        $cms = $this->_cms_auth();
        return $cms ? $cms->module_auth($mid, $name, $member) : null;
    }

    // 栏目权限 → Cms
    public function category_auth($module, $catid, $name, $member = []) {
        $cms = $this->_cms_auth();
        return $cms ? $cms->category_auth($module, $catid, $name, $member) : null;
    }

    // 废除
    public function mform_auth($mid, $fid, $name, $member = []) {
        return null;
    }

    // 废除
    public function form_auth($fid, $name, $member = []) {
        return null;
    }

}
