-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
368 lines (311 loc) · 13.6 KB
/
index.php
File metadata and controls
368 lines (311 loc) · 13.6 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
<?php
/*
* retrobrowse version 0.11.2a - for Ubuntu 20.04 & Windows Environment
* (C)Tsubasa Kato - 2024/7/17 22:21PM JST - Created with help from ChatGPT (GPT-4o) & C:Amie
* Last updated on 2024/8/12 9:51AM
* Note: Not yet tested by Tsubasa Kato himself on Windowss environment
* Enable error reporting for debugging - Off in this.
* On Ubuntu environment, please make sure you use .htaccess file too.
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
const IMG_ROOT_DIR = '/var/www/html/retrobrowse';
#Change above to below if in Windows Environment (Haven't tested yet):
#const IMG_ROOT_DIR = 'C:\inetpub\wwwroot';
const CURL_DEBUG = false;
const REQUIRE_BASIC_AUTH = true;
const BASIC_AUTH_USER = 'myuser';
const BASIC_AUTH_PASSWORD = 'password-here-please';
function challengeAuthentication(): void {
if (REQUIRE_BASIC_AUTH) {
/* test for username/password */
if (!(
isset($_SERVER['PHP_AUTH_USER']) &&
$_SERVER['PHP_AUTH_USER'] == BASIC_AUTH_USER &&
isset($_SERVER['PHP_AUTH_PW']) &&
$_SERVER['PHP_AUTH_PW'] == BASIC_AUTH_PASSWORD
))
{
// Send headers to cause a browser to request
// username and password from user
header("WWW-Authenticate: Basic realm=\"retrobrowse\"");
header("HTTP/1.0 401 Unauthorized");
// Show failure text, which browsers usually
// show only after several failed attempts
print("Access denied.<br>\n");
exit(0);
}
}
}
function convertHTML5toIE3($htmlContent, $baseUrl, $domainRootPath, $basePath, $imageDir, $webImageDir) {
// Define the replacements for HTML5 elements and attributes
$replacements = [
// HTML5 tags to be replaced or removed
'header' => 'div',
'footer' => 'div',
'nav' => 'div',
'article' => 'div',
'section' => 'div',
'aside' => 'div',
'figure' => 'div',
'figcaption' => 'div',
'main' => 'div',
// HTML5 attributes to be removed
'autofocus' => '',
'required' => '',
'placeholder' => '',
];
// Regular expressions for finding HTML5 tags and attributes
$tagRegex = '/<\s*(\/?)\s*(header|footer|nav|article|section|aside|figure|figcaption|main)(\s|>)/i';
$attrRegex = '/\s*(autofocus|required|placeholder)="[^"]*"/i';
// Replace HTML5 tags
$htmlContent = preg_replace_callback($tagRegex, function($matches) use ($replacements) {
$replacement = $replacements[strtolower($matches[2])];
return "<{$matches[1]}$replacement{$matches[3]}";
}, $htmlContent);
// Remove HTML5 attributes
$htmlContent = preg_replace($attrRegex, '', $htmlContent);
// Simplify CSS and JavaScript (example: removing unsupported CSS properties)
$cssRegex = '/(display\s*:\s*flex\s*;|grid\s*;|flexbox\s*;)/i';
$htmlContent = preg_replace($cssRegex, 'display: block;', $htmlContent);
// Extract image tags and process images in parallel
$imgTags = [];
$htmlContent = preg_replace_callback('/<img[^>]+>/i', function($matches) use ($basePath, &$imgTags, $domainRootPath) {
$imgTag = $matches[0];
if (preg_match('/src=["\']([^"\']+)["\']/i', $imgTag, $srcMatches)) {
$src = $srcMatches[1];
if (substr($src, 0, 1) === '/') { // The input URI is a Root Relative URL e.g. '/images/logo.jpg'
$src = $domainRootPath . $src;
} else if (!preg_match('/^(http|https):\/\//i', $src)) { // The input URI is a Path Relative URL e.g. 'images/logo.jpg'
$src = rtrim($basePath, '/') . '/' . ltrim($src, '/'); // Make an Absolute URL on the parent domain e.g. 'https://www.domain.com/images/logo.jpg'
}
$imgTags[] = [$imgTag, $src, $srcMatches[1]];
}
return $imgTag;
}, $htmlContent);
// Process images in parallel using curl_multi
$convertedImages = processImagesInParallel($imgTags, $imageDir, $webImageDir);
// Update image tags with new src
foreach ($convertedImages as $originalSrc => $newSrc) {
$htmlContent = str_replace($originalSrc, $newSrc, $htmlContent);
}
// Rewrite URLs to redirect through the converter with absolute paths
$htmlContent = preg_replace_callback('/<a[^>]+href=["\']([^["\']+)["\'][^>]*>/i', function($matches) use ($baseUrl, $basePath, $domainRootPath) {
$url = $matches[1];
// Convert relative URLs to absolute URLs
if (substr($url, 0, 1) === '/') { // The input URI is a Root Relative URL e.g. '/myfolder/index.html'
$url = $domainRootPath . $url;
} else if (!preg_match('/^(http|https):\/\//i', $url)) { // The input URI is a Path Relative URL e.g. 'myfolder/index.html'
$url = rtrim($basePath, '/') . '/' . ltrim($url, '/'); // Make an Absolute URL on the parent domain e.g. 'https://www.domain.com/myfolder/index.html'
}
$newUrl = $baseUrl . '?url=' . $url;
return str_replace($matches[1], htmlspecialchars($newUrl), $matches[0]);
}, $htmlContent);
// Return the converted HTML content
return $htmlContent;
}
function processImagesInParallel($imgTags, $imageDir, $webImageDir) {
$mh = curl_multi_init();
$chArray = [];
$convertedImages = [];
foreach ($imgTags as $imgData) {
[$imgTag, $src, $originalSrc] = $imgData;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $src);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_multi_add_handle($mh, $ch);
if (CURL_DEBUG) {
$streamVerboseHandle = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $streamVerboseHandle);
}
$chArray[] = ['handle' => $ch, 'originalSrc' => $originalSrc];
}
$running = null;
do {
curl_multi_exec($mh, $running);
curl_multi_select($mh);
} while ($running > 0);
foreach ($chArray as $chData) {
$ch = $chData['handle'];
$originalSrc = $chData['originalSrc'];
$imageContent = curl_multi_getcontent($ch);
// Check for a 200 status code on the request, if it 404's everything breaks
if ((curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) AND ($imageContent !== false)) {
$newSrc = resizeAndConvertImageContent($imageContent, $imageDir, $webImageDir);
if ($newSrc !== false) {
$convertedImages[$originalSrc] = $newSrc;
}
}
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}
if (CURL_DEBUG) {
rewind($streamVerboseHandle);
$verboseLog = stream_get_contents($streamVerboseHandle);
echo "cUrl verbose information:\n",
"<pre>", htmlspecialchars($verboseLog), "</pre>\n";
}
curl_multi_close($mh);
return $convertedImages;
}
function resizeAndConvertImageContent($imageContent, $imageDir, $webImageDir) {
// Create an image resource from the content
$image = imagecreatefromstring($imageContent);
if ($image === false) {
return false;
}
$width = imagesx($image);
$height = imagesy($image);
// Resize if the width is over 640 pixels
if ($width > 640) {
$newWidth = floor($width * 0.2);
$newHeight = floor($height * 0.2);
} else {
$newWidth = $width;
$newHeight = $height;
}
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// Create a unique file name for the resized image, convert to .jpg
$uniqueFileName = uniqid('img_', true) . '.jpg';
$imageFileName = $imageDir . '/' . $uniqueFileName;
$webImagePath = $webImageDir . '/' . $uniqueFileName;
imagejpeg($resizedImage, $imageFileName, 90);
imagedestroy($image);
imagedestroy($resizedImage);
// Return the web path to the resized image
return $webImagePath;
}
// Function to check if a string is URL encoded
function isUrlEncoded($string) {
$string = str_replace('%20', '+', $string);
return urldecode($string) !== $string;
}
// Function to fetch HTML content using CURL
function fetchHtmlContentInParallel($urls) {
$mh = curl_multi_init();
$chArray = [];
$htmlContents = [];
foreach ($urls as $url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_multi_add_handle($mh, $ch);
if (CURL_DEBUG) {
$streamVerboseHandle = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $streamVerboseHandle);
}
$chArray[] = $ch;
}
$running = null;
do {
curl_multi_exec($mh, $running);
curl_multi_select($mh);
} while ($running > 0);
foreach ($chArray as $ch) {
$htmlContent = curl_multi_getcontent($ch);
$htmlContents[] = $htmlContent;
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}
if (CURL_DEBUG) {
rewind($streamVerboseHandle);
$verboseLog = stream_get_contents($streamVerboseHandle);
echo "cUrl verbose information:\n",
"<pre>", htmlspecialchars($verboseLog), "</pre>\n";
}
curl_multi_close($mh);
return $htmlContents;
}
function cleanImageFolders($rootDir) {
$d = dir($rootDir);
while (false !== ($entry = $d->read())) {
if (is_dir($entry) && ($entry != '.') && ($entry != '..')) {
if (substr($entry, 0, 4) === 'img_') { // Prefix matches img_
$datePart = substr($entry, 4); // get the date part of the folder name
$time = strtotime($datePart); // Convert it to EPOC
// If the folder date is not the current date, delete it
if ($time !== strtotime(date('Y-m-d',time()))) {
deleteDir($rootDir . '/' . $entry);
}
}
}
}
$d->close();
}
function deleteDir(string $dirPath): void {
if (! is_dir($dirPath)) {
throw new InvalidArgumentException("$dirPath must be a directory");
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
$dirPath .= '/';
}
$files = glob($dirPath . '*', GLOB_MARK);
foreach ($files as $file) {
if (is_dir($file)) {
deleteDir($file);
} else {
unlink($file);
}
}
rmdir($dirPath);
}
// Test for configured authenticated access and prompt if necessary
challengeAuthentication();
// Check if the URL parameter is set
if (isset($_GET['url'])) {
$urls = is_array($_GET['url']) ? $_GET['url'] : [$_GET['url']];
// Decode URLs if necessary
foreach ($urls as &$url) {
if (isUrlEncoded($url)) {
$url = urldecode($url);
}
}
$baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
// Clean images directory
cleanImageFolders(IMG_ROOT_DIR);
// Create image directory
$date = date('Y-m-d');
$imageDir = IMG_ROOT_DIR . '/img_' . $date;
$webImageDir = 'img_' . $date;
if (!file_exists($imageDir)) {
if (!mkdir($imageDir, 0777, true)) {
die('Failed to create image directory');
}
}
// Fetch the HTML content from the given URLs using CURL in parallel
$htmlContents = fetchHtmlContentInParallel($urls);
foreach ($htmlContents as $htmlContent) {
if ($htmlContent !== false) {
// Get the base path of the URL to handle relative links
$parsedUrl = parse_url($url);
$domainRootPath = $parsedUrl['scheme'] . '://' . $parsedUrl['host'];
$basePath = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . (isset($parsedUrl['path']) ? str_replace("\\", "/", dirname($parsedUrl['path'])) : '');
if (substr($basePath, -1) !== '/') {
$basePath = $basePath . '/';
}
// Convert the HTML content
$convertedContent = convertHTML5toIE3($htmlContent, $baseUrl, $domainRootPath, $basePath, $imageDir, $webImageDir);
// Display the converted content
header('Content-Type: text/html; charset=UTF-8');
echo $convertedContent;
} else {
echo "Failed to fetch content from the URL.<br>";
}
}
} else {
?>
<form name="retrobrowse" method="GET" action="index.php">
<input type="text" name="url" value="" maxlength="255" size="40" placeholder="https://..."> <input type="submit" value="Go">
<br><small><font face="arial">Enter a https:// web address to browse</font></small>
</form>
<?php
}
?>