ktpermissions.php

来自「PHP 知识管理系统(基于树结构的知识管理系统), 英文原版的PHP源码。」· PHP 代码 · 共 905 行 · 第 1/3 页

PHP
905
字号
        $this->oPage->setTitle(sprintf(_kt('Manage Groups for Role "%s"'), $oRole->getName()));

        $initJS = 'var optGroup = new OptionTransfer("groupSelect","chosenGroups"); ' .
        'function startTrans() { var f = getElement("grouproleform"); ' .
        ' optGroup.saveNewRightOptions("groupFinal"); ' .
        ' optGroup.init(f); }; ' .
        ' addLoadEvent(startTrans); ';
        $this->oPage->requireJSStandalone($initJS);

        $aInitialUsers = $oRoleAllocation->getGroups();
        $aAllUsers = Group::getList();


        // FIXME this is massively non-performant for large userbases..
        $aRoleUsers = array();
        $aFreeUsers = array();
        foreach ($aInitialUsers as $oGroup) {
            $aRoleUsers[$oGroup->getId()] = $oGroup;
        }
        foreach ($aAllUsers as $oGroup) {
            if (!array_key_exists($oGroup->getId(), $aRoleUsers)) {
                $aFreeUsers[$oGroup->getId()] = $oGroup;
            }
        }



        $oTemplating =& KTTemplating::getSingleton();
        $oTemplate = $oTemplating->loadTemplate("ktcore/folder/roles_managegroups");
        $aTemplateData = array(
            "context" => $this,
            "edit_rolealloc" => $oRoleAllocation,
			'unused_groups' => $aFreeUsers,
			'role_groups' => $aRoleUsers,
			'rolename' => $oRole->getName(),
        );
        return $oTemplate->render($aTemplateData);
	}

    function do_setRoleUsers() {

        $role_allocation_id = KTUtil::arrayGet($_REQUEST, 'allocation_id');
        $oRoleAllocation = RoleAllocation::get($role_allocation_id);
        if ((PEAR::isError($oRoleAllocation)) || ($oRoleAllocation=== false)) {
            $this->errorRedirectToMain(_kt('No such role allocation.'), sprintf('fFolderId=%d',$this->oFolder->getId()));
        }
        $users = KTUtil::arrayGet($_REQUEST, 'userFinal', '');
		$aUserIds = explode(',', $users);

		// check that its not corrupt..
		$aFinalUserIds = array();
		foreach ($aUserIds as $iUserId) {
			$oUser =& User::get($iUserId);
			if (!(PEAR::isError($oUser) || ($oUser == false))) {
				$aFinalUserIds[] = $iUserId;
			}
		}
		if (empty($aFinalUserIds)) { $aFinalUserIds = null; }

		// hack straight in.
		$oPD = $oRoleAllocation->getPermissionDescriptor();
		$aAllowed = $oPD->getAllowed();



		// now, grab the existing allowed and modify.

		$aAllowed['user'] = $aFinalUserIds;

		$oRoleAllocation->setAllowed($aAllowed);
		$res = $oRoleAllocation->update();

		if (PEAR::isError($res) || ($res == false)) {
			$this->errorRedirectToMain(_kt('Failed to change the role allocation.') . print_r($res, true), sprintf('fFolderId=%d', $this->oFolder->getId()));
		}

        $oTransaction = KTFolderTransaction::createFromArray(array(
            'folderid' => $this->oFolder->getId(),
            'comment' => _kt('Set role users'),
            'transactionNS' => 'ktcore.transactions.role_allocations_change',
            'userid' => $_SESSION['userID'],
            'ip' => Session::getClientIP(),
        ));
        $aOptions = array(
            'defaultmessage' => _kt('Problem assigning role users'),
            'redirect_to' => array('main', sprintf('fFolderId=%d', $this->oFolder->getId())),
        );
        $this->oValidator->notErrorFalse($oTransaction, $aOptions);

		$this->renegeratePermissionsForRole($oRoleAllocation->getRoleId());

        $this->successRedirectToMain(_kt('Allocation changed.'), sprintf('fFolderId=%d',$this->oFolder->getId()));
    }

    function do_setRoleGroups() {

        $role_allocation_id = KTUtil::arrayGet($_REQUEST, 'allocation_id');
        $oRoleAllocation = RoleAllocation::get($role_allocation_id);
        if ((PEAR::isError($oRoleAllocation)) || ($oRoleAllocation=== false)) {
            $this->errorRedirectToMain(_kt('No such role allocation.'), sprintf('fFolderId=%d',$this->oFolder->getId()));
        }
        $groups = KTUtil::arrayGet($_REQUEST, 'groupFinal', '');
		$aGroupIds = explode(',', $groups);

		// check that its not corrupt..
		$aFinalGroupIds = array();
		foreach ($aGroupIds as $iGroupId) {
			$oGroup =& Group::get($iGroupId);
			if (!(PEAR::isError($oGroup) || ($oGroup == false))) {
				$aFinalGroupIds[] = $iGroupId;
			}
		}
		if (empty($aFinalGroupIds)) { $aFinalGroupIds = null; }

		// hack straight in.
		$oPD = $oRoleAllocation->getPermissionDescriptor();
		$aAllowed = $oPD->getAllowed();



		// now, grab the existing allowed and modify.

		$aAllowed['group'] = $aFinalGroupIds;

		$oRoleAllocation->setAllowed($aAllowed);
		$res = $oRoleAllocation->update();

		if (PEAR::isError($res) || ($res == false)) {
			$this->errorRedirectToMain(_kt('Failed to change the role allocation.') . print_r($res, true), sprintf('fFolderId=%d', $this->oFolder->getId()));
		}

        $oTransaction = KTFolderTransaction::createFromArray(array(
            'folderid' => $this->oFolder->getId(),
            'comment' => _kt('Set role groups'),
            'transactionNS' => 'ktcore.transactions.role_allocations_change',
            'userid' => $_SESSION['userID'],
            'ip' => Session::getClientIP(),
        ));
        $aOptions = array(
            'defaultmessage' => _kt('Problem assigning role groups'),
            'redirect_to' => array('main', sprintf('fFolderId=%d', $this->oFolder->getId())),
        );
        $this->oValidator->notErrorFalse($oTransaction, $aOptions);

		$this->renegeratePermissionsForRole($oRoleAllocation->getRoleId());

        $this->successRedirectToMain(_kt('Allocation changed.'), sprintf('fFolderId=%d',$this->oFolder->getId()));
    }

	function renegeratePermissionsForRole($iRoleId) {
	    $iStartFolderId = $this->oFolder->getId();
		/*
		 * 1. find all folders & documents "below" this one which use the role
		 *    definition _active_ (not necessarily present) at this point.
		 * 2. tell permissionutil to regen their permissions.
		 *
		 * The find algorithm is:
		 *
		 *  folder_queue <- (iStartFolderId)
		 *  while folder_queue is not empty:
		 *     active_folder =
		 *     for each folder in the active_folder:
		 *         find folders in _this_ folder without a role-allocation on the iRoleId
		 *            add them to the folder_queue
		 *         update the folder's permissions.
		 *         find documents in this folder:
		 *            update their permissions.
		 */

		$sRoleAllocTable = KTUtil::getTableName('role_allocations');
		$sFolderTable = KTUtil::getTableName('folders');
		$sQuery = sprintf('SELECT f.id as id FROM %s AS f LEFT JOIN %s AS ra ON (f.id = ra.folder_id) WHERE ra.id IS NULL AND f.parent_id = ?', $sFolderTable, $sRoleAllocTable);


		$folder_queue = array($iStartFolderId);
		while (!empty($folder_queue)) {
			$active_folder = array_pop($folder_queue);

			$aParams = array($active_folder);

			$aNewFolders = DBUtil::getResultArrayKey(array($sQuery, $aParams), 'id');
			if (PEAR::isError($aNewFolders)) {
				$this->errorRedirectToMain(_kt('Failure to generate folderlisting.'));
			}
			$folder_queue = kt_array_merge ($folder_queue, (array) $aNewFolders); // push.


			// update the folder.
			$oFolder =& Folder::get($active_folder);
			if (PEAR::isError($oFolder) || ($oFolder == false)) {
			    $this->errorRedirectToMain(_kt('Unable to locate folder: ') . $active_folder);
			}

			KTPermissionUtil::updatePermissionLookup($oFolder);
			$aDocList =& Document::getList(array('folder_id = ?', $active_folder));
			if (PEAR::isError($aDocList) || ($aDocList === false)) {
			    $this->errorRedirectToMain(sprintf(_kt('Unable to get documents in folder %s: %s'), $active_folder, $aDocList->getMessage()));
			}

			foreach ($aDocList as $oDoc) {
			    if (!PEAR::isError($oDoc)) {
			        KTPermissionUtil::updatePermissionLookup($oDoc);
				}
			}
		}
	}
}

