Passed
Push — master ( c0a3a7...3b84a4 )
by Jeroen
58:51
created

elgg_admin_gatekeeper()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 0
dl 0
loc 8
ccs 0
cts 5
cp 0
crap 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Elgg page handler functions
4
 *
5
 * @package    Elgg.Core
6
 * @subpackage Routing
7
 */
8
9
/**
10
 * Register a new route
11
 *
12
 * Route paths can contain wildcard segments, i.e. /blog/owner/{username}
13
 * To make a certain wildcard segment optional, add ? to its name,
14
 * i.e. /blog/owner/{username?}
15
 *
16
 * Wildcard requirements for common named variables such as 'guid' and 'username'
17
 * will be set automatically.
18
 *
19
 * @warning If you are registering a route in the path of a route registered by
20
 *          deprecated {@link elgg_register_page_handler}, your registration must
21
 *          preceed the call to elgg_register_page_handler() in the boot sequence.
22
 *
23
 * @param string $name   Unique route name
24
 *                       This name can later be used to generate route URLs
25
 * @param array  $params Route parameters
26
 *                       - path : path of the route
27
 *                       - resource : name of the resource view
28
 *                       - defaults : default values of wildcard segments
29
 *                       - requirements : regex patterns for wildcard segment requirements
30
 *                       - methods : HTTP methods
31
 *
32
 * @return \Elgg\Router\Route
33
 */
34
function elgg_register_route($name, array $params = []) {
35 112
	return _elgg_services()->router->registerRoute($name, $params);
36
}
37
38
/**
39
 * Unregister a route by its name
40
 *
41
 * @param string $name Name of the route
42
 *
43
 * @return void
44
 */
45
function elgg_unregister_route($name) {
46 19
	_elgg_services()->router->unregisterRoute($name);
47 19
}
48
49
/**
50
 * Generate a URL for named route
51
 *
52
 * @param string $name       Route name
53
 * @param array  $parameters Parameters
54
 *
55
 * @return string
56
 */
57
function elgg_generate_url($name, array $parameters = []) {
58 32
	return _elgg_services()->router->generateUrl($name, $parameters);
59
}
60
61
/**
62
 * Used at the top of a page to mark it as logged in users only.
63
 *
64
 * @return void
65
 * @throws \Elgg\GatekeeperException
66
 * @since 1.9.0
67
 */
68
function elgg_gatekeeper() {
69
	if (!elgg_is_logged_in()) {
70
		_elgg_services()->redirects->setLastForwardFrom();
71
72
		$msg = elgg_echo('loggedinrequired');
73
		throw new \Elgg\GatekeeperException($msg);
74
	}
75
}
76
77
/**
78
 * Used at the top of a page to mark it as admin only.
79
 *
80
 * @return void
81
 * @throws \Elgg\GatekeeperException
82
 * @since 1.9.0
83
 */
84
function elgg_admin_gatekeeper() {
85
	elgg_gatekeeper();
86
87
	if (!elgg_is_admin_logged_in()) {
88
		_elgg_services()->redirects->setLastForwardFrom();
89
90
		$msg = elgg_echo('adminrequired');
91
		throw new \Elgg\GatekeeperException($msg);
92
	}
93
}
94
95
96
/**
97
 * May the current user access item(s) on this page? If the page owner is a group,
98
 * membership, visibility, and logged in status are taken into account.
99
 *
100
 * @param bool $forward    If set to true (default), will forward the page;
101
 *                         if set to false, will return true or false.
102
 *
103
 * @param int  $group_guid The group that owns the page. If not set, this
104
 *                         will be pulled from elgg_get_page_owner_guid().
105
 *
106
 * @return bool Will return if $forward is set to false.
107
 * @throws InvalidParameterException
108
 * @throws SecurityException
109
 * @since 1.9.0
110
 */
111
function elgg_group_gatekeeper($forward = true, $group_guid = null) {
112
	if (null === $group_guid) {
113
		$group_guid = elgg_get_page_owner_guid();
114
	}
115
116
	if (!$group_guid) {
117
		return true;
118
	}
119
120
	// this handles non-groups and invisible groups
121
	$visibility = \Elgg\GroupItemVisibility::factory($group_guid);
122
123
	if (!$visibility->shouldHideItems) {
124
		return true;
125
	}
126
	if ($forward) {
127
		// only forward to group if user can see it
128
		$group = get_entity($group_guid);
129
		$forward_url = $group ? $group->getURL() : '';
130
131
		if (!elgg_is_logged_in()) {
132
			_elgg_services()->redirects->setLastForwardFrom();
133
			$forward_reason = 'login';
134
		} else {
135
			$forward_reason = 'member';
136
		}
137
138
		$msg_keys = [
139
			'non_member' => 'membershiprequired',
140
			'logged_out' => 'loggedinrequired',
141
			'no_access' => 'noaccess',
142
		];
143
		register_error(elgg_echo($msg_keys[$visibility->reasonHidden]));
144
		forward($forward_url, $forward_reason);
145
	}
146
147
	return false;
148
}
149
150
/**
151
 * Can the viewer see this entity?
152
 *
153
 * Tests if the entity exists and whether the viewer has access to the entity
154
 * if it does. If the viewer cannot view this entity, it forwards to an
155
 * appropriate page.
156
 *
157
 * @param int    $guid    Entity GUID
158
 * @param string $type    Optional required entity type
159
 * @param string $subtype Optional required entity subtype
160
 * @param bool   $forward If set to true (default), will forward the page;
161
 *                        if set to false, will return true or false.
162
 *
163
 * @return bool Will return if $forward is set to false.
164
 * @throws \Elgg\BadRequestException
165
 * @throws \Elgg\EntityNotFoundException
166
 * @throws \Elgg\EntityPermissionsException
167
 * @throws \Elgg\GatekeeperException
168
 * @since 1.9.0
169
 */
