-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathResultPlugin.php
More file actions
263 lines (218 loc) · 8.22 KB
/
ResultPlugin.php
File metadata and controls
263 lines (218 loc) · 8.22 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
<?php
/**
* Copyright © Magefan ([email protected]). All rights reserved.
* Please visit Magefan.com for license details (https://magefan.com/end-user-license-agreement).
*
* Glory to Ukraine! Glory to the heroes!
*/
namespace Magefan\RocketJavaScript\Model\Controller;
use Magento\Framework\App\Response\Http as ResponseHttp;
/**
* Plugin for processing relocation of javascript
*/
class ResultPlugin
{
const EXCLUDE_FLAG_PATTERN = 'data-rocketjavascript="false"';
/**
* Request
* @var \Magento\Framework\App\RequestInterface
*/
protected $request;
/**
* @var \Magefan\RocketJavaScript\Model\Config
*/
protected $config;
/**
* @var bool
*/
protected $allowedOnPage;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* ResultPlugin constructor.
* @param \Magento\Framework\App\RequestInterface $request
* @param \Magefan\RocketJavaScript\Model\Config $config
* @param \Magento\Store\Model\StoreManagerInterface|null $storeManager
*/
public function __construct(
\Magento\Framework\App\RequestInterface $request,
\Magefan\RocketJavaScript\Model\Config $config,
?\Magento\Store\Model\StoreManagerInterface $storeManager = null
) {
$this->request = $request;
$this->config = $config;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$this->storeManager = $storeManager ?: $objectManager->get(
\Magento\Store\Model\StoreManagerInterface::class
);
}
/**
* @param \Magento\Framework\Controller\ResultInterface $subject
* @param callable $proceed
* @param ResponseHttp $response
* @return \Magento\Framework\Controller\ResultInterface
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function aroundRenderResult(
\Magento\Framework\Controller\ResultInterface $subject,
\Closure $proceed,
ResponseHttp $response
) {
$result = $proceed($response);
if (PHP_SAPI === 'cli' || $this->request->isXmlHttpRequest() || !$this->isEnabled()) {
return $result;
}
if (!$this->isAllowedOnPage()) {
return $result;
}
$ignoredStrings = $this->config->getIgnoreJavaScript() ?: '';
$ignoredStrings = explode("\n", str_replace("\r", "\n", $ignoredStrings));
$ignoredStrings = array_map('trim', $ignoredStrings);
$ignoredStrings = array_filter($ignoredStrings);
$html = $response->getBody();
$scripts = [];
$positions = [];
$startTag = '<script';
$endTag = '</script>';
$lastPos = 0;
$start = 0;
// First pass: find all script tags and their positions
while (false !== ($start = stripos($html, $startTag, $start))) {
$end = stripos($html, $endTag, $start);
if (false === $end) {
break;
}
$scriptEnd = $end + strlen($endTag);
$script = substr($html, $start, $scriptEnd - $start);
// Check for exclusion flags or ignored content
if (false !== stripos($script, self::EXCLUDE_FLAG_PATTERN) ||
false !== stripos($script, 'application/ld+json')) {
$start = $scriptEnd; // Move pointer past this script
continue;
}
$isIgnored = false;
foreach ($ignoredStrings as $ignoredString) {
if (false !== stripos($script, $ignoredString)) {
$isIgnored = true;
break;
}
}
if ($isIgnored) {
$start = $scriptEnd;
continue;
}
// Store the script and its position
$scripts[] = $script;
$positions[] = ['start' => $start, 'end' => $scriptEnd];
$start = $scriptEnd; // Move pointer for the next search
}
// Second pass: reconstruct HTML and append scripts
if (empty($positions)) {
return $result; // No scripts found to move
}
$newHtml = '';
$lastPos = 0;
foreach ($positions as $pos) {
// Append the HTML content before the current script tag
$newHtml .= substr($html, $lastPos, $pos['start'] - $lastPos);
$lastPos = $pos['end'];
}
// Append the remaining HTML after the last script tag
$newHtml .= substr($html, $lastPos);
// Append the scripts before the closing </body> tag or at the end
$allScripts = implode(PHP_EOL, $scripts);
$bodyEndPos = stripos($newHtml, '</body>');
if ($bodyEndPos !== false) {
$newHtml = substr_replace($newHtml, $allScripts, $bodyEndPos, 0);
} else {
$newHtml .= $allScripts;
}
$response->setBody($newHtml);
return $result;
}
private function isEnabled()
{
$enabled = $this->config->isEnabled() && $this->config->isDeferredEnabled();
if ($enabled) {
/* check if Amasty AMP enabled */
if ($this->request->getParam('is_amp')) {
return false;
}
/* check if Plumrocket AMP enabled */
$isAmpRequest = $this->config->isAmpRequest();
if ($isAmpRequest) {
/* We know that using objectManager is not a not a good practice,
but if Plumrocket_AMP is not installed on your magento instance
you'll get error during di:compile */
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$isAmpRequest = $objectManager->get('\Plumrocket\Amp\Helper\Data')
->isAmpRequest();
}
$enabled = !$isAmpRequest;
}
return $enabled;
}
/**
* @return bool
*/
private function isAllowedOnPage()
{
if (null !== $this->allowedOnPage) {
return $this->allowedOnPage;
}
$this->allowedOnPage = false;
$spPages = $this->config->getDisallowedPages();
$spPages = explode("\n", str_replace("\r", "\n", $spPages));
foreach ($spPages as $key => $path) {
$spPages[$key] = trim($spPages[$key]);
if (empty($spPages[$key])) {
unset($spPages[$key]);
}
}
$baseUrl = trim($this->storeManager->getStore()->getBaseUrl(), '/');
$baseUrl = str_replace('/index.php', '', $baseUrl);
$currentUrl = $this->storeManager->getStore()->getCurrentUrl();
$currentUrl = explode('?', $currentUrl);
$currentUrl = trim($currentUrl[0], '/');
foreach (['index.php', '.php', '.html'] as $end) {
$el = mb_strlen($end);
$cl = mb_strlen($currentUrl);
if (mb_strrpos($currentUrl, $end) == $cl - $el) {
$currentUrl = mb_substr($currentUrl, 0, $cl - $el);
}
}
$currentUrl = str_replace('/index.php', '', $currentUrl);
$currentUrl = trim($currentUrl, '/');
foreach ($spPages as $key => $path) {
$path = trim($path, '/');
if (mb_strlen($path)) {
if ('*' == $path[0]) {
$subPath = trim($path, '*/');
if (mb_strlen($currentUrl) - mb_strlen($subPath) === mb_strrpos($currentUrl, $subPath)) {
$this->allowedOnPage = true;
break;
}
}
if ('*' == $path[mb_strlen($path) - 1]) {
if (0 === mb_strpos($currentUrl, $baseUrl . '/' . trim($path, '*/'))) {
$this->allowedOnPage = true;
break;
}
}
if ($currentUrl == $baseUrl . '/' . trim($path, '/')) {
$this->allowedOnPage = true;
break;
}
} else {
//homepage
if ($currentUrl == $baseUrl) {
$this->allowedOnPage = true;
break;
}
}
}
return $this->allowedOnPage = !$this->allowedOnPage;
}
}