class KTDocumentRolesAction extends KTDocumentAction {
    var $sName = 'ktcore.actions.document.roles';

    var $_sShowPermission = "ktcore.permissions.write";
    var $bAutomaticTransaction = true;

    function getDisplayName() {
        return _kt('View Roles');
    }

    function do_main() {
        $this->oPage->setTitle(_kt("View Roles"));
        $this->oPage->setBreadcrumbDetails(_kt("View Roles"));
        $oTemplating = new KTTemplating;
        $oTemplate = $oTemplating->loadTemplate("ktcore/action/view_roles");

        // we need to have:
        //   - a list of roles
        //   - with their users / groups
        //   - and that allocation id
        $aRoles = array(); // stores data for display.

        $aRoleList = Role::getList();
        foreach ($aRoleList as $oRole) {
            $iRoleId = $oRole->getId();
            $aRoles[$iRoleId] = array("name" => $oRole->getName());
            $oRoleAllocation = DocumentRoleAllocation::getAllocationsForDocumentAndRole($this->oDocument->getId(), $iRoleId);
			if (is_null($oRoleAllocation)) {
				$oRoleAllocation = RoleAllocation::getAllocationsForFolderAndRole($this->oDocument->getFolderID(), $iRoleId);
			}

            $u = array();
            $g = array();
            $aid = null;
            $raid = null;
            if (is_null($oRoleAllocation)) {
                ; // nothing.
            } else {
			    //var_dump($oRoleAllocation);
                $raid = $oRoleAllocation->getId(); // real_alloc_id
                $aAllowed = $oRoleAllocation->getAllowed();

                if (!empty($aAllowed['user'])) {
                    $u = $aAllowed['user'];
                }
                if (!empty($aAllowed['group'])) {
                    $g = $aAllowed['group'];
				}
			}
            $aRoles[$iRoleId]['users'] = $u;
            $aRoles[$iRoleId]['groups'] = $g;
            $aRoles[$iRoleId]['real_allocation_id'] = $raid;
        }

        // final step.

        // map to users, groups.
        foreach ($aRoles as $key => $role) {
            $_users = array();
            foreach ($aRoles[$key]['users'] as $iUserId) {
                $oUser = User::get($iUserId);
                if (!(PEAR::isError($oUser) || ($oUser == false))) {
                    $_users[] = $oUser->getName();
                }
            }
			if (empty($_users)) {
			    $aRoles[$key]['users'] = '<span class="descriptiveText"> ' . _kt('no users') . '</span>';
			} else {
			    $aRoles[$key]['users'] = implode(', ',$_users);
			}

            $_groups = array();
            foreach ($aRoles[$key]['groups'] as $iGroupId) {
                $oGroup = Group::get($iGroupId);
                if (!(PEAR::isError($oGroup) || ($oGroup == false))) {
                    $_groups[] = $oGroup->getName();
                }
            }
			if (empty($_groups)) {
			    $aRoles[$key]['groups'] = '<span class="descriptiveText"> ' . _kt('no groups') . '</span>';
			} else {
			    $aRoles[$key]['groups'] = implode(', ',$_groups);
			}
        }

        $aTemplateData = array(
            'context' => &$this,
            'roles' => $aRoles,
        );
        return $oTemplate->render($aTemplateData);
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?