1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SilverStripe\Subsites\Middleware; |
4
|
|
|
|
5
|
|
|
use SilverStripe\Admin\AdminRootController; |
6
|
|
|
use SilverStripe\Control\HTTPRequest; |
7
|
|
|
use SilverStripe\Control\Middleware\HTTPMiddleware; |
8
|
|
|
use SilverStripe\Core\Config\Configurable; |
9
|
|
|
use SilverStripe\Core\Injector\Injector; |
10
|
|
|
use SilverStripe\Subsites\Model\Subsite; |
11
|
|
|
use SilverStripe\Subsites\State\SubsiteState; |
12
|
|
|
|
13
|
|
|
class InitStateMiddleware implements HTTPMiddleware |
14
|
|
|
{ |
15
|
|
|
use Configurable; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* URL paths that should be considered as admin only, i.e. not frontend |
19
|
|
|
* |
20
|
|
|
* @config |
21
|
|
|
* @var array |
22
|
|
|
*/ |
23
|
|
|
private static $admin_url_paths = [ |
|
|
|
|
24
|
|
|
'dev/', |
25
|
|
|
'graphql/', |
26
|
|
|
]; |
27
|
|
|
|
28
|
|
|
public function process(HTTPRequest $request, callable $delegate) |
29
|
|
|
{ |
30
|
|
|
$state = SubsiteState::create(); |
31
|
|
|
Injector::inst()->registerService($state); |
32
|
|
|
|
33
|
|
|
// If the request is from the CMS, we should enable session storage |
34
|
|
|
$state->setUseSessions($this->getIsAdmin($request)); |
35
|
|
|
|
36
|
|
|
$state->setSubsiteId($this->detectSubsiteId($request)); |
37
|
|
|
|
38
|
|
|
return $delegate($request); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Determine whether the website is being viewed from an admin protected area or not |
43
|
|
|
* |
44
|
|
|
* @param HTTPRequest $request |
45
|
|
|
* @return bool |
46
|
|
|
*/ |
47
|
|
|
public function getIsAdmin(HTTPRequest $request) |
48
|
|
|
{ |
49
|
|
|
$adminPaths = static::config()->get('admin_url_paths'); |
50
|
|
|
$adminPaths[] = AdminRootController::config()->get('url_base') . '/'; |
51
|
|
|
$currentPath = rtrim($request->getURL(), '/') . '/'; |
52
|
|
|
foreach ($adminPaths as $adminPath) { |
53
|
|
|
if (substr($currentPath, 0, strlen($adminPath)) === $adminPath) { |
54
|
|
|
return true; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
return false; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Use the given request to detect the current subsite ID |
62
|
|
|
* |
63
|
|
|
* @param HTTPRequest $request |
64
|
|
|
* @return int |
65
|
|
|
*/ |
66
|
|
|
protected function detectSubsiteId(HTTPRequest $request) |
67
|
|
|
{ |
68
|
|
|
$id = null; |
69
|
|
|
|
70
|
|
|
if ($request->getVar('SubsiteID')) { |
71
|
|
|
$id = (int) $request->getVar('SubsiteID'); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
if (SubsiteState::singleton()->getUseSessions()) { |
75
|
|
|
$id = $request->getSession()->get('SubsiteID'); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
if ($id === null) { |
79
|
|
|
$id = Subsite::getSubsiteIDForDomain(); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
return (int) $id; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
This check marks private properties in classes that are never used. Those properties can be removed.