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