-
-
Notifications
You must be signed in to change notification settings - Fork 236
Expand file tree
/
Copy pathBackendController.php
More file actions
347 lines (305 loc) · 11.8 KB
/
BackendController.php
File metadata and controls
347 lines (305 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
<?php
namespace Backend\Classes;
use Backend\Facades\BackendAuth;
use Closure;
use Illuminate\Routing\Controller as ControllerBase;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\View;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use System\Classes\PluginManager;
use Winter\Storm\Router\Helper as RouterHelper;
use Winter\Storm\Support\Facades\Config;
use Winter\Storm\Support\Facades\Event;
use Winter\Storm\Support\Facades\File;
use Winter\Storm\Support\Str;
/**
* This is the master controller for all back-end pages.
* All requests that are prefixed with the backend URI pattern are sent here,
* then the next URI segments are analysed and the request is routed to the
* relevant back-end controller.
*
* For example, a request with the URL `/backend/acme/blog/posts` will look
* for the `Posts` controller inside the `Acme.Blog` plugin.
*
* @see Backend\Classes\Controller Base class for back-end controllers
* @package winter\wn-backend-module
* @author Alexey Bobkov, Samuel Georges
*/
class BackendController extends ControllerBase
{
use \Winter\Storm\Extension\ExtendableTrait;
/**
* @var array Behaviors implemented by this controller.
*/
public $implement;
/**
* @var string Allows early access to page action.
*/
public static $action;
/**
* @var array Allows early access to page parameters.
*/
public static $params;
/**
* @var boolean Flag to indicate that the CMS module is handling the current request
*/
protected $cmsHandling = false;
/**
* Stores the requested controller so that the constructor is only run once
*
* @var Backend\Classes\Controller
*/
protected $requestedController;
/**
* Instantiate a new BackendController instance.
*/
public function __construct()
{
$this->middleware(function ($request, $next) {
// Process the request before retrieving controller middleware, to allow for the session and auth data
// to be made available to the controller's constructor.
$response = $next($request);
// Find requested controller to determine if any middleware has been attached
$pathParts = explode('/', str_replace(Request::root() . '/', '', Request::url()));
if (count($pathParts)) {
// Drop off preceding backend URL part if needed
if (!empty(Config::get('cms.backendUri', 'backend'))) {
array_shift($pathParts);
}
$path = implode('/', $pathParts);
$requestedController = $this->getRequestedController($path);
if (
!is_null($requestedController)
&& is_array($requestedController)
&& count($requestedController['controller']->getMiddleware())
) {
$action = $requestedController['action'];
// Collect applicable middleware and insert middleware into pipeline
$controllerMiddleware = collect($requestedController['controller']->getMiddleware())
->reject(function ($data) use ($action) {
return static::methodExcludedByOptions($action, $data['options']);
})
->pluck('middleware');
foreach ($controllerMiddleware as $middleware) {
$middleware->call($requestedController['controller'], $request, $response);
}
}
}
return $response;
});
$this->extendableConstruct();
}
/**
* @inheritDoc
*/
public function callAction($method, $parameters)
{
return parent::callAction($method, array_values($parameters));
}
/**
* Pass unhandled URLs to the CMS Controller, if it exists
*
* @param string $url
* @return \Illuminate\Http\Response
*/
protected function passToCmsController($url)
{
if (
in_array('Cms', Config::get('cms.loadModules', [])) &&
class_exists('\Cms\Classes\Controller')
) {
$this->cmsHandling = true;
$response = App::make('Cms\Classes\Controller')->run($url);
if ($response->getStatusCode() !== 404 || !BackendAuth::check()) {
return $response;
}
}
return Response::make(View::make('backend::404'), 404);
}
/**
* Finds and serves the requested backend controller.
* If the controller cannot be found, returns the Cms page with the URL /404.
* If the /404 page doesn't exist, returns the system 404 page.
* @param string $url Specifies the requested page URL.
* If the parameter is omitted, the current URL used.
* @return string Returns the processed page content.
*/
public function run($url = null)
{
// Handle NotFoundHttpExceptions in the backend (usually triggered by abort(404))
Event::listen('exception.beforeRender', function ($exception, $httpCode, $request) {
if ($this->cmsHandling) {
return;
}
if ($exception instanceof NotFoundHttpException) {
return View::make('backend::404');
} elseif (
$exception instanceof HttpException
&& $exception->getStatusCode() === 403
) {
return View::make('backend::access_denied');
}
}, 1);
/*
* Database check
*/
if (!App::hasDatabase()) {
return Config::get('app.debug', false)
? Response::make(View::make('backend::no_database'), 200)
: $this->passToCmsController($url);
}
$controllerRequest = $this->getRequestedController($url);
if (!is_null($controllerRequest)) {
return $controllerRequest['controller']->run(
$controllerRequest['action'],
$controllerRequest['params']
);
}
/*
* Fall back on Cms controller
*/
return $this->passToCmsController($url);
}
/**
* Determines the controller and action to load in the backend via a provided URL.
*
* If a suitable controller is found, this will return an array with the controller class name as a string, the
* action to call as a string and an array of parameters. If a suitable controller and action cannot be found,
* this method will return null.
*
* @param string $url A URL to determine the requested controller and action for
* @return array|null A suitable controller, action and parameters in an array if found, otherwise null.
*/
protected function getRequestedController($url)
{
$params = RouterHelper::segmentizeUrl($url);
/*
* Look for a Module controller
*/
$module = $params[0] ?? 'backend';
$controller = $params[1] ?? 'index';
self::$action = $action = isset($params[2]) ? $this->parseAction($params[2]) : 'index';
self::$params = $controllerParams = array_slice($params, 3);
$controllerClass = '\\'.$module.'\Controllers\\'.$controller;
if ($controllerObj = $this->findController(
$controllerClass,
$action,
base_path().'/modules'
)) {
return [
'controller' => $controllerObj,
'action' => $action,
'params' => $controllerParams
];
}
/*
* Look for a Plugin controller
*/
if (count($params) >= 2) {
list($author, $plugin) = $params;
$pluginCode = ucfirst($author) . '.' . ucfirst($plugin);
if (PluginManager::instance()->isDisabled($pluginCode)) {
return Response::make(View::make('backend::404'), 404);
}
$controller = $params[2] ?? 'index';
self::$action = $action = isset($params[3]) ? $this->parseAction($params[3]) : 'index';
self::$params = $controllerParams = array_slice($params, 4);
$controllerClass = '\\'.$author.'\\'.$plugin.'\Controllers\\'.$controller;
if ($controllerObj = $this->findController(
$controllerClass,
$action,
plugins_path()
)) {
return [
'controller' => $controllerObj,
'action' => $action,
'params' => $controllerParams
];
}
}
return null;
}
/**
* This method is used internally.
* Finds a backend controller with a callable action method.
* @param string $controller Specifies a method name to execute.
* @param string $action Specifies a method name to execute.
* @param string $inPath Base path for class file location.
* @return ControllerBase Returns the backend controller object
*/
protected function findController($controller, $action, $inPath)
{
if (isset($this->requestedController)) {
return $this->requestedController;
}
/*
* Workaround: Composer does not support case insensitivity.
*/
if (!class_exists($controller)) {
$controller = Str::normalizeClassName($controller);
$controllerFile = $inPath.strtolower(str_replace('\\', '/', $controller)) . '.php';
if ($controllerFile = File::existsInsensitive($controllerFile)) {
include_once $controllerFile;
}
}
if (!class_exists($controller)) {
return $this->requestedController = null;
}
$controllerObj = App::make($controller);
if ($controllerObj->actionExists($action)) {
return $this->requestedController = $controllerObj;
}
return $this->requestedController = null;
}
/**
* Process the action name, since dashes are not supported in PHP methods.
* @param string $actionName
* @return string
*/
protected function parseAction($actionName)
{
if (strpos($actionName, '-') !== false) {
return camel_case($actionName);
}
return $actionName;
}
/**
* Determine if the given options exclude a particular method.
*
* @param string $method
* @param array $options
* @return bool
*/
protected static function methodExcludedByOptions($method, array $options)
{
return (isset($options['only']) && !in_array($method, (array) $options['only'])) ||
(!empty($options['except']) && in_array($method, (array) $options['except']));
}
public function __call($name, $params)
{
if ($name === 'extend') {
if (empty($params[0]) || !is_callable($params[0])) {
throw new \InvalidArgumentException('The extend() method requires a callback parameter or closure.');
}
if ($params[0] instanceof Closure) {
return $params[0]->call($this, $params[1] ?? $this);
}
return Closure::fromCallable($params[0])->call($this, $params[1] ?? $this);
}
return $this->extendableCall($name, $params);
}
public static function __callStatic($name, $params)
{
if ($name === 'extend') {
if (empty($params[0])) {
throw new \InvalidArgumentException('The extend() method requires a callback parameter or closure.');
}
self::extendableExtendCallback($params[0], $params[1] ?? false, $params[2] ?? null);
return;
}
return self::extendableCallStatic($name, $params);
}
}