170
function elgg_entity_gatekeeper($guid, $type = null, $subtype = null, $forward = true) {
171
	$entity = get_entity($guid);
172
	if (!$entity && $forward) {
173
		if (!elgg_entity_exists($guid)) {
174
			// entity doesn't exist
175
			throw new \Elgg\EntityNotFoundException();
176
		} else if (!elgg_is_logged_in()) {
177
			// entity requires at least a logged in user
178
			elgg_gatekeeper();
179
		} else {
180
			// user is logged in but still does not have access to it
181
			$msg = elgg_echo('limited_access');
182
			throw new \Elgg\GatekeeperException($msg);
183
		}
184
	} else if (!$entity) {
185
		return false;
186
	}
187
188
	if ($type && !elgg_instanceof($entity, $type, $subtype)) {
0 ignored issues
show
Bug Best Practice introduced by Ismayil Khayredinov
The expression $type of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
189
		// entity is of wrong type/subtype
190
		if ($forward) {
191
			throw new \Elgg\BadRequestException();
192
		} else {
193
			return false;
194
		}
195
	}
196
197
	$hook_type = "{$entity->getType()}:{$entity->getSubtype()}";
198
	$hook_params = [
199
		'entity' => $entity,
200
		'forward' => $forward,
201
	];
202
	if (!elgg_trigger_plugin_hook('gatekeeper', $hook_type, $hook_params, true)) {
203
		if ($forward) {
204
			throw new \Elgg\EntityPermissionsException();
205
		} else {
206
			return false;
207
		}
208
	}
209
210
	return true;
211
}
212
213
/**
214
 * Require that the current request be an XHR. If not, execution of the current function
215
 * will end and a 400 response page will be sent.
216
 *
217
 * @return void
218
 * @throws \Elgg\BadRequestException
219
 * @since 1.12.0
220
 */
221
function elgg_ajax_gatekeeper() {
222 17
	if (!elgg_is_xhr()) {
223
		$msg = elgg_echo('ajax:not_is_xhr');
224
		throw new \Elgg\BadRequestException($msg);
225
	}
226 17
}
227
228
/**
229
 * Prepares a successful response to be returned by a page or an action handler
230
 *
231
 * @param mixed  $content     Response content
232
 *                            In page handlers, response content should contain an HTML string
233
 *                            In action handlers, response content can contain either a JSON string or an array of data
234
 * @param string $message     System message visible to the client
235
 *                            Can be used by handlers to display a system message
236
 * @param string $forward_url Forward URL
237
 *                            Can be used by handlers to redirect the client on non-ajax requests
238
 * @param int    $status_code HTTP status code
239
 *                            Status code of the HTTP response (defaults to 200)
240
 *
241
 * @return \Elgg\Http\OkResponse
242
 */
243
function elgg_ok_response($content = '', $message = '', $forward_url = null, $status_code = ELGG_HTTP_OK) {
244 70
	if ($message) {
245 8
		system_message($message);
246
	}
247
248 70
	return new \Elgg\Http\OkResponse($content, $status_code, $forward_url);
249
250
}
251
252
/**
253
 * Prepare an error response to be returned by a page or an action handler
254
 *
255
 * @param string $error       Error message
256
 *                            Can be used by handlers to display an error message
257
 *                            For certain requests this error message will also be used as the response body
258
 * @param string $forward_url URL to redirect the client to
259
 *                            Can be used by handlers to redirect the client on non-ajax requests
260
 * @param int    $status_code HTTP status code
261
 *                            Status code of the HTTP response
262
 *                            For BC reasons and due to the logic in the client-side AJAX API,
263
 *                            this defaults to 200. Note that the Router and AJAX API will
264
 *                            treat these responses as error in spite of the HTTP code assigned
265
 *
266
 * @return \Elgg\Http\ErrorResponse
267
 */
268
function elgg_error_response($error = '', $forward_url = REFERRER, $status_code = ELGG_HTTP_OK) {
269 36
	if ($error) {
270 32
		register_error($error);
271
	}
272
273 36
	return new \Elgg\Http\ErrorResponse($error, $status_code, $forward_url);
274
}
275
276
/**
277
 * Prepare a silent redirect response to be returned by a page or an action handler
278
 *
279
 * @param string $forward_url Redirection URL
280
 *                            Relative or absolute URL to redirect the client to
281
 * @param int    $status_code HTTP status code
282
 *                            Status code of the HTTP response
283
 *                            Note that the Router and AJAX API will treat these responses
284
 *                            as redirection in spite of the HTTP code assigned
285
 *                            Note that non-redirection HTTP codes will throw an exception
286
 *
287
 * @return \Elgg\Http\RedirectResponse
288
 * @throws \InvalidArgumentException
289
 */
290
function elgg_redirect_response($forward_url = REFERRER, $status_code = ELGG_HTTP_FOUND) {
291 6
	return new Elgg\Http\RedirectResponse($forward_url, $status_code);
292
}
293
294
295
/**
296
 * @see \Elgg\Application::loadCore Do not do work here. Just register for events.
297
 */
298
return function (\Elgg\EventsService $events, \Elgg\HooksRegistrationService $hooks) {
1 ignored issue
show
Unused Code introduced by Ismayil Khayredinov
The parameter $events is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

298
return function (/** @scrutinizer ignore-unused */ \Elgg\EventsService $events, \Elgg\HooksRegistrationService $hooks) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by Steve Clay
The parameter $hooks is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

298
return function (\Elgg\EventsService $events, /** @scrutinizer ignore-unused */ \Elgg\HooksRegistrationService $hooks) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
299
300
};
301