-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathNodeRedirectService.php
308 lines (257 loc) · 11.2 KB
/
NodeRedirectService.php
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
<?php
declare(strict_types=1);
namespace Neos\RedirectHandler\NeosAdapter\Service;
/*
* This file is part of the Neos.RedirectHandler.NeosAdapter package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\ContentRepository\Core\SharedModel\Node\NodeAddress;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Persistence\PersistenceManagerInterface;
use Neos\Neos\Domain\Model\Domain;
use Neos\Neos\Domain\Model\SiteNodeName;
use Neos\Neos\Domain\Repository\SiteRepository;
use Neos\Neos\FrontendRouting\NodeUriBuilderFactory;
use Neos\RedirectHandler\Storage\RedirectStorageInterface;
use Psr\Http\Message\UriInterface;
use Psr\Log\LoggerInterface;
use Neos\ContentRepository\Core\NodeType\NodeType;
use Neos\Neos\FrontendRouting\NodeUriBuilder;
use Neos\ContentRepository\Core\SharedModel\ContentRepository\ContentRepositoryId;
use GuzzleHttp\Psr7\ServerRequest;
use Neos\Neos\FrontendRouting\SiteDetection\SiteDetectionResult;
use Neos\Flow\Mvc\ActionRequest;
use Neos\Neos\FrontendRouting\Projection\DocumentNodeInfo;
use Neos\ContentRepository\Core\NodeType\NodeTypeName;
use Neos\ContentRepositoryRegistry\ContentRepositoryRegistry;
use GuzzleHttp\Psr7\Uri;
use Neos\Flow\Mvc\Exception\NoMatchingRouteException;
/**
* Service that creates redirects for moved / deleted nodes.
*
* Note: This is usually invoked by a catchup hook. See: Neos\RedirectHandler\NeosAdapter\CatchUpHook\DocumentUriPathProjectionHook
*
* @Flow\Scope("singleton")
*/
final class NodeRedirectService
{
const STATUS_CODE_TYPE_REDIRECT = 'redirect';
const STATUS_CODE_TYPE_GONE = 'gone';
/**
* @var array<string,array{node:DocumentNodeInfo,url:UriInterface}|null>
*/
private array $affectedNodes = [];
/**
* @var array<string,list<string>>
*/
private array $hostnamesRuntimeCache = [];
#[Flow\Inject]
protected ?LoggerInterface $logger = null;
/**
* @var array<string, int>
*/
#[Flow\InjectConfiguration(path: "statusCode", package: "Neos.RedirectHandler")]
protected array $defaultStatusCode;
#[Flow\InjectConfiguration(path: "enableAutomaticRedirects", package: "Neos.RedirectHandler.NeosAdapter")]
protected bool $enableAutomaticRedirects;
#[Flow\InjectConfiguration(path: "enableRemovedNodeRedirect", package: "Neos.RedirectHandler.NeosAdapter")]
protected bool $enableRemovedNodeRedirect;
/**
* @var array<string, bool>
*/
#[Flow\InjectConfiguration(path: "restrictByOldUriPrefix", package: "Neos.RedirectHandler.NeosAdapter")]
protected array $restrictByOldUriPrefix = [];
/**
* @var array<string, bool>
*/
#[Flow\InjectConfiguration(path: "restrictByNodeType", package: "Neos.RedirectHandler.NeosAdapter")]
protected array $restrictByNodeType = [];
public function __construct(
private readonly RedirectStorageInterface $redirectStorage,
private readonly PersistenceManagerInterface $persistenceManager,
private readonly ContentRepositoryRegistry $contentRepositoryRegistry,
private readonly SiteRepository $siteRepository,
private readonly NodeUriBuilderFactory $nodeUriBuilderFactory
) {
}
/**
* Collects affected nodes before they got moved or removed.
*/
public function appendAffectedNode(DocumentNodeInfo $nodeInfo, NodeAddress $nodeAddress): void
{
try {
$this->affectedNodes[$this->createAffectedNodesKey($nodeInfo, $nodeAddress->contentRepositoryId)] = [
'node' => $nodeInfo,
'url' => $this->getNodeUriBuilder($nodeInfo->getSiteNodeName(), $nodeAddress->contentRepositoryId)->uriFor($nodeAddress),
];
} catch (NoMatchingRouteException $exception) {
}
}
/**
* Creates redirects for given node and uses the collected affected nodes to determine the source of the new redirect target.
*/
public function createRedirectForAffectedNode(DocumentNodeInfo $nodeInfo, NodeAddress $nodeAddress): void
{
if (!$this->enableAutomaticRedirects) {
return;
}
$affectedNode = $this->affectedNodes[$this->createAffectedNodesKey($nodeInfo, $nodeAddress->contentRepositoryId)] ?? null;
if ($affectedNode === null) {
return;
}
unset($this->affectedNodes[$this->createAffectedNodesKey($nodeInfo, $nodeAddress->contentRepositoryId)]);
/** @var Uri $oldUri */
$oldUri = $affectedNode['url'];
$nodeType = $this->getNodeType($nodeAddress->contentRepositoryId, $nodeInfo->getNodeTypeName());
if (!$nodeType || $this->isRestrictedByNodeType($nodeType) || $this->isRestrictedByOldUri($oldUri->getPath())) {
return;
}
try {
$newUri = $this->getNodeUriBuilder($nodeInfo->getSiteNodeName(), $nodeAddress->contentRepositoryId)->uriFor($nodeAddress);
} catch (NoMatchingRouteException $exception) {
// We can't build an uri for given node, so we can't create any redirect. E.g.: Node is disabled.
return;
}
$this->createRedirectWithNewTarget($oldUri->getPath(), $newUri->getPath(), $nodeInfo->getSiteNodeName());
$this->persistenceManager->persistAll();
}
/**
* Creates redirects for given removed node and uses the collected affected nodes to determine the source of the new redirect.
*/
public function createRedirectForRemovedAffectedNode(DocumentNodeInfo $nodeInfo, ContentRepositoryId $contentRepositoryId): void
{
if (!$this->enableAutomaticRedirects) {
return;
}
$affectedNode = $this->affectedNodes[$this->createAffectedNodesKey($nodeInfo, $contentRepositoryId)] ?? null;
if ($affectedNode === null) {
return;
}
unset($this->affectedNodes[$this->createAffectedNodesKey($nodeInfo, $contentRepositoryId)]);
/** @var Uri $oldUri */
$oldUri = $affectedNode['url'];
$nodeType = $this->getNodeType($contentRepositoryId, $nodeInfo->getNodeTypeName());
if (!$nodeType || $this->isRestrictedByNodeType($nodeType) || $this->isRestrictedByOldUri($oldUri->getPath())) {
return;
}
$this->createRedirectForRemovedTarget($oldUri->getPath(), $nodeInfo->getSiteNodeName());
$this->persistenceManager->persistAll();
}
protected function getNodeType(ContentRepositoryId $contentRepositoryId, NodeTypeName $nodeTypeName): ?NodeType
{
return $this->contentRepositoryRegistry->get($contentRepositoryId)->getNodeTypeManager()->getNodeType($nodeTypeName);
}
private function createAffectedNodesKey(DocumentNodeInfo $nodeInfo, ContentRepositoryId $contentRepositoryId): string
{
return $contentRepositoryId->value . '#' . $nodeInfo->getNodeAggregateId()->value . '#' . $nodeInfo->getDimensionSpacePointHash();
}
protected function getNodeUriBuilder(SiteNodeName $siteNodeName, ContentRepositoryId $contentRepositoryId): NodeUriBuilder
{
// Generate a custom request when the current request was triggered from CLI
$baseUri = 'http://localhost';
$httpRequest = new ServerRequest('POST', $baseUri);
$httpRequest = (SiteDetectionResult::create($siteNodeName, $contentRepositoryId))->storeInRequest($httpRequest);
$actionRequest = ActionRequest::fromHttpRequest($httpRequest);
return $this->nodeUriBuilderFactory->forActionRequest($actionRequest);
}
/**
* Adds a redirect for given $oldUriPath to $newUriPath for all domains set up for $siteNode
*/
protected function createRedirectWithNewTarget(string $oldUriPath, string $newUriPath, SiteNodeName $siteNodeName): bool
{
if ($oldUriPath === $newUriPath) {
return false;
}
$hosts = $this->getHostnames($siteNodeName);
$statusCode = $this->defaultStatusCode[self::STATUS_CODE_TYPE_REDIRECT];
$this->redirectStorage->addRedirect($oldUriPath, $newUriPath, $statusCode, $hosts);
return true;
}
/**
* Adds a redirect for a removed target if enabled.
*/
protected function createRedirectForRemovedTarget(string $oldUriPath, SiteNodeName $siteNodeName): bool
{
// By default the redirect handling for removed nodes is activated.
// If it is deactivated in your settings you will be able to handle the redirects on your own.
// For example redirect to dedicated landing pages for deleted campaign NodeTypes
if ($this->enableRemovedNodeRedirect) {
$hosts = $this->getHostnames($siteNodeName);
$statusCode = $this->defaultStatusCode[self::STATUS_CODE_TYPE_GONE];
$this->redirectStorage->addRedirect($oldUriPath, '', $statusCode, $hosts);
return true;
}
return false;
}
/**
* Check if the current node type is restricted by NodeType
*/
protected function isRestrictedByNodeType(NodeType $nodeType): bool
{
if (!isset($this->restrictByNodeType)) {
return false;
}
foreach ($this->restrictByNodeType as $disabledNodeType => $status) {
if ($status !== true) {
continue;
}
if ($nodeType->isOfType($disabledNodeType)) {
$this->logger?->debug(vsprintf('Redirect skipped based on the current node type (%s) for a node because is of type %s', [
$nodeType->name->value,
$disabledNodeType
]));
return true;
}
}
return false;
}
/**
* Check if the old URI is restricted by old uri
*/
protected function isRestrictedByOldUri(string $oldUriPath): bool
{
if (!isset($this->restrictByOldUriPrefix)) {
return false;
}
foreach ($this->restrictByOldUriPrefix as $uriPrefix => $status) {
if ($status !== true) {
continue;
}
$uriPrefix = rtrim($uriPrefix, '/') . '/';
$oldUriPath = rtrim($oldUriPath, '/') . '/';
if (mb_strpos($oldUriPath, $uriPrefix) === 0) {
$this->logger?->debug(vsprintf('Redirect skipped based on the old URI (%s) because prefix matches %s', [
$oldUriPath,
$uriPrefix
]));
return true;
}
}
return false;
}
/**
* Collects all hostnames from the Domain entries attached to the current site.
* @return list<string>
*/
protected function getHostnames(SiteNodeName $siteNodeName): array
{
if (!isset($this->hostnamesRuntimeCache[$siteNodeName->value])) {
$site = $this->siteRepository->findOneByNodeName($siteNodeName);
$domains = [];
if ($site === null) {
return $domains;
}
foreach ($site->getActiveDomains() as $domain) {
/** @var Domain $domain */
$domains[] = $domain->getHostname();
}
$this->hostnamesRuntimeCache[$siteNodeName->value] = $domains;
}
return $this->hostnamesRuntimeCache[$siteNodeName->value];
}
}