07687ab2 by Jeff Balicki

user Access Manager

Signed-off-by: Jeff <jeff@gotenzing.com>
1 parent d0336690
Showing 167 changed files with 4894 additions and 0 deletions
# Contributing to User Access Manager
* The coding style must PSR-2
* The unit test code coverage must be 100% expect for the views and the wrappers
* The _Humbug Mutation Score Indicator_ must be 100% (all mutants must be killed)
\ No newline at end of file
/*
uamAdmin.css
The file is needed for the uam admin style.
--- DO NOT EDIT THIS FILE ---
*/
.uam_main {
margin-right: 280px;
}
.uam_sidebar {
float: right;
width: 260px;
}
.uam_info_box {
width: 240px;
margin: 9px 0;
border: 1px solid #e5e5e5;
background: #fff;
padding: 16px 10px;
position: absolute;
}
.uam_info_box--head {
font-weight: bold;
font-size: 16px;
margin: 16px 0 6px;
display: block;
}
.uam_info_box--head:first-child {
margin-top: 0;
}
.uam_info_box--content {
display: block;
margin: 8px 0;
}
#toplevel_page_uam_user_group div.wp-menu-image {
background: transparent url('../gfx/icon.png') no-repeat scroll center 0;
height: 32px;
}
#toplevel_page_uam_user_group:hover div.wp-menu-image,
#toplevel_page_uam_user_group.wp-has-current-submenu div.wp-menu-image {
background: transparent url('../gfx/icon.png') no-repeat scroll center -28px;
}
ul.uam_group_selection > li {
position: relative;
}
ul.uam_group_selection > li > input {
position: absolute;
top: 6px;
}
ul.uam_group_selection > li > label {
margin-left: 24px;
display: inline-block;
}
.uam_group_date {
font-size: 11px;
margin-left: 24px;
display: block;
cursor: pointer;
font-weight: bold;
}
.uam_group_date_form {
margin-left: 24px;
display: none;
}
.uam_default_groups .uam_group_date_form {
display: block;
}
.uam_group_date_form label {
width: 65px;
display: inline-block;
}
.uam_group_date_form input {
width: 160px;
font-size: 12px;
}
@media (max-width: 782px) {
.uam_group_date,
.uam_group_date_form,
ul.uam_group_selection > li > label {
margin-left: auto;
}
ul.uam_group_selection > li > input {
position: static;
}
}
ul.uam_group_selection_ajax > li > input {
margin-top: 2px !important;
}
.compat-field-uam_user_groups .field {
width: 100%;
margin-bottom: 100px;
}
.uam_group_info_link {
cursor: pointer;
font-weight: bold;
}
.uam_group_info ul {
display: block !important;
padding: 0 !important;
margin: 0 !important;
list-style: none !important;
}
.uam_group_info ul li {
padding: 0 !important;
margin: 0 !important;
}
.uam_group_info ul li.recursiveTree ul li:before {
content: "— ";
}
.uam_group_info ul li.recursiveTree ul li ul li:before {
content: "—— ";
}
.uam_group_info ul li.recursiveTree ul li ul li ul li:before {
content: "——— ";
}
.uam_group_info_head {
list-style: none;
font-weight: bold;
}
.uam_group_info_head ul {
font-weight: normal;
}
.uam_group_selection_ajax li a,
.uam_group_selection li a {
vertical-align: middle;
}
.uam_tooltip {
z-index: 1000;
display: none;
min-width: 200px;
color: #000 !important;
background-color: #F9F9F9 !important;
padding: 4px 8px !important;
border: 1px solid #DFDFDF !important;
position: absolute;
}
.uam_group_info_link:hover + .uam_tooltip {
display: block;
}
#uam_dynamic_groups {
height: 28px;
margin: 0 4px 0 0;
}
.uam_supporters {
list-style: disc;
padding-left: 20px;
}
\ No newline at end of file
/*
uamLoginForm.css
The file for the login form style.
Modify this file to change the style of the login form.
*/
.uam_login_link {
}
.uam_login_form {
position: relative;
}
.uam_login_form .input {
display: block;
}
.uam_login_form .input_label {
display: block;
}
.uam_login_form .checkbox {
}
.uam_login_form .checkbox_label {
left: 20px;
}
.uam_login_form .button {
display: block;
}
.uam_login_options {
}
.uam_login_options a {
}
\ No newline at end of file
jQuery(document).ready(function ($) {
jQuery('.uam_group_selection').on('click', '.uam_group_date', function () {
var $element = jQuery(this);
var $next = $element.next('.uam_group_date_form');
$next.toggle();
$element.hide();
});
//Functions for the setting page
var toggleGroup = function (group, elementIndex, hiddenFlag, elementsToHide) {
hiddenFlag = hiddenFlag || 'true';
var $group = jQuery(group);
var $inputs = jQuery('tr:eq('+elementIndex+') input', $group);
var toggleElement = function (element) {
var $element = jQuery(element);
var $subElements = jQuery('tr:gt('+elementIndex+')', $group);
var currentState = ($element.val() === hiddenFlag);
elementsToHide = elementsToHide || $subElements.length;
for (var index = 0; index < $subElements.length; index++) {
var $subElement = jQuery($subElements[index]);
var data = $subElement.data('hidden') || {};
data[elementIndex] = (index < elementsToHide) ? currentState : !currentState;
$subElement.data('hidden', data);
var showElement = true;
jQuery.each(data, function(key, value) {
if (value === true) {
showElement = false;
return null;
}
});
$subElement.toggle(showElement);
}
};
$inputs.on('change', function () {
toggleElement(this);
});
toggleElement($inputs.filter(':checked'));
};
toggleGroup('.uam_settings_group_post_type', 0);
toggleGroup('.uam_settings_group_post_type:not(.default)', 1);
toggleGroup('.uam_settings_group_taxonomies:not(.default)', 0);
toggleGroup('.uam_settings_group_file:not(.default)', 1);
toggleGroup('#uam_settings_group_file', 0, 'false');
toggleGroup('#uam_settings_group_file', 4, 'false', 1);
// Functions for the setup page
jQuery('#uam_reset_confirm').on('change paste keyup', function () {
var $button = jQuery('#uam_reset_submit');
if (jQuery(this).val() === 'reset') {
$button.removeAttr('disabled');
} else if (typeof $button.attr('disabled') === 'undefined') {
$button.attr('disabled', 'disabled');
}
});
jQuery('#uam_settings_group_section').on('change', function () {
var $selected = jQuery(this).find(':selected');
window.location.href = $selected.data('link');
});
/** global: ajaxurl */
$('#uam_dynamic_groups').uamGroupSuggest(ajaxurl + '?action=uam-get-dynamic-group', { delay: 500, multiple: true });
$('.uam_time_input').uamTimeInput();
});
\ No newline at end of file
(function($) {
var delay = (function() {
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
var convertRawChunksToTime = function(chunks) {
var caps = [999, 24, 60, 60];
chunks = chunks.map(function(num) { return parseInt(num); });
for (var i = 4; i >= 0; i--) {
if (chunks[i] >= caps[i]) {
if (i - 1 >= 0) {
var times = Math.floor(chunks[i] / caps[i]);
chunks[i-1] += times;
chunks[i] = chunks[i] - (times * caps[i]);
} else {
chunks[i] = caps[i];
}
}
}
return chunks;
};
var formatChunks = function(chunks) {
return chunks[0].toString().padStart(3, 0) + '-'
+ chunks.slice(1, 4).map(function (element) {
return element.toString().padStart(2, 0);
}).join(':');
};
var convertChunksToSeconds = function(chunks) {
var multiples = [24, 60, 60, 1];
return chunks.reduce(function (sum, value, index) {
var multiplier = multiples.slice(index, multiples.length).reduce(function (product, value) {
return product * value;
});
return sum + value * multiplier;
}, 0);
};
$.uamTimeInput = function(targetInput) {
var $input = $(targetInput);
var $newInput = $input.clone().attr('name', '');
$input.hide().before($newInput);
var existingValue = $input.val();
if (existingValue !== '') {
$newInput.val(formatChunks(convertRawChunksToTime([0, 0, 0, existingValue * 1])));
}
$newInput.on('keyup', function (event) {
var $this = $(this);
var selection = window.getSelection().toString();
var rawInput = $this.val();
if (selection !== ''
|| rawInput === ''
|| $.inArray(event.keyCode, [38, 40, 37, 39]) !== -1
) {
return;
}
var domElement = $this.get(0);
var cursorStart = domElement.selectionStart;
var cursorEnd = domElement.selectionEnd;
var inputRegex = /(\d{3})(\d{2})(\d{2})(\d{2})/g;
var inputValue = rawInput.replace(/^\D+|:|-/g, '')
.substr(0, 9)
.padStart(9, 0);
var chunks = inputRegex.exec(inputValue);
chunks = convertRawChunksToTime([chunks[1], chunks[2], chunks[3], chunks[4]]);
$input.val(convertChunksToSeconds(chunks));
delay(function () {
$this.val(formatChunks(chunks));
domElement.setSelectionRange(cursorStart, cursorEnd);
}, 1000);
});
};
$.fn.uamTimeInput = function () {
this.each(function() {
$.uamTimeInput(this);
});
return this;
}
})(jQuery);
\ No newline at end of file
{
"name": "gmalex/user-access-manager",
"description": "User Access Manager plugin for Wordpress",
"type": "wordpress-plugin",
"license": "GPL-2.0",
"version": "2.2.23",
"authors": [
{
"name": "Alexander Schneider",
"email": "alexanderschneider85@gmail.com"
}
],
"require": {
"php": ">=7.2"
},
"require-dev": {
"phpunit/phpunit": "^8.5 || ^9.5",
"wp-cli/wp-cli": "^v2.4.1",
"adlawson/vfs": "^0.12",
"infection/infection": "^0.15 || ^0.21",
"squizlabs/php_codesniffer": "^3.5",
"johnpbloch/wordpress-core": "^5.8",
"php-vcr/php-vcr": "^1.5"
},
"autoload": {
"psr-4": {
"UserAccessManager\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"UserAccessManager\\Tests\\": "tests/"
}
}
}
This diff could not be displayed because it is too large.
{
"timeout": 60,
"source": {
"directories": [
"src/Access",
"src/Cache",
"src/Command",
"src/Config",
"src/Controller",
"src/Database",
"src/File",
"src/Form",
"src/Object",
"src/ObjectMembership",
"src/Setup",
"src/User",
"src/UserGroup",
"src/Util",
"src/Widget"
],
"excludes": [
"vendor",
"tests"
]
},
"testFramework": "phpunit",
"bootstrap": "./tests/bootstrap.php",
"logs": {
"text": "infection.txt"
},
"mutators": {
"@default": true,
"@cast": false,
"@function_signature": false,
"MethodCallRemoval": {
"ignore": [
"UserAccessManager\\Command\\GroupCommand::__construct",
"UserAccessManager\\Command\\ObjectCommand::__construct"
]
},
"IncrementInteger": {
"ignore": [
"UserAccessManager\\Controller\\Backend\\ObjectController::sortUserGroups"
]
},
"DecrementInteger": {
"ignore": [
"UserAccessManager\\Controller\\Backend\\ObjectController::sortUserGroups"
]
},
"UnwrapUcFirst": {
"ignore": [
"UserAccessManager\\Controller\\Backend\\UserGroupController::getUserGroups"
]
},
"FunctionCallRemoval": {
"ignore": [
"UserAccessManager\\Controller\\BaseControllerTrait::getIncludeContents"
]
},
"UnwrapArrayMap": {
"ignore": [
"UserAccessManager\\Controller\\Controller::processAction"
]
},
"UnwrapStrReplace": {
"ignore": [
"UserAccessManager\\Controller\\Frontend\\RedirectController::getFileSettingsByType"
]
}
}
}
\ No newline at end of file
<?php
//Classes
use UserAccessManager\Access\AccessHandler;
use UserAccessManager\Cache\Cache;
use UserAccessManager\Config\MainConfig;
use UserAccessManager\Config\ConfigFactory;
use UserAccessManager\Config\ConfigParameterFactory;
use UserAccessManager\Config\WordpressConfig;
use UserAccessManager\Cache\CacheProviderFactory;
use UserAccessManager\Controller\ControllerFactory;
use UserAccessManager\Controller\Backend\ObjectInformationFactory;
use UserAccessManager\Widget\WidgetFactory;
use UserAccessManager\Database\Database;
use UserAccessManager\File\FileHandler;
use UserAccessManager\File\FileObjectFactory;
use UserAccessManager\File\FileProtectionFactory;
use UserAccessManager\Form\FormFactory;
use UserAccessManager\Form\FormHelper;
use UserAccessManager\Object\ObjectHandler;
use UserAccessManager\Object\ObjectMapHandler;
use UserAccessManager\ObjectMembership\ObjectMembershipHandlerFactory;
use UserAccessManager\Setup\Database\DatabaseObjectFactory;
use UserAccessManager\Setup\Database\DatabaseHandler;
use UserAccessManager\Setup\SetupHandler;
use UserAccessManager\Setup\Update\UpdateFactory;
use UserAccessManager\UserAccessManager;
use UserAccessManager\UserGroup\AssignmentInformationFactory;
use UserAccessManager\UserGroup\UserGroupAssignmentHandler;
use UserAccessManager\UserGroup\UserGroupFactory;
use UserAccessManager\UserGroup\UserGroupHandler;
use UserAccessManager\User\UserHandler;
use UserAccessManager\Util\Util;
use UserAccessManager\Util\DateUtil;
use UserAccessManager\Wrapper\Php;
use UserAccessManager\Wrapper\Wordpress;
function initUserAccessManger()
{
$file = str_replace('init.php', 'user-access-manager.php', __FILE__);
$php = new Php();
$wordpress = new Wordpress();
$util = new Util($php);
$dateUtil = new DateUtil($wordpress);
$configFactory = new ConfigFactory($wordpress);
$configParameterFactory = new ConfigParameterFactory();
$cacheProviderFactory = new CacheProviderFactory($php, $wordpress, $util, $configFactory, $configParameterFactory);
$cache = new Cache($wordpress, $cacheProviderFactory);
$database = new Database($wordpress);
$objectMapHandler = new ObjectMapHandler($database, $cache);
$assignmentInformationFactory = new AssignmentInformationFactory();
$membershipHandlerFactory = new ObjectMembershipHandlerFactory(
$php,
$wordpress,
$database,
$objectMapHandler,
$assignmentInformationFactory
);
$objectHandler = new ObjectHandler($php, $wordpress, $membershipHandlerFactory);
$wordpressConfig = new WordpressConfig($wordpress, $file);
$mainConfig = new MainConfig($wordpress, $objectHandler, $cache, $configParameterFactory);
$fileObjectFactory = new FileObjectFactory();
$formFactory = new FormFactory();
$formHelper = new FormHelper($php, $wordpress, $mainConfig, $formFactory);
$userGroupFactory = new UserGroupFactory(
$php,
$wordpress,
$database,
$mainConfig,
$util,
$objectHandler,
$assignmentInformationFactory
);
$userHandler = new UserHandler(
$wordpress,
$mainConfig,
$database,
$objectHandler
);
$userGroupHandler = new UserGroupHandler(
$wordpress,
$wordpressConfig,
$mainConfig,
$database,
$objectHandler,
$userHandler,
$userGroupFactory
);
$accessHandler = new AccessHandler(
$wordpress,
$mainConfig,
$database,
$objectHandler,
$userHandler,
$userGroupHandler
);
$fileProtectionFactory = new FileProtectionFactory(
$php,
$wordpress,
$wordpressConfig,
$mainConfig,
$util
);
$fileHandler = new FileHandler(
$php,
$wordpress,
$wordpressConfig,
$mainConfig,
$fileProtectionFactory
);
$updateFactory = new UpdateFactory($database, $objectHandler);
$databaseObjectFactory = new DatabaseObjectFactory();
$databaseHandler = new DatabaseHandler($wordpress, $database, $databaseObjectFactory, $updateFactory);
$setupHandler = new SetupHandler(
$wordpress,
$database,
$databaseHandler,
$mainConfig,
$fileHandler
);
$objectInformationFactory = new ObjectInformationFactory();
$userGroupAssignmentHandler = new UserGroupAssignmentHandler(
$dateUtil,
$userHandler,
$userGroupHandler,
$userGroupFactory
);
$controllerFactory = new ControllerFactory(
$php,
$wordpress,
$database,
$wordpressConfig,
$mainConfig,
$util,
$dateUtil,
$cache,
$objectHandler,
$objectMapHandler,
$userHandler,
$userGroupHandler,
$userGroupFactory,
$userGroupAssignmentHandler,
$accessHandler,
$fileHandler,
$fileObjectFactory,
$setupHandler,
$formFactory,
$formHelper,
$objectInformationFactory
);
$widgetFactory = new WidgetFactory($php, $wordpress, $wordpressConfig);
$userAccessManager = new UserAccessManager(
$php,
$wordpress,
$util,
$cache,
$mainConfig,
$database,
$objectHandler,
$userHandler,
$userGroupHandler,
$accessHandler,
$fileHandler,
$setupHandler,
$userGroupFactory,
$membershipHandlerFactory,
$controllerFactory,
$widgetFactory,
$cacheProviderFactory,
$configFactory,
$configParameterFactory,
$fileProtectionFactory,
$fileObjectFactory
);
$wordpress->doAction('uam_init', [$userAccessManager]);
//install
if (function_exists('register_activation_hook') === true) {
register_activation_hook($file, [$setupHandler, 'install']);
}
//uninstall
if (function_exists('register_uninstall_hook')) {
function uninstallUserAccessManager()
{
$file = str_replace('init.php', 'user-access-manager.php', __FILE__);
$php = new Php();
$wordpress = new Wordpress();
$util = new Util($php);
$database = new Database($wordpress);
$configFactory = new ConfigFactory($wordpress);
$configParameterFactory = new ConfigParameterFactory();
$cacheProviderFactory = new CacheProviderFactory(
$php,
$wordpress,
$util,
$configFactory,
$configParameterFactory
);
$cache = new Cache($wordpress, $cacheProviderFactory);
$objectMapHandler = new ObjectMapHandler($database, $cache);
$assignmentInformationFactory = new AssignmentInformationFactory();
$membershipHandlerFactory = new ObjectMembershipHandlerFactory(
$php,
$wordpress,
$database,
$objectMapHandler,
$assignmentInformationFactory
);
$objectHandler = new ObjectHandler($php, $wordpress, $membershipHandlerFactory);
$wordpressConfig = new WordpressConfig($wordpress, $file);
$mainConfig = new MainConfig($wordpress, $objectHandler, $cache, $configParameterFactory);
$fileProtectionFactory = new FileProtectionFactory(
$php,
$wordpress,
$wordpressConfig,
$mainConfig,
$util
);
$fileHandler = new FileHandler(
$php,
$wordpress,
$wordpressConfig,
$mainConfig,
$fileProtectionFactory
);
$updateFactory = new UpdateFactory($database, $objectHandler);
$databaseObjectFactory = new DatabaseObjectFactory();
$databaseHandler = new DatabaseHandler($wordpress, $database, $databaseObjectFactory, $updateFactory);
$setupHandler = new SetupHandler(
$wordpress,
$database,
$databaseHandler,
$mainConfig,
$fileHandler
);
$setupHandler->uninstall();
}
register_uninstall_hook($file, 'uninstallUserAccessManager');
}
//deactivation
if (function_exists('register_deactivation_hook')) {
register_deactivation_hook($file, [$setupHandler, 'deactivate']);
}
$userAccessManager->addActionsAndFilters();
//Add the cli interface to the known commands
if (defined('WP_CLI') === true && WP_CLI === true) {
$cliWrapper = new \UserAccessManager\Wrapper\WordpressCli();
$groupCommand = new \UserAccessManager\Command\GroupCommand($cliWrapper, $userGroupHandler, $userGroupFactory);
$objectCommand = new \UserAccessManager\Command\ObjectCommand($cliWrapper, $userGroupHandler);
try {
\WP_CLI::add_command('uam groups', $groupCommand);
\WP_CLI::add_command('uam objects', $objectCommand);
} catch (Exception $exception) {
// Do nothing
}
}
return $userAccessManager;
}
<?php
/**
* AccessHandler.php
*
* The AccessHandler class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Access;
use Exception;
use UserAccessManager\Config\MainConfig;
use UserAccessManager\Database\Database;
use UserAccessManager\Object\ObjectHandler;
use UserAccessManager\User\UserHandler;
use UserAccessManager\UserGroup\AbstractUserGroup;
use UserAccessManager\UserGroup\UserGroupHandler;
use UserAccessManager\UserGroup\UserGroupTypeException;
use UserAccessManager\Wrapper\Wordpress;
/**
* Class AccessHandler
* @package UserAccessManager\AccessHandler
*/
class AccessHandler
{
/**
* @var Wordpress
*/
private $wordpress;
/**
* @var MainConfig
*/
private $mainConfig;
/**
* @var Database
*/
private $database;
/**
* @var ObjectHandler
*/
private $objectHandler;
/**
* @var UserHandler
*/
private $userHandler;
/**
* @var UserGroupHandler
*/
private $userGroupHandler;
/**
* @var null|array
*/
private $excludedTerms = null;
/**
* @var null|array
*/
private $excludedPosts = null;
/**
* @var array
*/
private $objectAccess = [];
/**
* @var null|array
*/
private $noneHiddenPostTypes = null;
/**
* AccessHandler constructor.
* @param Wordpress $wordpress
* @param MainConfig $mainConfig
* @param Database $database
* @param ObjectHandler $objectHandler
* @param UserHandler $userHandler
* @param UserGroupHandler $userGroupHandler
*/
public function __construct(
Wordpress $wordpress,
MainConfig $mainConfig,
Database $database,
ObjectHandler $objectHandler,
UserHandler $userHandler,
UserGroupHandler $userGroupHandler
) {
$this->wordpress = $wordpress;
$this->mainConfig = $mainConfig;
$this->database = $database;
$this->objectHandler = $objectHandler;
$this->userHandler = $userHandler;
$this->userGroupHandler = $userGroupHandler;
}
/**
* Checks it the user has access because he is the author.
* @param string $objectType
* @param int|string $objectId
* @return bool
*/
private function hasAuthorAccess(string $objectType, $objectId): bool
{
if ($this->mainConfig->authorsHasAccessToOwn() === true
&& $this->objectHandler->isPostType($objectType)
) {
$post = $this->objectHandler->getPost($objectId);
return $post !== false
&& $this->wordpress->getCurrentUser()->ID === (int) $post->post_author;
}
return false;
}
/**
* Checks if the is admin value is set if not grabs it from the wordpress function.
* @param null|bool $isAdmin
* @return bool
*/
private function isAdmin(?bool $isAdmin): bool
{
return ($isAdmin === null) ? $this->wordpress->isAdmin() : $isAdmin;
}
/**
* Returns the user user groups filtered by the write access.
* @param bool|null $isAdmin If set we force the admin mode.
* @return AbstractUserGroup[]
* @throws UserGroupTypeException
*/
private function getUserUserGroupsForObjectAccess(?bool $isAdmin = null): array
{
$userUserGroups = $this->userGroupHandler->getUserGroupsForUser();
if ($this->isAdmin($isAdmin) === true) {
$userUserGroups = array_filter(
$userUserGroups,
function (AbstractUserGroup $userGroup) {
return $userGroup->getWriteAccess() !== 'none';
}
);
}
return $this->wordpress->applyFilters('uam_get_user_user_groups_for_object_access', $userUserGroups, $isAdmin);
}
/**
* Checks if the current_user has access to the given post.
* @param string|null $objectType The object type which should be checked.
* @param int|string $objectId The id of the object.
* @param null|bool $isAdmin If set we force the admin mode.
* @return bool
* @throws UserGroupTypeException
* @throws Exception
*/
public function checkObjectAccess(?string $objectType, $objectId, ?bool $isAdmin = null): bool
{
$isAdmin = $this->isAdmin($isAdmin);
if (isset($this->objectAccess[$isAdmin][$objectType][$objectId]) === false) {
if ($this->objectHandler->isValidObjectType($objectType) === false
|| $this->userHandler->checkUserAccess(UserHandler::MANAGE_USER_GROUPS_CAPABILITY) === true
|| $this->hasAuthorAccess($objectType, $objectId) === true
) {
$access = true;
} else {
$membership = $this->userGroupHandler->getUserGroupsForObject($objectType, $objectId);
$access = $membership === []
|| array_intersect_key($membership, $this->getUserUserGroupsForObjectAccess($isAdmin)) !== [];
if ($access && $this->wordpress->isUserLoggedIn() && $this->wordpress->isMultiSite()) {
$access = $this->wordpress->isUserMemberOfBlog();
}
}
$this->objectAccess[$isAdmin][$objectType][$objectId] = $access;
}
return $this->objectAccess[$isAdmin][$objectType][$objectId];
}
/**
* Returns the excluded objects.
* @param string $type
* @param array $filterTypesMap
* @return array
* @throws UserGroupTypeException
* @throws Exception
*/
private function getExcludedObjects(string $type, array $filterTypesMap = []): array
{
$excludedObjects = [];
$userGroups = $this->userGroupHandler->getFullUserGroups();
foreach ($userGroups as $userGroup) {
$excludedObjects += $userGroup->getAssignedObjectsByType($type);
}
$userUserGroups = $this->userGroupHandler->getUserGroupsForUser();
foreach ($userUserGroups as $userGroup) {
$excludedObjects = array_diff_key($excludedObjects, $userGroup->getAssignedObjectsByType($type));
}
if ($filterTypesMap !== []) {
$excludedObjects = array_filter(
$excludedObjects,
function ($element) use ($filterTypesMap) {
return isset($filterTypesMap[$element]) === false;
}
);
}
$objectIds = array_keys($excludedObjects);
return array_combine($objectIds, $objectIds);
}
/**
* Returns the excluded terms for a user.
* @return array
* @throws UserGroupTypeException
*/
public function getExcludedTerms(): ?array
{
if ($this->userHandler->checkUserAccess(UserHandler::MANAGE_USER_GROUPS_CAPABILITY)) {
$this->excludedTerms = [];
}
if ($this->excludedTerms === null) {
$this->excludedTerms = $this->getExcludedObjects(ObjectHandler::GENERAL_TERM_OBJECT_TYPE);
}
return $this->excludedTerms;
}
/**
* Returns the none hidden post types map.
* @return array
*/
private function getNoneHiddenPostTypes(): ?array
{
if ($this->noneHiddenPostTypes === null) {
$this->noneHiddenPostTypes = [];
if ($this->wordpress->isAdmin() === false) {
$postTypes = $this->objectHandler->getPostTypes();
foreach ($postTypes as $postType) {
if ($this->mainConfig->hidePostType($postType) === false) {
$this->noneHiddenPostTypes[$postType] = $postType;
}
}
}
}
return $this->noneHiddenPostTypes;
}
/**
* Returns the excluded posts.
* @return array
* @throws UserGroupTypeException
*/
public function getExcludedPosts(): ?array
{
if ($this->userHandler->checkUserAccess(UserHandler::MANAGE_USER_GROUPS_CAPABILITY)) {
$this->excludedPosts = [];
}
if ($this->excludedPosts === null) {
$noneHiddenPostTypes = $this->getNoneHiddenPostTypes();
$excludedPosts = $this->getExcludedObjects(ObjectHandler::GENERAL_POST_OBJECT_TYPE, $noneHiddenPostTypes);
if ($this->mainConfig->authorsHasAccessToOwn() === true) {
$query = $this->database->prepare(
"SELECT ID FROM {$this->database->getPostsTable()}
WHERE post_author = %d",
$this->wordpress->getCurrentUser()->ID
);
$ownPosts = array_filter(
(array) $this->database->getResults($query),
function ($ownPost) {
return isset($ownPost->ID);
}
);
$ownPostIds = [];
foreach ($ownPosts as $ownPost) {
$ownPostIds[$ownPost->ID] = $ownPost->ID;
}
$excludedPosts = array_diff_key($excludedPosts, $ownPostIds);
}
$this->excludedPosts = $excludedPosts;
}
return $this->excludedPosts;
}
}
<?php
/**
* Cache.php
*
* The Cache class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Cache;
use UserAccessManager\Wrapper\Wordpress;
/**
* Class Cache
*
* @package UserAccessManager\Cache
*/
class Cache
{
/**
* @var Wordpress
*/
private $wordpress;
/**
* @var CacheProviderFactory
*/
private $cacheProviderFactory;
/**
* @var null|CacheProviderInterface
*/
private $cacheProvider = null;
/**
* @var array
*/
private $cache = [];
/**
* @var array
*/
private $runtimeCache = [];
/**
* Cache constructor.
* @param Wordpress $wordpress
* @param CacheProviderFactory $cacheProviderFactory
*/
public function __construct(Wordpress $wordpress, CacheProviderFactory $cacheProviderFactory)
{
$this->wordpress = $wordpress;
$this->cacheProviderFactory = $cacheProviderFactory;
}
/**
* Return the cache provider.
* @return CacheProviderInterface|null
*/
public function getCacheProvider(): ?CacheProviderInterface
{
return $this->cacheProvider;
}
/**
* Sets a cache provider
* @param null|string $key
*/
public function setActiveCacheProvider(?string $key)
{
$cacheProviders = $this->getRegisteredCacheProviders();
$this->cacheProvider = (isset($cacheProviders[$key]) === true) ? $cacheProviders[$key] : null;
if ($this->cacheProvider !== null) {
$this->cacheProvider->init();
}
}
/**
* Returns a generated cache key.
* @return string
*/
public function generateCacheKey(): string
{
$arguments = func_get_args();
return implode('|', $arguments);
}
/**
* Adds the variable to the cache.
* @param string $key The cache key
* @param mixed $value The value.
*/
public function add(string $key, $value)
{
if ($this->cacheProvider !== null) {
$this->cacheProvider->add($key, $value);
}
$this->cache[$key] = $value;
}
/**
* Returns a value from the cache by the given key.
* @param string $key
* @return mixed
*/
public function get(string $key)
{
if (isset($this->cache[$key]) === false) {
$this->cache[$key] = ($this->cacheProvider !== null) ? $this->cacheProvider->get($key) : null;
}
return $this->cache[$key];
}
/**
* Invalidates the cached object.
* @param string $key
*/
public function invalidate(string $key)
{
if ($this->cacheProvider !== null) {
$this->cacheProvider->invalidate($key);
}
unset($this->cache[$key]);
}
/**
* Adds the variable to the runtime cache.
* @param string $key The cache key
* @param mixed $value The value.
*/
public function addToRuntimeCache(string $key, $value)
{
$this->runtimeCache[$key] = $value;
}
/**
* Returns a value from the runtime cache by the given key.
* @param string $key
* @return mixed
*/
public function getFromRuntimeCache(string $key)
{
if (isset($this->runtimeCache[$key]) === true) {
return $this->runtimeCache[$key];
}
return null;
}
/**
* Flushes the cache.
*/
public function flushCache()
{
$this->cache = [];
$this->runtimeCache = [];
}
/**
* Returns a list of the registered cache handlers.
* @return CacheProviderInterface[]
*/
public function getRegisteredCacheProviders(): array
{
$fileSystemCacheProvider = $this->cacheProviderFactory->createFileSystemCacheProvider();
return $this->wordpress->applyFilters(
'uam_registered_cache_handlers',
[$fileSystemCacheProvider->getId() => $fileSystemCacheProvider]
);
}
}
<?php
/**
* CacheProviderFactory.php
*
* The CacheProviderFactory class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Cache;
use UserAccessManager\Config\ConfigFactory;
use UserAccessManager\Config\ConfigParameterFactory;
use UserAccessManager\Util\Util;
use UserAccessManager\Wrapper\Php;
use UserAccessManager\Wrapper\Wordpress;
/**
* Class CacheProviderFactory
*
* @package UserAccessManager\Cache
*/
class CacheProviderFactory
{
/**
* @var Php
*/
private $php;
/**
* @var Wordpress
*/
private $wordpress;
/**
* @var Util
*/
private $util;
/**
* @var ConfigFactory
*/
private $configFactory;
/**
* @var ConfigParameterFactory
*/
private $configParameterFactory;
/**
* CacheProviderFactory constructor.
* @param Php $php
* @param Wordpress $wordpress
* @param Util $util
* @param ConfigFactory $configFactory
* @param ConfigParameterFactory $configParameterFactory
*/
public function __construct(
Php $php,
Wordpress $wordpress,
Util $util,
ConfigFactory $configFactory,
ConfigParameterFactory $configParameterFactory
) {
$this->php = $php;
$this->wordpress = $wordpress;
$this->util = $util;
$this->configFactory = $configFactory;
$this->configParameterFactory = $configParameterFactory;
}
/**
* Creates a FileSystemCacheProvider object.
* @return FileSystemCacheProvider
*/
public function createFileSystemCacheProvider(): FileSystemCacheProvider
{
return new FileSystemCacheProvider(
$this->php,
$this->wordpress,
$this->util,
$this->configFactory,
$this->configParameterFactory
);
}
}
<?php
/**
* CacheProviderInterface.php
*
* The CacheProviderInterface interface file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Cache;
use UserAccessManager\Config\Config;
/**
* Interface CacheProviderInterface
*
* @package UserAccessManager\Cache
*/
interface CacheProviderInterface
{
/**
* Returns the id of the cache provider.
* @return string
*/
public function getId(): string;
/**
* Initialises the cache provider object.
*/
public function init();
/**
* Returns the cache provider configuration.
* @return Config
*/
public function getConfig(): Config;
/**
* Adds a value to the cache.
* @param string $key
* @param mixed $value
*/
public function add(string $key, $value);
/**
* Returns a value from the cache.
* @param string $key
* @return mixed
*/
public function get(string $key);
/**
* Invalidates the cache.
* @param string $key
*/
public function invalidate(string $key);
}
<?php
/**
* FileSystemCacheProvider.php
*
* The FileSystemCacheProvider interface file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Cache;
use Exception;
use UserAccessManager\Config\Config;
use UserAccessManager\Config\ConfigFactory;
use UserAccessManager\Config\ConfigParameterFactory;
use UserAccessManager\Util\Util;
use UserAccessManager\Wrapper\Php;
use UserAccessManager\Wrapper\Wordpress;
/**
* Class FileSystemCacheProvider
*
* @package UserAccessManager\Cache
*/
class FileSystemCacheProvider implements CacheProviderInterface
{
const ID = 'FileSystemCacheProvider';
const CONFIG_KEY = 'uam_file_system_cache_provider';
const CONFIG_PATH = 'fs_cache_path';
const CONFIG_METHOD = 'fs_cache_method';
const METHOD_SERIALIZE = 'serialize';
const METHOD_IGBINARY = 'igbinary';
const METHOD_JSON = 'json';
const METHOD_VAR_EXPORT = 'var_export';
/**
* @var Php
*/
private $php;
/**
* @var Wordpress
*/
private $wordpress;
/**
* @var Util
*/
private $util;
/**
* @var ConfigFactory
*/
private $configFactory;
/**
* @var ConfigParameterFactory
*/
private $configParameterFactory;
/**
* @var null|Config
*/
private $config = null;
/**
* @var string
*/
private $path = null;
/**
* FileSystemCacheProvider constructor.
* @param Php $php
* @param Wordpress $wordpress
* @param Util $util
* @param ConfigFactory $configFactory
* @param ConfigParameterFactory $configParameterFactory
*/
public function __construct(
Php $php,
Wordpress $wordpress,
Util $util,
ConfigFactory $configFactory,
ConfigParameterFactory $configParameterFactory
) {
$this->php = $php;
$this->wordpress = $wordpress;
$this->util = $util;
$this->configFactory = $configFactory;
$this->configParameterFactory = $configParameterFactory;
}
/**
* Returns the id.
* @return string
*/
public function getId(): string
{
return self::ID;
}
/**
* Returns the cache path.
* @return string
* @throws Exception
*/
private function getPath(): string
{
if ($this->path === null) {
$this->path = $this->getConfig()->getParameterValue(self::CONFIG_PATH);
if ($this->util->endsWith($this->path, DIRECTORY_SEPARATOR) === false) {
$this->path .= DIRECTORY_SEPARATOR;
}
}
return $this->path;
}
/**
* Initialise the caching path.
* @throws Exception
*/
public function init()
{
$path = $this->getPath();
if (is_dir($path) === false) {
$this->php->mkdir($path, 0775, true);
}
$htaccessFile = $path . '.htaccess';
if (file_exists($htaccessFile) === false) {
file_put_contents($htaccessFile, 'Deny from all');
}
}
/**
* Returns the cache config.
* @return Config
* @throws Exception
*/
public function getConfig(): Config
{
if ($this->config === null) {
$this->config = $this->configFactory->createConfig(self::CONFIG_KEY);
$selections = [
self::METHOD_SERIALIZE,
self::METHOD_JSON,
self::METHOD_VAR_EXPORT
];
if ($this->php->functionExists('igbinary_serialize') === true) {
$selections[] = self::METHOD_IGBINARY;
}
$configParameters = [
self::CONFIG_PATH => $this->configParameterFactory->createStringConfigParameter(
self::CONFIG_PATH,
$this->wordpress->getHomePath() . 'cache/uam'
),
self::CONFIG_METHOD => $this->configParameterFactory->createSelectionConfigParameter(
self::CONFIG_METHOD,
self::METHOD_VAR_EXPORT,
$selections
)
];
$this->config->setDefaultConfigParameters($configParameters);
}
return $this->config;
}
/**
* Returns the caching method.
* @return string|null
* @throws Exception
*/
private function getCacheMethod(): ?string
{
$method = (string) $this->getConfig()->getParameterValue(self::CONFIG_METHOD);
if ($method === self::METHOD_IGBINARY
&& ($this->php->functionExists('igbinary_serialize') === false
|| $this->php->functionExists('igbinary_unserialize') === false)
) {
$method = null;
}
return $method;
}
/**
* Returns the cache file name with path.
* @param string|null $method
* @param string $key
* @return string
* @throws Exception
*/
private function getCacheFile(?string $method, string $key): string
{
$cacheFile = $this->getPath() . $key;
$cacheFile .= ($method === self::METHOD_VAR_EXPORT) ? '.php' : '.cache';
return $cacheFile;
}
/**
* Adds a value to the cache.
* @param string $key
* @param mixed $value
* @throws Exception
*/
public function add(string $key, $value)
{
$method = $this->getCacheMethod();
$cacheFile = $this->getCacheFile($method, $key);
if ($method === self::METHOD_SERIALIZE) {
$this->php->filePutContents($cacheFile, base64_encode(serialize($value)), LOCK_EX);
} elseif ($method === self::METHOD_IGBINARY) {
$this->php->filePutContents($cacheFile, $this->php->igbinarySerialize($value), LOCK_EX);
} elseif ($method === self::METHOD_JSON) {
$this->php->filePutContents($cacheFile, json_encode($value), LOCK_EX);
} elseif ($method === self::METHOD_VAR_EXPORT) {
$this->php->filePutContents(
$cacheFile,
"<?php\n\$cachedValue = " . var_export($value, true) . ';',
LOCK_EX
);
}
}
/**
* Returns a value from the cache.
* @param string $key
* @return mixed
* @throws Exception
*/
public function get(string $key)
{
$method = $this->getCacheMethod();
$cacheFile = $this->getCacheFile($method, $key);
if ((file_exists($cacheFile) === true)) {
if ($method === self::METHOD_SERIALIZE) {
return unserialize(base64_decode(file_get_contents($cacheFile)));
} elseif ($method === self::METHOD_IGBINARY) {
return $this->php->igbinaryUnserialize(file_get_contents($cacheFile));
} elseif ($method === self::METHOD_JSON) {
return json_decode(file_get_contents($cacheFile), true);
} elseif ($method === self::METHOD_VAR_EXPORT) {
$cachedValue = null;
/** @noinspection PhpIncludeInspection */
include($cacheFile);
return $cachedValue;
}
}
return null;
}
/**
* Invalidates the cache.
* @param string $key
* @throws Exception
*/
public function invalidate(string $key)
{
$method = $this->getCacheMethod();
$cacheFile = $this->getCacheFile($method, $key);
if ((file_exists($cacheFile) === true)) {
unlink($cacheFile);
}
}
}
<?php
/**
* GroupCommand.php
*
* The GroupCommand class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @author Nils Woetzel nils.woetzel@h-its.org
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Command;
use Exception;
use UserAccessManager\Object\ObjectHandler;
use UserAccessManager\UserGroup\UserGroup;
use UserAccessManager\UserGroup\UserGroupFactory;
use UserAccessManager\UserGroup\UserGroupHandler;
use UserAccessManager\UserGroup\UserGroupTypeException;
use UserAccessManager\Wrapper\WordpressCli;
use WP_CLI\ExitException;
use WP_CLI\Formatter;
use WP_CLI_Command;
/**
* Class GroupCommand
*
* @package UserAccessManager\Command
*/
class GroupCommand extends WP_CLI_Command
{
const FORMATTER_PREFIX = 'uam_user_groups';
/**
* @var array
*/
private static $allowedAccessValues = ['group', 'all'];
/**
* @var WordpressCli
*/
private $wordpressCli;
/**
* @var UserGroupHandler
*/
private $userGroupHandler;
/**
* @var UserGroupFactory
*/
private $userGroupFactory;
/**
* ObjectCommand constructor.
* @param WordpressCli $wordpressCli
* @param UserGroupHandler $userGroupHandler
* @param UserGroupFactory $userGroupFactory
*/
public function __construct(
WordpressCli $wordpressCli,
UserGroupHandler $userGroupHandler,
UserGroupFactory $userGroupFactory
) {
$this->wordpressCli = $wordpressCli;
$this->userGroupHandler = $userGroupHandler;
$this->userGroupFactory = $userGroupFactory;
parent::__construct();
}
/**
* Returns the formatter
* @param $assocArguments
* @return Formatter
*/
private function getFormatter(&$assocArguments): Formatter
{
return $this->wordpressCli->createFormatter(
$assocArguments,
[
'ID',
'group_name',
'group_desc',
'read_access',
'write_access',
'roles',
'ip_range',
],
self::FORMATTER_PREFIX
);
}
/**
* list groups
* ## OPTIONS
* [--format=<format>]
* : Accepted values: table, csv, json, count, ids. Default: table
* ## EXAMPLES
* wp uam groups list
* @subcommand ls
* @param array $arguments
* @param array $assocArguments
* @throws ExitException
* @throws UserGroupTypeException
* @throws Exception
*/
public function ls(array $arguments, array $assocArguments)
{
if (count($arguments) > 0) {
$this->wordpressCli->error('No arguments excepted. Please use the format option.');
return;
}
$userGroups = $this->userGroupHandler->getUserGroups();
if (count($userGroups) <= 0) {
$this->wordpressCli->error('No groups defined yet!');
return;
}
$groups = [];
foreach ($userGroups as $userGroup) {
$groups[$userGroup->getId()] = [
'ID' => $userGroup->getId(),
'group_name' => $userGroup->getName(),
'group_desc' => $userGroup->getDescription(),
'read_access' => $userGroup->getReadAccess(),
'write_access' => $userGroup->getWriteAccess(),
'roles' => implode(
',',
array_keys($userGroup->getAssignedObjectsByType(ObjectHandler::GENERAL_ROLE_OBJECT_TYPE))
),
'ip_range' => $userGroup->getIpRange() !== null ? $userGroup->getIpRange() : ''
];
}
$formatter = $this->getFormatter($assocArguments);
$formatter->display_items($groups);
}
/**
* delete groups
* ## OPTIONS
* <group_id>
* : id of the group(s) to delete; accepts unlimited ids
* ## EXAMPLES
* wp uam groups del 3 5
* @subcommand del
* @param array $arguments
* @throws ExitException
* @throws UserGroupTypeException
*/
public function del(array $arguments)
{
if (count($arguments) < 1) {
$this->wordpressCli->error('Expected: wp uam groups del \<id\> ...');
return;
}
foreach ($arguments as $userGroupId) {
if ($this->userGroupHandler->deleteUserGroup($userGroupId) === true) {
$this->wordpressCli->success("Successfully deleted group with id '{$userGroupId}'.");
} else {
$this->wordpressCli->error("Group id '{$userGroupId}' doesn't exists.");
}
}
}
/**
* Checks if the user group already exists.
* @param $userGroupName
* @return bool
* @throws ExitException
* @throws UserGroupTypeException
*/
private function doesUserGroupExists($userGroupName): bool
{
$userGroups = $this->userGroupHandler->getUserGroups();
foreach ($userGroups as $userGroup) {
if ($userGroup->getName() === $userGroupName) {
$this->wordpressCli->error(
"Group with the same name '{$userGroupName}' already exists: {$userGroup->getId()}"
);
return false;
}
}
return true;
}
/**
* Returns the argument value.
* @param array $arguments
* @param string $value
* @return string
*/
private function getArgumentValue(array $arguments, string $value): string
{
return (isset($arguments[$value]) === true) ? (string) $arguments[$value] : '';
}
/**
* Processes the access value.
* @param array $arguments
* @param string $value
* @param bool $porcelain
* @return string
*/
private function getAccessValue(array $arguments, string $value, bool $porcelain): string
{
$accessValue = $this->getArgumentValue($arguments, $value);
if (in_array($accessValue, self::$allowedAccessValues) === false) {
if ($porcelain === true) {
$this->wordpressCli->line("setting {$value} to " . self::$allowedAccessValues[0]);
}
$accessValue = self::$allowedAccessValues[0];
}
return $accessValue;
}
/**
* Creates the user group.
* @param string $userGroupName
* @param array $assocArguments
* @return UserGroup
* @throws UserGroupTypeException
* @throws Exception
*/
private function createUserGroup(string $userGroupName, array $assocArguments): UserGroup
{
$groupDescription = $this->getArgumentValue($assocArguments, 'desc');
$ipRange = $this->getArgumentValue($assocArguments, 'ip_range');
$porcelain = isset($assocArguments['porcelain']);
$readAccess = $this->getAccessValue($assocArguments, 'read_access', $porcelain);
$writeAccess = $this->getAccessValue($assocArguments, 'write_access', $porcelain);
$userGroup = $this->userGroupFactory->createUserGroup();
$userGroup->setName($userGroupName);
$userGroup->setDescription($groupDescription);
$userGroup->setIpRange($ipRange);
$userGroup->setReadAccess($readAccess);
$userGroup->setWriteAccess($writeAccess);
// add roles
if (isset($assocArguments['roles']) === true) {
$roles = explode(',', $assocArguments['roles']);
$userGroup->removeObject(ObjectHandler::GENERAL_ROLE_OBJECT_TYPE);
foreach ($roles as $role) {
$userGroup->addObject(ObjectHandler::GENERAL_ROLE_OBJECT_TYPE, trim($role));
}
}
$userGroup->save();
return $userGroup;
}
/**
* add group
* ## OPTIONS
* <group_name>
* : the name of the new group
* [--porcelain]
* : Output just the new post id.
* [--roles=<list>]
* : comma separated list of group associated roles
* [--<field>=<value>]
* : Associative args for new UamUserGroup object
* allowed fields and values are:
* desc="",
* read_access={group,all*},
* write_access={group,all*},
* ip_range="192.168.0.1-192.168.0.10;192.168.0.20-192.168.0.30"
* *=default
* ## EXAMPLES
* wp uam groups add fighters --read_access=all
* @param array $arguments
* @param array $assocArguments
* @throws ExitException
* @throws UserGroupTypeException
*/
public function add(array $arguments, array $assocArguments)
{
if (isset($arguments[0]) === false) {
$this->wordpressCli->error("Please provide a group name.");
return;
}
$userGroupName = $arguments[0];
if ($this->doesUserGroupExists($userGroupName) === false) {
return;
}
$userGroup = $this->createUserGroup($userGroupName, $assocArguments);
$this->userGroupHandler->addUserGroup($userGroup);
if (isset($assocArguments['porcelain']) === true) {
$this->wordpressCli->line($userGroup->getId());
} else {
$this->wordpressCli->success("Added new group '{$userGroupName}' with id {$userGroup->getId()}.");
}
}
}
<?php
/**
* ObjectsCommand.php
*
* The ObjectCommand class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @author Nils Woetzel nils.woetzel@h-its.org
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Command;
use Exception;
use UserAccessManager\UserGroup\AbstractUserGroup;
use UserAccessManager\UserGroup\UserGroup;
use UserAccessManager\UserGroup\UserGroupHandler;
use UserAccessManager\UserGroup\UserGroupTypeException;
use UserAccessManager\Wrapper\WordpressCli;
use WP_CLI\ExitException;
use WP_CLI_Command;
/**
* Class ObjectCommand
*
* @package UserAccessManager\Command
*/
class ObjectCommand extends WP_CLI_Command
{
const ACTION_ADD = 'add';
const ACTION_UPDATE = 'update';
const ACTION_REMOVE = 'remove';
/**
* @var WordpressCli
*/
private $wordpressCli;
/**
* @var UserGroupHandler
*/
private $userGroupHandler;
/**
* ObjectCommand constructor.
* @param WordpressCli $wordpressCli
* @param UserGroupHandler $userGroupHandler
*/
public function __construct(WordpressCli $wordpressCli, UserGroupHandler $userGroupHandler)
{
$this->wordpressCli = $wordpressCli;
$this->userGroupHandler = $userGroupHandler;
parent::__construct();
}
/**
* Converts the string to and associative array of index and group
* @param AbstractUserGroup[] $userGroups
* @return array
*/
private function getUserGroupNameMap(array $userGroups): array
{
$userGroupNames = array_map(
function (UserGroup $userGroup) {
return $userGroup->getName();
},
$userGroups
);
$userGroupNames = array_flip($userGroupNames);
return (is_array($userGroupNames) === true) ? $userGroupNames : [];
}
/**
* Returns the user group id and the type of the id.
* @param array $namesMap
* @param string $identifier
* @param string|null $type
* @return int|string
*/
private function getUserGroupIdAndType(array $namesMap, string $identifier, ?string &$type = '')
{
$type = (is_numeric($identifier) === true) ? 'id' : 'name';
return $namesMap[$identifier] ?? $identifier;
}
/**
* Returns the add and remove user groups by reference.
* @param string $operation
* @param string $objectType
* @param int|string $objectId
* @param array $userGroupIds
* @param AbstractUserGroup[] $userGroups
* @param array|null $addUserGroups
* @param array|null $removeUserGroups
* @return bool
* @throws ExitException
* @throws UserGroupTypeException
*/
private function getAddRemoveUserGroups(
string $operation,
string $objectType,
$objectId,
array $userGroupIds,
array $userGroups,
?array &$addUserGroups = [],
?array &$removeUserGroups = []
): bool {
$addUserGroups = [];
$namesMap = $this->getUserGroupNameMap($userGroups);
// find the UserGroup object for the ids or strings given on the commandline
foreach ($userGroupIds as $identifier) {
$userGroupId = $this->getUserGroupIdAndType($namesMap, $identifier, $type);
if (isset($userGroups[$userGroupId]) !== true) {
$this->wordpressCli->error("There is no group with the {$type}: {$identifier}");
return false;
}
$addUserGroups[$userGroupId] = $userGroups[$userGroupId];
}
$removeUserGroups = ($operation === self::ACTION_UPDATE) ?
$this->userGroupHandler->getUserGroupsForObject($objectType, $objectId) : [];
if ($operation === self::ACTION_REMOVE) {
$removeUserGroups = $addUserGroups;
$addUserGroups = [];
}
return true;
}
/**
* update groups for an object
* ## OPTIONS
* <operation>
* : 'add', 'remove' or 'update'
* <object_type>
* : 'page', 'post', 'user', 'role', 'category' or any other term type
* <object_id>
* : the id of the object (string for role)
* <user_groups>
* : comma separated list of group names or ids to add, remove of update to for the object
* ## EXAMPLES
* wp uam object add user 1 fighters,losers
* wp uam object remove role author fighters
* wp uam object update category 5 controller
* @param array $arguments
* @param array $assocArguments
* @throws ExitException
* @throws UserGroupTypeException
* @throws Exception
*/
public function __invoke(array $arguments, array $assocArguments)
{
if (count($arguments) < 4) {
$this->wordpressCli->error('<operation>, <object_type>, <object_id> and <user_groups> are required');
return;
}
$operation = $arguments[0];
$messages = [
self::ACTION_ADD => 'Groups %1$s successfully added to %2$s %3$s',
self::ACTION_UPDATE => 'Successfully updated %2$s %3$s with groups %1$s',
self::ACTION_REMOVE => 'Successfully removed groups: %1$s from %2$s %3$s'
];
// check that operation is valid
if (isset($messages[$operation]) === false) {
$this->wordpressCli->error("Operation is not valid: {$operation}");
return;
}
$objectType = $arguments[1];
$objectId = $arguments[2];
$userGroupIds = array_unique(explode(',', $arguments[3]));
$userGroups = $this->userGroupHandler->getUserGroups();
$success = $this->getAddRemoveUserGroups(
$operation,
$objectType,
$objectId,
$userGroupIds,
$userGroups,
$addUserGroups,
$removeUserGroups
);
if ($success === false) {
return;
}
foreach ($userGroups as $groupId => $userGroup) {
if (isset($removeUserGroups[$groupId]) === true) {
$userGroup->removeObject($objectType, $objectId);
}
if (isset($addUserGroups[$groupId]) === true) {
$userGroup->addObject($objectType, $objectId);
}
$userGroup->save();
}
$this->wordpressCli->success(
sprintf($messages[$operation], implode(', ', $userGroupIds), $objectType, $objectId)
);
}
}
<?php
/**
* BooleanParameter.php
*
* The BooleanParameter class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Config;
use Exception;
/**
* Class BooleanConfigParameter
* @package UserAccessManager\Config
*/
class BooleanConfigParameter extends ConfigParameter
{
/**
* BooleanConfigParameter constructor.
* @param string $id
* @param bool $defaultValue
* @throws Exception
*/
public function __construct(string $id, $defaultValue = false)
{
parent::__construct($id, $defaultValue);
}
/**
* Legacy converter for legacy values.
* @param mixed $value
* @return bool|string
*/
private function stringToBoolConverter($value)
{
if ($value === 'true') {
$value = true;
} elseif ($value === 'false') {
$value = false;
}
return $value;
}
/**
* Legacy wrapper for old config values.
* @param mixed $value
*/
public function setValue($value)
{
$value = (bool) $this->stringToBoolConverter($value);
parent::setValue($value);
}
/**
* Checks if the given value is bool.
* @param mixed $value
* @return bool
*/
public function isValidValue($value): bool
{
return is_bool($value) === true;
}
}
<?php
/**
* Config.php
*
* The Config class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Config;
use Exception;
use UserAccessManager\Wrapper\Wordpress;
/**
* Class Config
*
* @package UserAccessManager\Config
*/
class Config
{
/**
* @var Wordpress
*/
protected $wordpress;
/**
* @var string
*/
protected $key;
/**
* @var array
*/
protected $wpOptions = [];
/**
* @var ConfigParameter[]
*/
protected $defaultConfigParameters = [];
/**
* @var null|ConfigParameter[]
*/
protected $configParameters = null;
/**
* Config constructor.
* @param Wordpress $wordpress
* @param string $key
*/
public function __construct(
Wordpress $wordpress,
string $key
) {
$this->wordpress = $wordpress;
$this->key = $key;
}
/**
* Returns the WordPress options.
* @param string $option
* @return mixed
*/
public function getWpOption(string $option)
{
if (!isset($this->wpOptions[$option]) === true) {
$this->wpOptions[$option] = $this->wordpress->getOption($option);
}
return $this->wpOptions[$option];
}
/**
* Returns the default parameters for the current config.
* @return ConfigParameter[]
*/
protected function getDefaultConfigParameters(): array
{
return $this->defaultConfigParameters;
}
/**
* Sets the default config parameters
* @param ConfigParameter[] $defaultConfigParameters
*/
public function setDefaultConfigParameters(array $defaultConfigParameters)
{
$this->defaultConfigParameters = $defaultConfigParameters;
}
/**
* Returns the current settings
* @return ConfigParameter[]
*/
public function getConfigParameters(): array
{
if ($this->configParameters === null) {
$configParameters = $this->getDefaultConfigParameters();
$currentOptions = (array) $this->getWpOption($this->key);
foreach ($currentOptions as $key => $option) {
if (isset($configParameters[$key])) {
$configParameters[$key]->setValue($option);
}
}
$this->configParameters = $configParameters;
}
return $this->configParameters;
}
/**
* Sets the new config parameters and saves them to the database.
* @param array $rawParameters
*/
public function setConfigParameters(array $rawParameters)
{
$configParameters = $this->getConfigParameters();
foreach ($rawParameters as $key => $value) {
if (isset($configParameters[$key]) === true) {
$configParameters[$key]->setValue($value);
}
}
$this->configParameters = $configParameters;
$simpleConfigParameters = [];
foreach ($configParameters as $parameter) {
$simpleConfigParameters[$parameter->getId()] = $parameter->getValue();
}
$this->wordpress->updateOption($this->key, $simpleConfigParameters);
}
/**
* Flushes the config parameters.
*/
public function flushConfigParameters()
{
$this->defaultConfigParameters = [];
$this->configParameters = null;
}
/**
* Returns the requested parameter value
* @param string $parameterName
* @return mixed
* @throws Exception
*/
public function getParameterValueRaw(string $parameterName)
{
$options = $this->getConfigParameters();
if (isset($options[$parameterName]) === false) {
throw new Exception("Unknown config parameter '{$parameterName}'.");
}
return $options[$parameterName]->getValue();
}
/**
* Returns the requested parameter value but suppresses exceptions.
* @param string $parameterName
* @return mixed
*/
public function getParameterValue(string $parameterName)
{
try {
return $this->getParameterValueRaw($parameterName);
} catch (Exception $exception) {
return null;
}
}
}
<?php
/**
* Config.php
*
* The ConfigFactory class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Config;
use UserAccessManager\Wrapper\Wordpress;
/**
* Class ConfigFactory
*
* @package UserAccessManager\Config
*/
class ConfigFactory
{
private $wordpress;
/**
* ConfigFactory constructor.
* @param Wordpress $wordpress
*/
public function __construct(Wordpress $wordpress)
{
$this->wordpress = $wordpress;
}
/**
* Returns a new configuration.
* @param string $key
* @return Config
*/
public function createConfig(string $key): Config
{
return new Config($this->wordpress, $key);
}
}
<?php
/**
* ConfigParameter.php
*
* The ConfigParameter class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Config;
use Exception;
/**
* Class ConfigParameter
*
* @package UserAccessManager\Config
*/
abstract class ConfigParameter implements ConfigParameterInterface
{
/**
* @var string
*/
protected $id;
/**
* @var mixed
*/
protected $defaultValue = null;
/**
* @var mixed
*/
protected $value = null;
/**
* ConfigParameter constructor.
* @param string $id
* @param mixed $defaultValue
* @throws Exception
*/
public function __construct(string $id, $defaultValue = null)
{
$this->id = $id;
$this->validateValue($defaultValue);
$this->defaultValue = $defaultValue;
}
/**
* Returns the id.
* @return string
*/
public function getId(): string
{
return $this->id;
}
/**
* Checks the value type and throws an exception if the value isn't the required type.
* @param mixed $value
* @throws Exception
*/
protected function validateValue($value)
{
if ($this->isValidValue($value) === false) {
throw new Exception("Wrong value '{$value}' type given for '{$this->id}'.'");
}
}
/**
* Sets the current value.
* @param mixed $value
*/
public function setValue($value)
{
$this->isValidValue($value);
$this->value = $value;
}
/**
* Returns the current parameter value.
* @return mixed
*/
public function getValue()
{
return ($this->value === null) ? $this->defaultValue : $this->value;
}
}
<?php
/**
* ConfigParameterFactory.php
*
* The ConfigParameterFactory class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Config;
use Exception;
/**
* Class ConfigParameterFactory
*
* @package UserAccessManager\Config
*/
class ConfigParameterFactory
{
/**
* Creates a boolean config parameter object.
* @param string $id
* @param mixed $defaultValue
* @return BooleanConfigParameter
* @throws Exception
*/
public function createBooleanConfigParameter(string $id, $defaultValue = false): BooleanConfigParameter
{
return new BooleanConfigParameter($id, $defaultValue);
}
/**
* Creates a selection config parameter object.
* @param string $id
* @param mixed $defaultValue
* @param array $selection
* @return SelectionConfigParameter
* @throws Exception
*/
public function createSelectionConfigParameter(
string $id,
$defaultValue,
array $selection
): SelectionConfigParameter {
return new SelectionConfigParameter($id, $defaultValue, $selection);
}
/**
* Creates a string config parameter object.
* @param string $id
* @param mixed $defaultValue
* @return StringConfigParameter
* @throws Exception
*/
public function createStringConfigParameter(string $id, $defaultValue = ''): StringConfigParameter
{
return new StringConfigParameter($id, $defaultValue);
}
}
<?php
/**
* ConfigParameterInterface.php
*
* The ConfigParameterInterface interface file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Config;
/**
* Interface ConfigParameterInterface
*
* @package UserAccessManager\Config
*/
interface ConfigParameterInterface
{
/**
* Validates the value.
* @param mixed $value
* @return bool
*/
public function isValidValue($value): bool;
/**
* Sets the current value.
* @param mixed $value
*/
public function setValue($value);
/**
* Returns the current parameter value.
* @return mixed
*/
public function getValue();
}
<?php
/**
* SelectionConfigParameter.php
*
* The SelectionConfigParameter class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Config;
use Exception;
/**
* Class SelectionConfigParameter
*
* @package UserAccessManager\Config
*/
class SelectionConfigParameter extends ConfigParameter
{
/**
* @var array
*/
private $selections;
/**
* SelectionConfigParameter constructor.
* @param string $id
* @param mixed $defaultValue
* @param array $selections
* @throws Exception
*/
public function __construct(string $id, $defaultValue, array $selections)
{
$this->selections = $selections;
parent::__construct($id, $defaultValue);
}
/**
* Checks if the value is part of the selection.
* @param mixed $value
* @return bool
*/
public function isValidValue($value): bool
{
$map = array_flip($this->selections);
return (isset($map[$value]) === true);
}
/**
* Returns the available selections.
* @return array
*/
public function getSelections(): array
{
return $this->selections;
}
}
<?php
/**
* StringConfigParameter.php
*
* The StringConfigParameter class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Config;
use Exception;
class StringConfigParameter extends ConfigParameter
{
/**
* StringConfigParameter constructor.
* @param string $id
* @param string $defaultValue
* @throws Exception
*/
public function __construct(string $id, $defaultValue = '')
{
parent::__construct($id, $defaultValue);
}
/**
* Checks if the given value is a string.
* @param mixed $value
* @return bool
*/
public function isValidValue($value): bool
{
return is_string($value) === true;
}
}
<?php
/**
* WordpressConfig.php
*
* The WordpressConfig class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Config;
use UserAccessManager\Wrapper\Wordpress;
/**
* Class WordpressConfig
*
* @package UserAccessManager\Config
*/
class WordpressConfig
{
/**
* @var Wordpress
*/
private $wordpress;
/**
* @var string
*/
private $baseFile;
/**
* @var null|bool
*/
private $isPermalinksActive = null;
/**
* @var null|array
*/
private $mimeTypes = null;
/**
* WordpressClass constructor.
* @param Wordpress $wordpress
* @param string $baseFile
*/
public function __construct(Wordpress $wordpress, string $baseFile)
{
$this->wordpress = $wordpress;
$this->baseFile = $baseFile;
}
/**
* Returns true if a user is at the admin panel.
* @return bool
*/
public function atAdminPanel(): bool
{
return $this->wordpress->isAdmin();
}
/**
* Returns true if permalinks are active otherwise false.
* @return bool
*/
public function isPermalinksActive(): ?bool
{
if ($this->isPermalinksActive === null) {
$permalinkStructure = $this->wordpress->getOption('permalink_structure');
$this->isPermalinksActive = (empty($permalinkStructure) === false);
}
return $this->isPermalinksActive;
}
/**
* Returns the upload directory.
* @return null|string
*/
public function getUploadDirectory(): ?string
{
$wordpressUploadDir = $this->wordpress->getUploadDir();
if (empty($wordpressUploadDir['error'])) {
return $wordpressUploadDir['basedir'] . DIRECTORY_SEPARATOR;
}
return null;
}
/**
* Returns the full supported mine types.
* @return array
*/
public function getMimeTypes(): ?array
{
if ($this->mimeTypes === null) {
$mimeTypes = $this->wordpress->getAllowedMimeTypes();
$fullMimeTypes = [];
foreach ($mimeTypes as $extensions => $mineType) {
$extensions = explode('|', $extensions);
foreach ($extensions as $extension) {
$fullMimeTypes[$extension] = $mineType;
}
}
$this->mimeTypes = $fullMimeTypes;
}
return $this->mimeTypes;
}
/**
* Returns the module url path.
* @return string
*/
public function getUrlPath(): string
{
return $this->wordpress->pluginsUrl('', $this->baseFile) . '/';
}
/**
* Returns the module real path.
* @return string
*/
public function getRealPath(): string
{
$dirName = dirname($this->baseFile);
return $this->wordpress->getPluginDir() . DIRECTORY_SEPARATOR
. $this->wordpress->pluginBasename($dirName) . DIRECTORY_SEPARATOR;
}
}
<?php
/**
* AboutController.php
*
* The AboutController class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Controller\Backend;
use UserAccessManager\Controller\Controller;
/**
* Class AboutController
*
* @package UserAccessManager\Controller
*/
class AboutController extends Controller
{
const SUPPORTER_FILE = 'supporters.json';
const SUPPORTER_FILE_URL = 'https://gm-alex.github.io/user-access-manager/supporters.json';
/**
* @var string
*/
protected $template = 'AdminAbout.php';
/**
* @var null|array
*/
private $supporters = null;
/**
* Returns all the supporters.
* @return array
*/
private function getAllSupporters(): ?array
{
if ($this->supporters === null) {
$realPath = rtrim($this->wordpressConfig->getRealPath(), DIRECTORY_SEPARATOR);
$path = [$realPath, 'assets'];
$path = implode(DIRECTORY_SEPARATOR, $path) . DIRECTORY_SEPARATOR;
$fileWithPath = $path . self::SUPPORTER_FILE;
$needsUpdate = is_file($fileWithPath) === false
|| filemtime($fileWithPath) < $this->wordpress->currentTime('timestamp') - 24 * 60 * 60;
$fileContent = ($needsUpdate === true) ? @file_get_contents(self::SUPPORTER_FILE_URL) : false;
if ($fileContent !== false) {
file_put_contents($fileWithPath, $fileContent);
} elseif (is_file($fileWithPath) === true) {
$fileContent = file_get_contents($fileWithPath);
}
$this->supporters = (is_string($fileContent) === true) ? json_decode($fileContent, true) : [];
}
return $this->supporters;
}
/**
* Returns the people which earn a special thanks.
* @return array
*/
public function getSpecialThanks(): array
{
$supporters = $this->getAllSupporters();
return isset($supporters['special-thanks']) === true ? $supporters['special-thanks'] : [];
}
/**
* Returns the people which earn a special thanks.
* @return array
*/
public function getTopSupporters(): array
{
$supporters = $this->getAllSupporters();
return isset($supporters['top-supporters']) === true ? $supporters['top-supporters'] : [];
}
/**
* Returns the people which earn a special thanks.
* @return array
*/
public function getSupporters(): array
{
$supporters = $this->getAllSupporters();
return isset($supporters['supporters']) === true ? $supporters['supporters'] : [];
}
}
<?php
/**
* BackendController.php
*
* The BackendController class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Controller\Backend;
use UserAccessManager\Config\WordpressConfig;
use UserAccessManager\Controller\Controller;
use UserAccessManager\File\FileHandler;
use UserAccessManager\Setup\SetupHandler;
use UserAccessManager\User\UserHandler;
use UserAccessManager\UserAccessManager;
use UserAccessManager\Wrapper\Php;
use UserAccessManager\Wrapper\Wordpress;
/**
* Class BackendController
*
* @package UserAccessManager\Controller
*/
class BackendController extends Controller
{
public const HANDLE_STYLE_ADMIN = 'UserAccessManagerAdmin';
public const HANDLE_SCRIPT_GROUP_SUGGEST = 'UserAccessManagerGroupSuggest';
public const HANDLE_SCRIPT_TIME_INPUT = 'UserAccessManagerTimeInput';
public const HANDLE_SCRIPT_ADMIN = 'UserAccessManagerFunctions';
public const UAM_ERRORS = 'UAM_ERRORS';
/**
* @var UserHandler
*/
private $userHandler;
/**
* @var SetupHandler
*/
private $setupHandler;
/**
* @var string
*/
private $notice = '';
/**
* BackendController constructor.
* @param Php $php
* @param Wordpress $wordpress
* @param WordpressConfig $wordpressConfig
* @param UserHandler $userHandler
* @param SetupHandler $setupHandler
*/
public function __construct(
Php $php,
Wordpress $wordpress,
WordpressConfig $wordpressConfig,
UserHandler $userHandler,
SetupHandler $setupHandler
) {
parent::__construct($php, $wordpress, $wordpressConfig);
$this->userHandler = $userHandler;
$this->setupHandler = $setupHandler;
}
/**
* Shows the admin notices.
*/
public function showAdminNotice()
{
$messages = isset($_SESSION[self::UAM_ERRORS]) === true ? $_SESSION[self::UAM_ERRORS] : [];
$updateAction = $this->getRequestParameter('uam_update_db');
if ($this->setupHandler->getDatabaseHandler()->isDatabaseUpdateNecessary() === true
&& $updateAction !== SetupController::UPDATE_BLOG
&& $updateAction !== SetupController::UPDATE_NETWORK
) {
$messages[] = sprintf(TXT_UAM_NEED_DATABASE_UPDATE, 'admin.php?page=uam_setup');
}
if ($messages !== []) {
$this->notice = implode('<br>', $messages);
echo $this->getIncludeContents('AdminNotice.php');
}
}
/**
* Returns the set notice.
* @return string
*/
public function getNotice(): string
{
return $this->notice;
}
/**
* Register styles and scripts with handle for admin panel.
*/
private function registerStylesAndScripts()
{
$urlPath = $this->wordpressConfig->getUrlPath();
$this->wordpress->registerStyle(
self::HANDLE_STYLE_ADMIN,
$urlPath . 'assets/css/uamAdmin.css',
[],
UserAccessManager::VERSION,
'screen'
);
$this->wordpress->registerScript(
self::HANDLE_SCRIPT_GROUP_SUGGEST,
$urlPath . 'assets/js/jquery.uam-group-suggest.js',
['jquery'],
UserAccessManager::VERSION
);
$this->wordpress->registerScript(
self::HANDLE_SCRIPT_TIME_INPUT,
$urlPath . 'assets/js/jquery.uam-time-input.js',
['jquery'],
UserAccessManager::VERSION
);
$this->wordpress->registerScript(
self::HANDLE_SCRIPT_ADMIN,
$urlPath . 'assets/js/functions.js',
['jquery'],
UserAccessManager::VERSION
);
}
/**
* The function for the admin_enqueue_scripts action for styles and scripts.
*/
public function enqueueStylesAndScripts()
{
$this->registerStylesAndScripts();
$this->wordpress->enqueueStyle(self::HANDLE_STYLE_ADMIN);
$this->wordpress->enqueueScript(self::HANDLE_SCRIPT_GROUP_SUGGEST);
$this->wordpress->enqueueScript(self::HANDLE_SCRIPT_TIME_INPUT);
$this->wordpress->enqueueScript(self::HANDLE_SCRIPT_ADMIN);
}
/**
* The function for the wp_dashboard_setup action.
* Removes widgets to which a user should not have access.
*/
public function setupAdminDashboard()
{
if ($this->userHandler->checkUserAccess(UserHandler::MANAGE_USER_GROUPS_CAPABILITY) === false) {
$metaBoxes = $this->wordpress->getMetaBoxes();
unset($metaBoxes['dashboard']['normal']['core']['dashboard_recent_comments']);
$this->wordpress->setMetaBoxes($metaBoxes);
}
}
}
<?php
/**
* CacheController.php
*
* The ObjectController class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Controller\Backend;
use UserAccessManager\Cache\Cache;
use UserAccessManager\Object\ObjectMapHandler;
/**
* Class CacheController
*
* @package UserAccessManager\Controller\Backend
*/
class CacheController
{
/**
* @var Cache
*/
private $cache;
/**
* CacheController constructor.
* @param Cache $cache
*/
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
/**
* Invalidates the term related cache objects.
*/
public function invalidateTermCache()
{
$this->cache->invalidate(ObjectMapHandler::POST_TERM_MAP_CACHE_KEY);
$this->cache->invalidate(ObjectMapHandler::TERM_POST_MAP_CACHE_KEY);
$this->cache->invalidate(ObjectMapHandler::TERM_TREE_MAP_CACHE_KEY);
}
/**
* Invalidates the post related cache objects.
*/
public function invalidatePostCache()
{
$this->cache->invalidate(ObjectMapHandler::TERM_POST_MAP_CACHE_KEY);
$this->cache->invalidate(ObjectMapHandler::POST_TERM_MAP_CACHE_KEY);
$this->cache->invalidate(ObjectMapHandler::POST_TREE_MAP_CACHE_KEY);
}
}
<?php
/**
* ControllerTabNavigationTrait.php
*
* The ControllerTabNavigationTrait class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Controller\Backend;
/**
* Trait ControllerTabNavigationTrait
*
* @package UserAccessManager\Controller
*/
trait ControllerTabNavigationTrait
{
/**
* Returns the current request url.
* @return string
*/
abstract public function getRequestUrl(): string;
/**
* Returns the request parameter.
* @param string $name
* @param mixed $default
* @return mixed
*/
abstract public function getRequestParameter(string $name, $default = null);
/**
* Translates the given group by the group key.
* @param string $key
* @return string
*/
abstract public function getGroupText(string $key): string;
/**
* Translates the given group section by the group key.
* @param string $key
* @return string
*/
abstract public function getGroupSectionText(string $key): string;
/**
* Returns the tab groups.
* @return array
*/
abstract public function getTabGroups(): array;
/**
* Returns the current tab group.
* @return string
*/
public function getCurrentTabGroup(): string
{
$groups = $this->getTabGroups();
$keys = array_keys($groups);
return (string) $this->getRequestParameter('tab_group', reset($keys));
}
/**
* Returns the tab group sections.
* @return array
*/
public function getSections(): array
{
$groups = $this->getTabGroups();
$group = $this->getCurrentTabGroup();
return isset($groups[$group]) === true ? $groups[$group] : [];
}
/**
* Returns the current tab group section.
* @return string
*/
public function getCurrentTabGroupSection(): string
{
$groups = $this->getTabGroups();
$group = $this->getCurrentTabGroup();
if (isset($groups[$group]) === true) {
$default = reset($groups[$group]);
} else {
$firstGroup = reset($groups);
$default = reset($firstGroup);
}
return (string) $this->getRequestParameter('tab_group_section', $default);
}
/**
* Returns the settings group link by the given group key.
* @param string $groupKey
* @return string
*/
public function getTabGroupLink(string $groupKey): string
{
$rawUrl = $this->getRequestUrl();
$url = preg_replace('/&amp;tab_group[^&]*/i', '', $rawUrl);
return $url . '&tab_group=' . $groupKey;
}
/**
* Returns the settings section link by the given group and section key.
* @param string $groupKey
* @param string $sectionKey
* @return string
*/
public function getTabGroupSectionLink(string $groupKey, string $sectionKey): string
{
$rawUrl = $this->getTabGroupLink($groupKey);
$url = preg_replace('/&amp;tab_group_section[^&]*/i', '', $rawUrl);
return $url . '&tab_group_section=' . $sectionKey;
}
}
<?php
/**
* DynamicGroupsController.php
*
* The DynamicGroupsController class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Controller\Backend;
use UserAccessManager\UserGroup\DynamicUserGroup;
use WP_Role;
/**
* Class DynamicGroupsController
*
* @package UserAccessManager\Controller\Backend
*/
class DynamicGroupsController extends ObjectController
{
/**
* Returns the dynamic user groups for the ajax request.
*/
public function getDynamicGroupsForAjax()
{
if ($this->checkUserAccess() === false) {
echo json_encode([]);
$this->php->callExit();
return;
}
$search = $this->getRequestParameter('q');
$searches = explode(',', $search);
$search = trim(end($searches));
$users = $this->wordpress->getUsers([
'search' => '*' . $search . '*',
'fields' => ['ID', 'display_name', 'user_login', 'user_email']
]);
$matches = array_map(
function ($element) {
return [
'id' => $element->ID,
'name' => TXT_UAM_USER . ": {$element->display_name} ($element->user_login)",
'type' => DynamicUserGroup::USER_TYPE
];
},
$users
);
/**
* @var WP_Role[] $roles
*/
$roles = $this->wordpress->getRoles()->roles;
foreach ($roles as $key => $role) {
if (strpos(strtolower($role['name']), strtolower($search)) !== false) {
$matches[] = [
'id' => $key,
'name' => TXT_UAM_ROLE . ': ' . $role['name'],
'type' => DynamicUserGroup::ROLE_TYPE
];
}
}
echo json_encode($matches);
$this->php->callExit();
}
}
<?php
/**
* ObjectInformation.php
*
* The ObjectInformation class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Controller\Backend;
use UserAccessManager\UserGroup\AbstractUserGroup;
/**
* Class ObjectInformation
*
* @package UserAccessManager\Controller\Backend
*/
class ObjectInformation
{
/**
* @var null|string
*/
protected $objectType = null;
/**
* @var null|string
*/
protected $objectId = null;
/**
* @var int
*/
protected $userGroupDiff = 0;
/**
* @var AbstractUserGroup[]
*/
protected $objectUserGroups = [];
/**
* Sets the object type.
* @param string $objectType
* @return $this
*/
public function setObjectType(string $objectType): ObjectInformation
{
$this->objectType = $objectType;
return $this;
}
/**
* Returns the current object type.
* @return null|string
*/
public function getObjectType(): ?string
{
return $this->objectType;
}
/**
* Sets the object id.
* @param $objectId
* @return $this
*/
public function setObjectId($objectId): ObjectInformation
{
$this->objectId = $objectId;
return $this;
}
/**
* Returns the current object id.
* @return int|string|null
*/
public function getObjectId()
{
return $this->objectId;
}
/**
* Sets the user group diff count.
* @param int $userGroupDiff
* @return $this
*/
public function setUserGroupDiff(int $userGroupDiff): ObjectInformation
{
$this->userGroupDiff = $userGroupDiff;
return $this;
}
/**
* Returns the user group count diff.
* @return int
*/
public function getUserGroupDiff(): int
{
return $this->userGroupDiff;
}
/**
* Sets the user group diff count.
* @param $objectUserGroups
* @return $this
*/
public function setObjectUserGroups($objectUserGroups): ObjectInformation
{
$this->objectUserGroups = $objectUserGroups;
return $this;
}
/**
* Returns the current object user groups.
* @return AbstractUserGroup[]
*/
public function getObjectUserGroups(): array
{
return $this->objectUserGroups;
}
}
<?php
/**
* ObjectInformationFactory.php
*
* The ObjectInformationFactory class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Controller\Backend;
/**
* Class ObjectInformationFactory
*
* @package UserAccessManager\Controller\Backend
*/
class ObjectInformationFactory
{
/**
* Creates and returns a new object information object.
* @return ObjectInformation
*/
public function createObjectInformation(): ObjectInformation
{
return new ObjectInformation();
}
}
<?php
/**
* PostObjectController.php
*
* The PostObjectController class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Controller\Backend;
use UserAccessManager\Object\ObjectHandler;
use UserAccessManager\UserGroup\UserGroupTypeException;
use WP_Post;
/**
* Class PostObjectController
*
* @package UserAccessManager\Controller\Backend
*/
class PostObjectController extends ObjectController
{
/**
* The function for the manage_posts_columns and
* the manage_pages_columns filter.
* @param array $defaults The table headers.
* @return array
*/
public function addPostColumnsHeader(array $defaults): array
{
$defaults[self::COLUMN_NAME] = TXT_UAM_COLUMN_ACCESS;
return $defaults;
}
/**
* The function for the manage_users_custom_column action.
* @param string $columnName The column name.
* @param int|string $id The id.
* @throws UserGroupTypeException
*/
public function addPostColumn(string $columnName, $id)
{
if ($columnName === self::COLUMN_NAME) {
$post = $this->objectHandler->getPost($id);
echo $this->getGroupColumn($post->post_type, $post->ID);
}
}
/**
* The function for the uam_post_access meta box.
* @param mixed $post The post.
* @throws UserGroupTypeException
*/
public function editPostContent($post)
{
if ($post instanceof WP_Post) {
$this->setObjectInformation($post->post_type, $post->ID);
}
echo $this->getIncludeContents('PostEditForm.php');
}
/**
* Adds the bulk edit form.
* @param $columnName
*/
public function addBulkAction($columnName)
{
if ($columnName === self::COLUMN_NAME) {
$this->getObjectInformation()->setObjectId(null);
echo $this->getIncludeContents('BulkEditForm.php');
}
}
/**
* The function for the save_post action.
* @param mixed $postParam The post id or a array of a post.
* @throws UserGroupTypeException
*/
public function savePostData($postParam)
{
$postId = (is_array($postParam) === true) ? $postParam['ID'] : $postParam;
$post = $this->objectHandler->getPost($postId);
$postType = $post->post_type;
$postId = $post->ID;
if ($postType === 'revision') {
$postId = $post->post_parent;
$parentPost = $this->objectHandler->getPost($postId);
$postType = $parentPost->post_type;
}
$this->saveObjectData($postType, $postId);
}
/**
* The function for the add_attachment action.
* @param int $postId
* @throws UserGroupTypeException
*/
public function addAttachment(int $postId)
{
$post = $this->objectHandler->getPost($postId);
$postType = $post->post_type;
$postId = $post->ID;
$defaultGroups = [];
foreach ($this->userGroupHandler->getFullUserGroups() as $userGroup) {
if ($userGroup->isDefaultGroupForObjectType($postType) === true) {
$defaultGroups[$userGroup->getId()] = ['id' => $userGroup->getId()];
}
}
$this->saveObjectData($postType, $postId, $defaultGroups, true);
}
/**
* The function for the attachment_fields_to_save filter.
* We have to use this because the attachment actions work
* not in the way we need.
* @param array $attachment The attachment id.
* @return array
* @throws UserGroupTypeException
*/
public function saveAttachmentData(array $attachment): array
{
$this->savePostData($attachment['ID']);
return $attachment;
}
/**
* The function for the wp_ajax_save_attachment_compat filter.
* @throws UserGroupTypeException
*/
public function saveAjaxAttachmentData()
{
$attachmentId = $this->getRequestParameter('id');
$userGroups = $this->getRequestParameter(self::DEFAULT_GROUPS_FORM_NAME);
$this->saveObjectData(
ObjectHandler::GENERAL_POST_OBJECT_TYPE,
$attachmentId,
$userGroups
);
}
/**
* The function for the delete_post action.
* @param int|string $postId The post id.
*/
public function removePostData($postId)
{
$post = $this->objectHandler->getPost($postId);
$this->removeObjectData($post->post_type, $postId);
}
/**
* The function for the media_meta action.
* @param array $formFields The meta.
* @param WP_Post $post The post.
* @return array
* @throws UserGroupTypeException
*/
public function showMediaFile(array $formFields, $post = null): array
{
if ($this->getRequestParameter('action') !== 'edit') {
$attachmentId = $this->getRequestParameter('attachment_id');
if ($attachmentId !== null) {
$post = $this->objectHandler->getPost($attachmentId);
}
if ($post instanceof WP_Post) {
$this->setObjectInformation($post->post_type, $post->ID);
}
$formFields[self::DEFAULT_GROUPS_FORM_NAME] = [
'label' => TXT_UAM_SET_UP_USER_GROUPS,
'input' => 'editFrom',
'editFrom' => $this->getIncludeContents('MediaAjaxEditForm.php')
];
}
return $formFields;
}
}
<?php
/**
* SetupController.php
*
* The SetupController class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Controller\Backend;
use UserAccessManager\Config\WordpressConfig;
use UserAccessManager\Controller\Controller;
use UserAccessManager\Database\Database;
use UserAccessManager\Setup\Database\MissingColumnsException;
use UserAccessManager\Setup\SetupHandler;
use UserAccessManager\UserAccessManager;
use UserAccessManager\Wrapper\Php;
use UserAccessManager\Wrapper\Wordpress;
/**
* Class SetupController
*
* @package UserAccessManager\Controller
*/
class SetupController extends Controller
{
const SETUP_UPDATE_NONCE = 'uamSetupUpdate';
const SETUP_REVERT_NONCE = 'uamSetupRevert';
const SETUP_REPAIR_NONCE = 'uamSetupRepair';
const SETUP_DELETE_BACKUP_NONCE = 'uamSetupDeleteBackup';
const SETUP_RESET_NONCE = 'uamSetupReset';
const UPDATE_BLOG = 'blog';
const UPDATE_NETWORK = 'network';
/**
* @var string
*/
protected $template = 'AdminSetup.php';
/**
* @var SetupHandler
*/
private $setupHandler;
/**
* @var Database
*/
private $database;
/**
* SetupController constructor.
* @param Php $php
* @param Wordpress $wordpress
* @param WordpressConfig $wordpressConfig
* @param Database $database
* @param SetupHandler $setupHandler
*/
public function __construct(
Php $php,
Wordpress $wordpress,
WordpressConfig $wordpressConfig,
Database $database,
SetupHandler $setupHandler
) {
parent::__construct($php, $wordpress, $wordpressConfig);
$this->database = $database;
$this->setupHandler = $setupHandler;
}
/**
* Returns if a database update is necessary.
* @return bool
*/
public function isDatabaseUpdateNecessary(): bool
{
return $this->setupHandler->getDatabaseHandler()->isDatabaseUpdateNecessary();
}
/**
* Checks if a network update is nessary.
* @return bool
*/
public function showNetworkUpdate(): bool
{
return $this->wordpress->isSuperAdmin() === true
&& defined('MULTISITE') === true && MULTISITE === true
&& defined('WP_ALLOW_MULTISITE') === true && WP_ALLOW_MULTISITE === true;
}
/**
* Returns the existing backups
* @return array
*/
public function getBackups(): array
{
return $this->setupHandler->getDatabaseHandler()->getBackups();
}
/**
* The database update action.
*/
public function updateDatabaseAction()
{
$success = true;
$this->verifyNonce(self::SETUP_UPDATE_NONCE);
$update = $this->getRequestParameter('uam_update_db');
$backup = (bool) $this->getRequestParameter('uam_backup_db', false);
if ($update === self::UPDATE_BLOG || $update === self::UPDATE_NETWORK) {
$currentBlogId = $this->database->getCurrentBlogId();
$blogIds = ($update === self::UPDATE_NETWORK) ? $this->setupHandler->getBlogIds() : [$currentBlogId];
foreach ($blogIds as $blogId) {
$this->wordpress->switchToBlog($blogId);
if ($backup === true) {
$this->setupHandler->getDatabaseHandler()->backupDatabase();
}
$success = $success && $this->setupHandler->update();
$this->wordpress->restoreCurrentBlog();
}
$message = $success === true ? TXT_UAM_UAM_DB_UPDATE_SUCCESS : TXT_UAM_UAM_DB_UPDATE_FAILURE;
$this->setUpdateMessage($message);
}
}
/**
* Reverts the database to the given version.
*/
public function revertDatabaseAction()
{
$this->verifyNonce(self::SETUP_REVERT_NONCE);
$version = $this->getRequestParameter('uam_revert_database');
if ($this->setupHandler->getDatabaseHandler()->revertDatabase($version) === true) {
$this->setUpdateMessage(TXT_UAM_REVERT_DATABASE_SUCCESS);
}
}
/**
* Checks if the database is broken.
* @return bool
* @throws MissingColumnsException
*/
public function isDatabaseBroken(): bool
{
$information = $this->setupHandler->getDatabaseHandler()->getCorruptedDatabaseInformation();
$numberOfIssues = array_reduce(
$information,
function ($carry, $item) {
$carry += count($item);
return $carry;
}
);
return $numberOfIssues > 0;
}
/**
* Repairs the database.
* @throws MissingColumnsException
*/
public function repairDatabaseAction()
{
$this->verifyNonce(self::SETUP_REPAIR_NONCE);
$databaseHandler = $this->setupHandler->getDatabaseHandler();
$backups = $databaseHandler->getBackups();
if (isset($backups[UserAccessManager::DB_VERSION]) === false) {
$databaseHandler->backupDatabase();
}
if ($databaseHandler->repairDatabase() === true) {
$this->setUpdateMessage(TXT_UAM_REPAIR_DATABASE_SUCCESS);
$this->wordpress->updateOption('uam_db_version', UserAccessManager::DB_VERSION);
}
}
/**
* Deletes the given database backup.
*/
public function deleteDatabaseBackupAction()
{
$this->verifyNonce(self::SETUP_DELETE_BACKUP_NONCE);
$version = (string) $this->getRequestParameter('uam_delete_backup');
if ($this->setupHandler->getDatabaseHandler()->deleteBackup($version) === true) {
$this->setUpdateMessage(TXT_UAM_DELETE_DATABASE_BACKUP_SUCCESS);
}
}
/**
* The reset action.
* @throws MissingColumnsException
*/
public function resetUamAction()
{
$this->verifyNonce(self::SETUP_RESET_NONCE);
$reset = $this->getRequestParameter('uam_reset');
if ($reset === 'reset') {
$this->setupHandler->uninstall();
$this->setupHandler->install(true);
$this->setUpdateMessage(TXT_UAM_UAM_RESET_SUCCESS);
}
}
}
<?php
/**
* TermObjectController.php
*
* The TermObjectController class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Controller\Backend;
use UserAccessManager\Object\ObjectHandler;
use UserAccessManager\UserGroup\UserGroupTypeException;
use WP_Term;
/**
* Class TermObjectController
*
* @package UserAccessManager\Controller\Backend
*/
class TermObjectController extends ObjectController
{
/**
* The function for the manage_categories_columns filter.
* @param array $defaults The table headers.
* @return array
*/
public function addTermColumnsHeader(array $defaults): array
{
$defaults[self::COLUMN_NAME] = TXT_UAM_COLUMN_ACCESS;
return $defaults;
}
/**
* The function for the manage_categories_custom_column action.
* @param string|null $content Content for the column. Multiple filter calls are possible, so we need to append.
* @param string $columnName The column name.
* @param int|string $id The id.
* @return string|null $content with content appended for self::COLUMN_NAME column
* @throws UserGroupTypeException
*/
public function addTermColumn(?string $content, string $columnName, $id): ?string
{
if ($columnName === self::COLUMN_NAME) {
$term = $this->objectHandler->getTerm($id);
$objectType = ($term !== false) ? $term->taxonomy : ObjectHandler::GENERAL_TERM_OBJECT_TYPE;
$content .= $this->getGroupColumn($objectType, $id);
}
return $content;
}
/**
* The function for the edit_{term}_form action.
* @param string|WP_Term $term The term.
* @throws UserGroupTypeException
*/
public function showTermEditForm($term)
{
if ($term instanceof WP_Term) {
$this->setObjectInformation($term->taxonomy, $term->term_id);
} else {
$this->setObjectInformation($term, null);
}
echo $this->getIncludeContents('TermEditForm.php');
}
/**
* The function for the edit_term action.
* @param int|string $termId The term id.
* @throws UserGroupTypeException
*/
public function saveTermData($termId)
{
$term = $this->objectHandler->getTerm($termId);
$objectType = ($term !== false) ? $term->taxonomy : ObjectHandler::GENERAL_TERM_OBJECT_TYPE;
$this->saveObjectData($objectType, $termId);
}
/**
* The function for the delete_{term} action.
* @param int|string $termId The id of the term.
*/
public function removeTermData($termId)
{
$this->removeObjectData(ObjectHandler::GENERAL_TERM_OBJECT_TYPE, $termId);
}
}
<?php
/**
* UserObjectController.php
*
* The UserObjectController class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Controller\Backend;
use UserAccessManager\Object\ObjectHandler;
use UserAccessManager\UserGroup\UserGroupTypeException;
/**
* Class UserObjectController
*
* @package UserAccessManager\Controller\Backend
*/
class UserObjectController extends ObjectController
{
/**
* The function for the manage_users_columns filter.
* @param array $defaults The table headers.
* @return array
*/
public function addUserColumnsHeader(array $defaults): array
{
$defaults[self::COLUMN_NAME] = TXT_UAM_COLUMN_USER_GROUPS;
return $defaults;
}
/**
* The function for the manage_users_custom_column action.
* @param null|string $return The normal return value.
* @param string $columnName The column name.
* @param int|string $id The id.
* @return string|null
* @throws UserGroupTypeException
*/
public function addUserColumn(?string $return, string $columnName, $id): ?string
{
if ($columnName === self::COLUMN_NAME) {
$this->setObjectInformation(ObjectHandler::GENERAL_USER_OBJECT_TYPE, $id);
$return .= $this->getIncludeContents('UserColumn.php');
}
return $return;
}
/**
* The function for the edit_user_profile action.
* @throws UserGroupTypeException
*/
public function showUserProfile()
{
$userId = $this->getRequestParameter('user_id');
$this->setObjectInformation(ObjectHandler::GENERAL_USER_OBJECT_TYPE, $userId);
echo $this->getIncludeContents('UserProfileEditForm.php');
}
/**
* The function for the profile_update action.
* @param int|string $userId The user id.
* @throws UserGroupTypeException
* @throws UserGroupTypeException
*/
public function saveUserData($userId)
{
$this->saveObjectData(ObjectHandler::GENERAL_USER_OBJECT_TYPE, $userId);
}
/**
* The function for the delete_user action.
* @param int|string $userId The user id.
*/
public function removeUserData($userId)
{
$this->removeObjectData(ObjectHandler::GENERAL_USER_OBJECT_TYPE, $userId);
}
}
<?php
/**
* BaseControllerTrait.php
*
* The BaseControllerTrait trait file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Controller;
use Exception;
use UserAccessManager\Config\WordpressConfig;
use UserAccessManager\Wrapper\Php;
/**
* Trait BaseControllerTrait
*
* @package UserAccessManager\Controller
*/
trait BaseControllerTrait
{
/**
* @return Php
*/
abstract protected function getPhp(): Php;
/**
* @return WordpressConfig
*/
abstract protected function getWordpressConfig(): WordpressConfig;
/**
* @var string
*/
protected $template = null;
/**
* Returns the current request url.
* @return string
*/
public function getRequestUrl(): string
{
return htmlentities($_SERVER['REQUEST_URI']);
}
/**
* Sanitize the given value.
* @param mixed $value
* @return array|string
*/
private function sanitizeValue($value)
{
if (is_object($value) === true) {
return $value;
} elseif (is_array($value) === true) {
$newValue = [];
foreach ($value as $key => $arrayValue) {
$sanitizedKey = $this->sanitizeValue($key);
$newValue[$sanitizedKey] = $this->sanitizeValue($arrayValue);
}
$value = $newValue;
} elseif (is_string($value) === true) {
$value = preg_replace('/[\\\\]+(["|\'])/', '$1', $value);
$value = stripslashes($value);
$value = htmlspecialchars($value);
}
return $value;
}
/**
* Returns the request parameter.
* @param string $name
* @param mixed $default
* @return mixed
*/
public function getRequestParameter(string $name, $default = null)
{
$return = (isset($_POST[$name]) === true) ? $this->sanitizeValue($_POST[$name]) : null;
if ($return === null) {
$return = (isset($_GET[$name]) === true) ? $this->sanitizeValue($_GET[$name]) : $default;
}
return $return;
}
/**
* Returns the content of the excluded php file.
* @param string $fileName The view file name
* @return string
*/
protected function getIncludeContents(string $fileName): string
{
$contents = '';
$realPath = rtrim($this->getWordpressConfig()->getRealPath(), DIRECTORY_SEPARATOR);
$path = [$realPath, 'src', 'View'];
$path = implode(DIRECTORY_SEPARATOR, $path).DIRECTORY_SEPARATOR;
$fileWithPath = $path.$fileName;
if (is_file($fileWithPath) === true) {
try {
ob_start();
$this->getPhp()->includeFile($this, $fileWithPath);
$contents = ob_get_contents();
ob_end_clean();
} catch (Exception $exception) {
$contents = "Error on including content '{$fileWithPath}': {$exception->getMessage()}";
ob_end_clean();
}
}
return $contents;
}
/**
* Renders the given template
*/
public function render()
{
if ($this->template !== null) {
echo $this->getIncludeContents($this->template);
}
}
}
<?php
/**
* Controller.php
*
* The Controller class file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Controller;
use UserAccessManager\Config\WordpressConfig;
use UserAccessManager\Controller\Backend\BackendController;
use UserAccessManager\Wrapper\Php;
use UserAccessManager\Wrapper\Wordpress;
/**
* Class Controller
*
* @package UserAccessManager\Controller
*/
abstract class Controller
{
use BaseControllerTrait {
render as traitRender;
}
const ACTION_PARAMETER = 'uam_action';
const ACTION_SUFFIX = 'Action';
/**
* @var Php
*/
protected $php;
/**
* @var WordpressConfig
*/
protected $wordpressConfig;
/**
* @var Wordpress
*/
protected $wordpress;
/**
* @var string
*/
protected $updateMessage = null;
/**
* Controller constructor.
* @param Php $php
* @param Wordpress $wordpress
* @param WordpressConfig $wordpressConfig
*/
public function __construct(Php $php, Wordpress $wordpress, WordpressConfig $wordpressConfig)
{
$this->php = $php;
$this->wordpress = $wordpress;
$this->wordpressConfig = $wordpressConfig;
}
/**
* @return Php
*/
protected function getPhp(): Php
{
return $this->php;
}
/**
* @return WordpressConfig
*/
protected function getWordpressConfig(): WordpressConfig
{
return $this->wordpressConfig;
}
/**
* Returns the nonce field.
* @param string $name
* @return string
*/
public function createNonceField(string $name): string
{
return $this->wordpress->getNonceField($name, $name.'Nonce');
}
/**
* Returns the nonce.
* @param string $name
* @return string
*/
public function getNonce(string $name): string
{
return $this->wordpress->createNonce($name);
}
/**
* Verifies the nonce and terminates the application if the nonce is wrong.
* @param string $name
*/
protected function verifyNonce(string $name)
{
$nonce = $this->getRequestParameter($name.'Nonce');
if ($this->wordpress->verifyNonce($nonce, $name) === false) {
$this->wordpress->wpDie(TXT_UAM_NONCE_FAILURE_MESSAGE, TXT_UAM_NONCE_FAILURE_TITLE, ['response' => 401]);
}
}
/**
* Sets the update message.
* @param string $message
*/
protected function setUpdateMessage(string $message)
{
$this->updateMessage = $message;
}
/**
* Adds an error message.
* @param string $message
*/
protected function addErrorMessage(string $message)
{
if (isset($_SESSION[BackendController::UAM_ERRORS]) === false) {
$_SESSION[BackendController::UAM_ERRORS] = [];
}
$_SESSION[BackendController::UAM_ERRORS][] = $message;
}
/**
* Returns the update message.
* @return string
*/
public function getUpdateMessage(): ?string
{
return $this->updateMessage;
}
/**
* Returns true if a update message is set.
* @return bool
*/
public function hasUpdateMessage(): bool
{
return $this->updateMessage !== null;
}
/**
* Process the action.
*/
protected function processAction()
{
$postAction = (string) $this->getRequestParameter(self::ACTION_PARAMETER);
$postActionSplit = explode('_', $postAction);
$postAction = array_shift($postActionSplit);
$postAction .= implode('', array_map('ucfirst', $postActionSplit));
$actionMethod = $postAction.self::ACTION_SUFFIX;
if (method_exists($this, $actionMethod) === true) {
$this->{$actionMethod}();
}
}
/**
* Renders the given template
*/
public function render()
{
$this->processAction();
$this->traitRender();
}
}
<?php
/**
* FrontendAdminOutputControllerTrait.php
*
* The FrontendTermController trait file.
*
* PHP versions 5
*
* @author Alexander Schneider <alexanderschneider85@gmail.com>
* @copyright 2008-2017 Alexander Schneider
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2
* @version SVN: $id$
* @link http://wordpress.org/extend/plugins/user-access-manager/
*/
declare(strict_types=1);
namespace UserAccessManager\Controller\Frontend;
use UserAccessManager\Config\MainConfig;
use UserAccessManager\Config\WordpressConfig;
use UserAccessManager\User\UserHandler;
use UserAccessManager\UserGroup\UserGroupHandler;
use UserAccessManager\UserGroup\UserGroupTypeException;
use UserAccessManager\Util\Util;
use UserAccessManager\Wrapper\Wordpress;
/**
* Trait FrontendAdminOutputControllerTrait
*
* @package UserAccessManager\Controller
*/
trait AdminOutputControllerTrait
{
/**
* @return Wordpress
*/
abstract protected function getWordpress(): Wordpress;
/**
* @return WordpressConfig
*/
abstract protected function getWordpressConfig(): WordpressConfig;
/**
* @return MainConfig
*/
abstract protected function getMainConfig(): MainConfig;
/**
* @return Util
*/
abstract protected function getUtil(): Util;
/**
* @return UserHandler
*/
abstract protected function getUserHandler(): UserHandler;
/**
* @return UserGroupHandler
*/
abstract protected function getUserGroupHandler(): UserGroupHandler;
/**
* Returns true if the hint text should be shown.
* @return bool
*/
private function showAdminHint(): bool
{
return $this->getWordpressConfig()->atAdminPanel() === false
&& $this->getMainConfig()->blogAdminHint() === true;
}
/**
* Returns the admin hint.
* @param string $objectType The object type.
* @param int|string $objectId The object id we want to check.
* @param null $text The text on which we want to append the hint.
* @return string
* @throws UserGroupTypeException
*/
public function adminOutput(string $objectType, $objectId, $text = null): string
{
if ($this->showAdminHint() === true) {
$hintText = $this->getMainConfig()->getBlogAdminHintText();
if ($text !== null && $this->getUtil()->endsWith($text, $hintText) === true) {
return '';
}
if ($this->getUserHandler()->userIsAdmin($this->getWordpress()->getCurrentUser()->ID) === true
&& count($this->getUserGroupHandler()->getUserGroupsForObject($objectType, $objectId)) > 0
) {
return $hintText;
}
}
return '';
}
}
<?php
declare(strict_types=1);
namespace UserAccessManager\Controller\Frontend;
use UserAccessManager\Access\AccessHandler;
use UserAccessManager\Config\MainConfig;
use UserAccessManager\Config\WordpressConfig;
use UserAccessManager\Controller\Controller;
use UserAccessManager\Object\ObjectHandler;
use UserAccessManager\Object\ObjectMapHandler;
use UserAccessManager\User\UserHandler;
use UserAccessManager\UserGroup\UserGroupHandler;
use UserAccessManager\Util\Util;
use UserAccessManager\Wrapper\Php;
use UserAccessManager\Wrapper\Wordpress;
/**
* Class ContentController
*
* @package UserAccessManager\Controller\Frontend
*/
abstract class ContentController extends Controller
{
use AdminOutputControllerTrait;
/**
* @var MainConfig
*/
protected $mainConfig;
/**
* @var Util
*/
protected $util;
/**
* @var ObjectHandler
*/
protected $objectHandler;
/**
* @var ObjectMapHandler
*/
protected $objectMapHandler;
/**
* @var UserHandler
*/
protected $userHandler;
/**
* @var UserGroupHandler
*/
protected $userGroupHandler;
/**
* @var AccessHandler
*/
protected $accessHandler;
/**
* ContentController constructor.
* @param Php $php
* @param Wordpress $wordpress
* @param WordpressConfig $wordpressConfig
* @param MainConfig $mainConfig
* @param Util $util
* @param ObjectHandler $objectHandler
* @param UserHandler $userHandler
* @param UserGroupHandler $userGroupHandler
* @param AccessHandler $accessHandler
*/
public function __construct(
Php $php,
Wordpress $wordpress,
WordpressConfig $wordpressConfig,
MainConfig $mainConfig,
Util $util,
ObjectHandler $objectHandler,
UserHandler $userHandler,
UserGroupHandler $userGroupHandler,
AccessHandler $accessHandler
) {
parent::__construct($php, $wordpress, $wordpressConfig);
$this->mainConfig = $mainConfig;
$this->util = $util;
$this->objectHandler = $objectHandler;
$this->userHandler = $userHandler;
$this->userGroupHandler = $userGroupHandler;
$this->accessHandler = $accessHandler;
}
/**
* @return Wordpress
*/
protected function getWordpress(): Wordpress
{
return $this->wordpress;
}
/**
* @return MainConfig
*/
protected function getMainConfig(): MainConfig
{
return $this->mainConfig;
}
/**
* @return Util
*/
protected function getUtil(): Util
{
return $this->util;
}
/**
* @return UserHandler
*/
protected function getUserHandler(): UserHandler
{
return $this->userHandler;
}
/**
* @return UserGroupHandler
*/
protected function getUserGroupHandler(): UserGroupHandler
{
return $this->userGroupHandler;
}
protected function removePostFromList($postType): bool
{
return $this->mainConfig->hidePostType($postType) === true
|| $this->wordpressConfig->atAdminPanel() === true;
}
}