-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert.php
More file actions
2251 lines (1964 loc) · 70.9 KB
/
convert.php
File metadata and controls
2251 lines (1964 loc) · 70.9 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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* RapidHTML2PNG - HTML to PNG Conversion API
*
* This script converts HTML blocks to PNG images with transparent background.
* It accepts POST requests with HTML content and CSS URL, caches results based
* on content hash, and auto-detects available rendering libraries.
*
* @author RapidHTML2PNG Development Team
* @version 1.0.0
*/
// Set error reporting for production
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/php_errors.log');
// Set JSON header for all responses
header('Content-Type: application/json; charset=utf-8');
// Allow CORS for development (restrict in production)
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-API-Key');
// Input size limits (in bytes)
define('MAX_HTML_BLOCK_SIZE', 1048576); // 1MB per HTML block
define('MAX_TOTAL_INPUT_SIZE', 5242880); // 5MB total input size
define('MAX_CSS_SIZE', 1048576); // 1MB for CSS content
// Abuse protection settings
define('REQUEST_MAX_RUNTIME_SECONDS', 300); // 5 minutes
define('REQUEST_LOCK_PATH', __DIR__ . '/logs/convert_runtime.lock');
define('API_KEY_ENV_NAME', 'RAPIDHTML2PNG_API_KEY');
// Enforce UTF-8 processing for all text operations.
if (function_exists('mb_internal_encoding')) {
mb_internal_encoding('UTF-8');
}
if (function_exists('mb_regex_encoding')) {
mb_regex_encoding('UTF-8');
}
$GLOBALS['request_guard'] = [
'started_at' => microtime(true),
'lock_handle' => null
];
// Handle OPTIONS preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit(json_encode(['status' => 'OK']));
}
/**
* Get library selection log file path
*
* @return string Path to log file
*/
function getLibraryLogPath() {
$logDir = __DIR__ . '/logs';
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
return $logDir . '/library_selection.log';
}
/**
* Log library selection for debugging
*
* @param string $selectedLibrary The library that was selected
* @param array $detectionResults Full detection results from all libraries
* @param string $reason Explanation of why this library was chosen
* @return void
*/
function logLibrarySelection($selectedLibrary, $detectionResults, $reason = '') {
$logPath = getLibraryLogPath();
$timestamp = date('Y-m-d H:i:s');
$logEntry = sprintf(
"[%s] Selected Library: %s\n",
$timestamp,
$selectedLibrary ? strtoupper($selectedLibrary) : 'NONE'
);
// Add reason
if (!empty($reason)) {
$logEntry .= sprintf(" Reason: %s\n", $reason);
}
// Add detection details for each library
if (isset($detectionResults['detected_libraries'])) {
$logEntry .= " Detection Results:\n";
foreach ($detectionResults['detected_libraries'] as $libName => $libInfo) {
$status = $libInfo['available'] ? 'AVAILABLE' : 'UNAVAILABLE';
$logEntry .= sprintf(" - %s: %s\n", strtoupper($libName), $status);
if ($libInfo['available']) {
// Add details for available libraries
if (isset($libInfo['version'])) {
$logEntry .= sprintf(" Version: %s\n", $libInfo['version']);
}
if (isset($libInfo['path'])) {
$logEntry .= sprintf(" Path: %s\n", $libInfo['path']);
}
if (isset($libInfo['info'])) {
$infoStr = json_encode($libInfo['info'], JSON_UNESCAPED_SLASHES);
$logEntry .= sprintf(" Info: %s\n", $infoStr);
}
} else {
// Add reason for unavailable libraries
if (isset($libInfo['reason'])) {
$logEntry .= sprintf(" Reason: %s\n", $libInfo['reason']);
}
if (isset($libInfo['error'])) {
$logEntry .= sprintf(" Error: %s\n", $libInfo['error']);
}
}
}
}
$logEntry .= "\n";
// Append to log file
file_put_contents($logPath, $logEntry, FILE_APPEND | LOCK_EX);
}
/**
* Send JSON error response
*
* @param int $code HTTP status code
* @param string $message Error message
* @param mixed $data Additional data
*/
function sendError($code, $message, $data = null) {
http_response_code($code);
$response = [
'success' => false,
'error' => $message,
'timestamp' => date('c')
];
if ($data !== null) {
$response['data'] = $data;
}
// Log the error for debugging
logError($code, $message, $data);
echo json_encode($response, JSON_PRETTY_PRINT);
if (!defined('TEST_MODE')) {
exit;
}
}
/**
* Log error to application error log
*
* Creates structured log entries with timestamp, HTTP status code,
* error message, and sanitized context data. Sensitive information
* is filtered out before logging.
*
* @param int $code HTTP status code
* @param string $message Error message
* @param mixed $data Additional data (will be sanitized)
*/
function logError($code, $message, $data = null) {
$logPath = __DIR__ . '/logs/application_errors.log';
$logDir = dirname($logPath);
// Create log directory if it doesn't exist
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
// Sanitize data to remove sensitive information
$safeData = sanitizeLogData($data);
// Build log entry
$timestamp = date('Y-m-d H:i:s');
$logEntry = "[$timestamp] HTTP $code - $message\n";
// Add request context
if (isset($_SERVER['REQUEST_METHOD'])) {
$logEntry .= " Method: {$_SERVER['REQUEST_METHOD']}\n";
}
if (isset($_SERVER['REQUEST_URI'])) {
// Sanitize URI to remove query string with potential sensitive data
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$logEntry .= " URI: $uri\n";
}
if (isset($_SERVER['REMOTE_ADDR'])) {
// Mask IP address for privacy (keep first 2 octets)
$ip = $_SERVER['REMOTE_ADDR'];
$maskedIp = preg_replace('/(\d+\.\d+)\.\d+\.\d+/', '$1.0.0.0', $ip);
$logEntry .= " Client IP: $maskedIp\n";
}
// Add sanitized context data
if ($safeData !== null) {
$logEntry .= " Context: " . json_encode($safeData, JSON_UNESCAPED_SLASHES) . "\n";
}
$logEntry .= "\n";
// Append to log file
file_put_contents($logPath, $logEntry, FILE_APPEND | LOCK_EX);
}
/**
* Sanitize data for logging
*
* Removes or masks sensitive information before logging.
* Filters out passwords, API keys, tokens, etc.
*
* @param mixed $data Data to sanitize
* @return mixed Sanitized data
*/
function sanitizeLogData($data) {
if ($data === null) {
return null;
}
if (!is_array($data)) {
// For non-array data, just return as string if it's safe
return (string)$data;
}
$sensitiveKeys = [
'password', 'passwd', 'secret', 'api_key', 'apikey', 'api-key',
'token', 'authorization', 'auth', 'session', 'cookie',
'private_key', 'privatekey', 'access_token', 'accesstoken'
];
$sanitized = [];
foreach ($data as $key => $value) {
$lowerKey = strtolower(str_replace(['-', '_', ' '], '', $key));
// Check if this key contains sensitive information
$isSensitive = false;
foreach ($sensitiveKeys as $sensitive) {
if (strpos($lowerKey, $sensitive) !== false) {
$isSensitive = true;
break;
}
}
if ($isSensitive) {
// Mask sensitive values
$sanitized[$key] = '[REDACTED]';
} elseif (is_array($value)) {
// Recursively sanitize nested arrays
$sanitized[$key] = sanitizeLogData($value);
} else {
// Keep non-sensitive values as-is
$sanitized[$key] = $value;
}
}
return $sanitized;
}
/**
* Send JSON success response
*
* @param mixed $data Response data
* @param string $message Success message
*/
function sendSuccess($data = null, $message = 'OK') {
http_response_code(200);
$response = [
'success' => true,
'message' => $message,
'timestamp' => date('c')
];
if ($data !== null) {
$response['data'] = $data;
}
echo json_encode($response, JSON_PRETTY_PRINT);
if (!defined('TEST_MODE')) {
exit;
}
}
/**
* Normalize string to UTF-8.
*
* @param mixed $text Input value
* @param string $fieldName Field name for error context
* @return mixed UTF-8 string or original non-string value
*/
function normalizeToUtf8($text, $fieldName = 'input') {
if (!is_string($text)) {
return $text;
}
// Remove UTF-8 BOM if present.
$text = preg_replace('/^\xEF\xBB\xBF/', '', $text);
if ($text === '') {
return $text;
}
if (function_exists('mb_check_encoding') && mb_check_encoding($text, 'UTF-8')) {
return $text;
}
if (!function_exists('mb_convert_encoding') || !function_exists('mb_check_encoding')) {
sendError(500, 'mbstring extension is required for UTF-8 normalization', [
'field' => $fieldName,
'required_extension' => 'mbstring'
]);
}
$sourceEncodings = ['UTF-8', 'Windows-1251', 'CP1251', 'KOI8-R', 'ISO-8859-1'];
foreach ($sourceEncodings as $sourceEncoding) {
$converted = @mb_convert_encoding($text, 'UTF-8', $sourceEncoding);
if ($converted !== false && mb_check_encoding($converted, 'UTF-8')) {
return $converted;
}
}
sendError(400, 'Invalid text encoding detected', [
'field' => $fieldName,
'expected_encoding' => 'UTF-8'
]);
}
/**
* Recursively normalize request payload to UTF-8.
*
* @param mixed $value Input payload
* @param string $path Current path for error context
* @return mixed Normalized payload
*/
function normalizePayloadUtf8($value, $path = 'input') {
if (is_array($value)) {
$normalized = [];
foreach ($value as $key => $item) {
$itemPath = $path . '[' . $key . ']';
$normalized[$key] = normalizePayloadUtf8($item, $itemPath);
}
return $normalized;
}
if (is_string($value)) {
return normalizeToUtf8($value, $path);
}
return $value;
}
/**
* Get raw request body with in-memory caching.
*
* @return string
*/
function getRawRequestBody() {
static $rawBody = null;
if ($rawBody === null) {
$rawBody = file_get_contents('php://input');
if ($rawBody === false) {
$rawBody = '';
}
}
return $rawBody;
}
/**
* Emit compact JSON response without error logging helper.
*
* @param int $code HTTP status code
* @param array $payload Response payload
* @return void
*/
function emitSimpleJson($code, $payload) {
http_response_code($code);
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
}
/**
* Get configured API key from environment.
*
* @return string|null
*/
function getConfiguredApiKey() {
$apiKey = getenv(API_KEY_ENV_NAME);
if ($apiKey === false || $apiKey === null) {
return null;
}
$apiKey = trim((string)$apiKey);
return $apiKey === '' ? null : $apiKey;
}
/**
* Extract API key from headers or request payload.
*
* @return string|null
*/
function extractApiKeyFromRequest() {
$headerCandidates = [
'HTTP_X_API_KEY',
'HTTP_X_APIKEY',
'REDIRECT_HTTP_X_API_KEY'
];
foreach ($headerCandidates as $headerName) {
if (!empty($_SERVER[$headerName])) {
return trim((string)$_SERVER[$headerName]);
}
}
if (isset($_POST['api_key'])) {
return trim((string)$_POST['api_key']);
}
if (isset($_GET['api_key'])) {
return trim((string)$_GET['api_key']);
}
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (strpos($contentType, 'application/json') !== false) {
$jsonFlags = defined('JSON_INVALID_UTF8_SUBSTITUTE') ? JSON_INVALID_UTF8_SUBSTITUTE : 0;
$payload = json_decode(getRawRequestBody(), true, 512, $jsonFlags);
if (is_array($payload) && isset($payload['api_key'])) {
return trim((string)$payload['api_key']);
}
}
return null;
}
/**
* Release single-instance lock handle.
*
* @return void
*/
function releaseRequestLock() {
$lockHandle = $GLOBALS['request_guard']['lock_handle'] ?? null;
if (!is_resource($lockHandle)) {
return;
}
@flock($lockHandle, LOCK_UN);
@fclose($lockHandle);
$GLOBALS['request_guard']['lock_handle'] = null;
}
/**
* Acquire non-blocking single-instance lock.
*
* @return array
*/
function acquireRequestLock() {
$lockDir = dirname(REQUEST_LOCK_PATH);
if (!is_dir($lockDir)) {
@mkdir($lockDir, 0755, true);
}
$lockHandle = @fopen(REQUEST_LOCK_PATH, 'c+');
if ($lockHandle === false) {
return [
'acquired' => false,
'reason' => 'lock_open_failed'
];
}
if (!@flock($lockHandle, LOCK_EX | LOCK_NB)) {
@fclose($lockHandle);
$runningMeta = json_decode((string)@file_get_contents(REQUEST_LOCK_PATH), true);
if (!is_array($runningMeta)) {
$runningMeta = [];
}
return [
'acquired' => false,
'reason' => 'already_running',
'running_meta' => $runningMeta
];
}
$lockMeta = [
'started_at' => time(),
'pid' => function_exists('getmypid') ? getmypid() : null,
'uri' => $_SERVER['REQUEST_URI'] ?? '/convert.php'
];
ftruncate($lockHandle, 0);
rewind($lockHandle);
fwrite($lockHandle, json_encode($lockMeta, JSON_UNESCAPED_SLASHES));
fflush($lockHandle);
$GLOBALS['request_guard']['lock_handle'] = $lockHandle;
register_shutdown_function('releaseRequestLock');
return [
'acquired' => true,
'meta' => $lockMeta
];
}
/**
* Abort request if runtime exceeded configured max duration.
*
* @param string $stage Runtime stage marker
* @return void
*/
function enforceRuntimeLimit($stage = 'runtime') {
$startedAt = $GLOBALS['request_guard']['started_at'] ?? microtime(true);
$elapsed = microtime(true) - $startedAt;
if ($elapsed <= REQUEST_MAX_RUNTIME_SECONDS) {
return;
}
releaseRequestLock();
emitSimpleJson(408, [
'success' => false,
'error' => 'Request timed out',
'stage' => $stage,
'max_runtime_seconds' => REQUEST_MAX_RUNTIME_SECONDS,
'elapsed_seconds' => (int)round($elapsed)
]);
exit;
}
// Only allow POST requests for actual conversion (unless in test mode)
if (!defined('TEST_MODE') && $_SERVER['REQUEST_METHOD'] !== 'POST') {
sendError(405, 'Method Not Allowed', [
'allowed_methods' => ['POST'],
'endpoint' => '/convert.php',
'documentation' => 'This endpoint accepts POST requests with html_blocks and optional css_url/render_engine for conversion to PNG'
]);
}
// Configure script hard timeout for long-running executions.
if (!defined('TEST_MODE') && function_exists('set_time_limit')) {
@set_time_limit(REQUEST_MAX_RUNTIME_SECONDS);
}
// Require API key without invoking structured error logger.
if (!defined('TEST_MODE')) {
$configuredApiKey = getConfiguredApiKey();
if ($configuredApiKey === null) {
emitSimpleJson(503, [
'success' => false,
'error' => 'API key is not configured',
'config_env' => API_KEY_ENV_NAME
]);
return;
}
$providedApiKey = extractApiKeyFromRequest();
if ($providedApiKey === null || $providedApiKey === '') {
emitSimpleJson(401, [
'success' => false,
'error' => 'API key is required'
]);
return;
}
if (!hash_equals($configuredApiKey, $providedApiKey)) {
emitSimpleJson(403, [
'success' => false,
'error' => 'Invalid API key'
]);
return;
}
$lockResult = acquireRequestLock();
if (!$lockResult['acquired']) {
if (($lockResult['reason'] ?? '') === 'already_running') {
$runningStartedAt = (int)($lockResult['running_meta']['started_at'] ?? 0);
$runningFor = $runningStartedAt > 0 ? max(0, time() - $runningStartedAt) : null;
emitSimpleJson(429, [
'success' => false,
'error' => 'Work already in progress, please wait',
'running_for_seconds' => $runningFor,
'max_runtime_seconds' => REQUEST_MAX_RUNTIME_SECONDS,
'running_over_timeout' => $runningFor !== null && $runningFor > REQUEST_MAX_RUNTIME_SECONDS
]);
return;
}
emitSimpleJson(503, [
'success' => false,
'error' => 'Failed to acquire execution lock'
]);
return;
}
}
enforceRuntimeLimit('startup');
/**
* Parse input data from POST request
* Supports both multipart/form-data and JSON formats
*
* @return array Parsed input data
*/
function parseInput() {
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
// Handle JSON input
if (strpos($contentType, 'application/json') !== false) {
$json = getRawRequestBody();
$jsonFlags = defined('JSON_INVALID_UTF8_SUBSTITUTE') ? JSON_INVALID_UTF8_SUBSTITUTE : 0;
$data = json_decode($json, true, 512, $jsonFlags);
if (json_last_error() !== JSON_ERROR_NONE) {
sendError(400, 'Invalid JSON', [
'json_error' => json_last_error_msg()
]);
}
return normalizePayloadUtf8($data ?? []);
}
// Handle multipart/form-data or form-urlencoded
if (strpos($contentType, 'multipart/form-data') !== false ||
strpos($contentType, 'application/x-www-form-urlencoded') !== false) {
return normalizePayloadUtf8($_POST);
}
// Default to $_POST if no content type specified
return normalizePayloadUtf8($_POST);
}
/**
* Check total input size from request body
*
* @return void Sends error if size exceeds limit
*/
function checkTotalInputSize() {
$contentLength = $_SERVER['CONTENT_LENGTH'] ?? 0;
if ($contentLength > MAX_TOTAL_INPUT_SIZE) {
sendError(413, 'Request body too large', [
'content_length' => $contentLength,
'max_allowed' => MAX_TOTAL_INPUT_SIZE,
'max_allowed_mb' => round(MAX_TOTAL_INPUT_SIZE / 1048576, 2),
'exceeded_by' => $contentLength - MAX_TOTAL_INPUT_SIZE
]);
}
}
/**
* Validate HTML blocks input
*
* @param mixed $htmlBlocks The html_blocks parameter to validate
* @return array Validated array of HTML blocks
*/
function validateHtmlBlocks($htmlBlocks) {
// Check if parameter exists
if ($htmlBlocks === null || $htmlBlocks === '') {
sendError(400, 'Missing required parameter: html_blocks', [
'required_parameters' => ['html_blocks'],
'optional_parameters' => ['css_url', 'render_engine']
]);
}
// Ensure it's an array
if (!is_array($htmlBlocks)) {
// Try to convert single string to array
if (is_string($htmlBlocks)) {
$htmlBlocks = [$htmlBlocks];
} else {
sendError(400, 'html_blocks must be an array', [
'received_type' => gettype($htmlBlocks),
'expected_type' => 'array'
]);
}
}
// Check if array is empty
if (empty($htmlBlocks)) {
sendError(400, 'html_blocks array cannot be empty', [
'provided_count' => 0,
'minimum_count' => 1
]);
}
// Validate each block is a non-empty string and sanitize
foreach ($htmlBlocks as $index => $block) {
if (!is_string($block)) {
sendError(400, "html_blocks[$index] must be a string", [
'invalid_index' => $index,
'received_type' => gettype($block)
]);
}
$block = normalizeToUtf8($block, "html_blocks[$index]");
// Check individual block size
$blockSize = strlen($block);
if ($blockSize > MAX_HTML_BLOCK_SIZE) {
sendError(413, "html_blocks[$index] exceeds maximum size", [
'invalid_index' => $index,
'block_size' => $blockSize,
'max_allowed_size' => MAX_HTML_BLOCK_SIZE,
'max_allowed_mb' => round(MAX_HTML_BLOCK_SIZE / 1048576, 2),
'exceeded_by' => $blockSize - MAX_HTML_BLOCK_SIZE
]);
}
if (trim($block) === '') {
sendError(400, "html_blocks[$index] cannot be empty", [
'invalid_index' => $index
]);
}
// Sanitize HTML to prevent XSS attacks
$htmlBlocks[$index] = sanitizeHtmlInput($block);
// Check if sanitization removed all content
if (trim($htmlBlocks[$index]) === '') {
sendError(400, "html_blocks[$index] contained only dangerous/invalid HTML", [
'invalid_index' => $index,
'reason' => 'Sanitization removed all content'
]);
}
}
return $htmlBlocks;
}
/**
* Validate CSS URL parameter (optional)
*
* @param string $cssUrl The CSS URL to validate
* @return string|null Validated CSS URL or null if not provided
*/
function validateCssUrl($cssUrl) {
if ($cssUrl === null || $cssUrl === '') {
return null;
}
if (!is_string($cssUrl)) {
sendError(400, 'css_url must be a string', [
'received_type' => gettype($cssUrl)
]);
}
$cssUrl = normalizeToUtf8($cssUrl, 'css_url');
// Basic URL validation
if (!filter_var($cssUrl, FILTER_VALIDATE_URL)) {
sendError(400, 'css_url must be a valid URL', [
'provided_url' => $cssUrl
]);
}
// Ensure it's http or https
$scheme = parse_url($cssUrl, PHP_URL_SCHEME);
if (!in_array($scheme, ['http', 'https'])) {
sendError(400, 'css_url must use http or https scheme', [
'provided_scheme' => $scheme
]);
}
return $cssUrl;
}
/**
* Validate requested render engine (optional).
*
* Supported aliases:
* - imagick => imagemagick
* - auto => null (default fallback mode)
*
* @param mixed $renderEngine Requested engine value
* @return string|null Canonical engine name or null for auto mode
*/
function validateRenderEngine($renderEngine) {
if ($renderEngine === null || $renderEngine === '') {
return null;
}
if (!is_string($renderEngine)) {
sendError(400, 'render_engine must be a string', [
'received_type' => gettype($renderEngine),
'allowed_values' => ['auto', 'wkhtmltoimage', 'gd', 'imagick', 'imagemagick']
]);
}
$renderEngine = strtolower(trim(normalizeToUtf8($renderEngine, 'render_engine')));
$aliases = [
'auto' => null,
'imagick' => 'imagemagick',
'imagemagick' => 'imagemagick',
'wkhtmltoimage' => 'wkhtmltoimage',
'gd' => 'gd'
];
if (!array_key_exists($renderEngine, $aliases)) {
sendError(400, 'Invalid render_engine value', [
'provided_value' => $renderEngine,
'allowed_values' => ['auto', 'wkhtmltoimage', 'gd', 'imagick', 'imagemagick']
]);
}
return $aliases[$renderEngine];
}
/**
* Sanitize HTML content to prevent XSS attacks
*
* This function removes potentially dangerous HTML elements and attributes
* that could be used for XSS attacks while preserving safe HTML structure
* needed for rendering.
*
* Security measures:
* - Removes <script> tags and their content
* - Removes event handler attributes (onclick, onload, etc.)
* - Removes javascript: URLs
* - Removes iframe, object, embed, form, input tags
* - Removes data attributes that could contain malicious code
* - Removes style attributes with javascript: or expression()
*
* @param string $html The HTML content to sanitize
* @return string Sanitized HTML content
*/
function sanitizeHtmlInput($html) {
// Remove script tags and their content
$html = preg_replace('#<script\b[^>]*>(.*?)</script>#is', '', $html);
// Remove iframe tags (often used for clickjacking)
$html = preg_replace('#<iframe\b[^>]*>.*?</iframe>#is', '', $html);
// Remove object tags
$html = preg_replace('#<object\b[^>]*>.*?</object>#is', '', $html);
// Remove embed tags
$html = preg_replace('#<embed\b[^>]*>#i', '', $html);
// Remove form and input tags
$html = preg_replace('#<form\b[^>]*>.*?</form>#is', '', $html);
$html = preg_replace('#<input\b[^>]*>#i', '', $html);
$html = preg_replace('#<button\b[^>]*>.*?</button>#is', '', $html);
// Remove dangerous event handler attributes from all tags
// This covers: onclick, onload, onerror, onmouseover, onmouseout, etc.
$dangerousEvents = [
'onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate',
'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus',
'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate',
'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu',
'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged',
'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend',
'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop',
'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus',
'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup',
'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter',
'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup',
'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste',
'onpropertychange', 'onreadystatechange', 'onreset', 'onresize',
'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete',
'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart',
'onstart', 'onstop', 'onsubmit', 'onunload'
];
foreach ($dangerousEvents as $event) {
$html = preg_replace('#\s' . $event . '\s*=\s*(["\']).*?\1#is', '', $html);
$html = preg_replace('#\s' . $event . '\s*=\s*[^\s>]*#is', '', $html);
}
// Remove javascript: and vbscript: protocols from href and src attributes
$html = preg_replace('#\s(href|src|lowsrc|dynsrc|background)\s*=\s*(["\'])?\s*javascript:[^"\'>]*\2?#is', '', $html);
$html = preg_replace('#\s(href|src|lowsrc|dynsrc|background)\s*=\s*(["\'])?\s*vbscript:[^"\'>]*\2?#is', '', $html);
$html = preg_replace('#\s(href|src|lowsrc|dynsrc|background)\s*=\s*(["\'])?\s*data:[^"\'>]*\2?#is', '', $html);
// Remove style attributes containing javascript: or expression()
$html = preg_replace('#\sstyle\s*=\s*(["\'])(.*?(?:javascript:|expression\().*?)\1#is', '', $html);
// Remove data-* attributes that could contain malicious code (be conservative)
$html = preg_replace('#\sdata-[a-z-]+=\s*(["\']).*?\1#is', '', $html);
// Remove any remaining potential HTML comments with malicious content
$html = preg_replace('#<!--.*?-->#s', '', $html);
return normalizeToUtf8(trim($html), 'html_sanitized');
}
/**
* Get CSS cache directory path
*
* @return string Cache directory path
*/
function getCssCacheDir() {
$cacheDir = __DIR__ . '/assets/media/rapidhtml2png/css_cache';
if (!is_dir($cacheDir)) {
if (!mkdir($cacheDir, 0755, true)) {
sendError(500, 'Failed to create CSS cache directory', [
'cache_dir' => $cacheDir
]);
}
}
return $cacheDir;
}
/**
* Get cached CSS file path for a URL
*
* @param string $cssUrl The CSS URL
* @return string Path to cached CSS file
*/
function getCssCachePath($cssUrl) {
$cacheDir = getCssCacheDir();
$cacheKey = md5($cssUrl);
return $cacheDir . '/' . $cacheKey . '.css';
}
/**
* Get CSS metadata file path for a URL
*
* @param string $cssUrl The CSS URL
* @return string Path to metadata file
*/
function getCssMetadataPath($cssUrl) {
$cacheDir = getCssCacheDir();
$cacheKey = md5($cssUrl);
return $cacheDir . '/' . $cacheKey . '.meta.json';
}
/**
* Save CSS metadata
*
* @param string $cssUrl The CSS URL
* @param string $etag Optional ETag from HTTP response
* @param int $lastModified Optional Last-Modified timestamp from HTTP response
* @return void
*/
function saveCssMetadata($cssUrl, $etag = null, $lastModified = null) {
$metadataPath = getCssMetadataPath($cssUrl);
$metadata = [
'url' => $cssUrl,
'cached_at' => time(),
'etag' => $etag,
'last_modified' => $lastModified
];
file_put_contents($metadataPath, json_encode($metadata, JSON_PRETTY_PRINT));
}
/**
* Load CSS metadata
*
* @param string $cssUrl The CSS URL
* @return array|null Metadata or null if not found
*/
function loadCssMetadata($cssUrl) {
$metadataPath = getCssMetadataPath($cssUrl);
if (!file_exists($metadataPath)) {
return null;
}
$content = file_get_contents($metadataPath);
return json_decode($content, true);
}
/**
* Check if cached CSS is still valid using conditional HTTP request
*
* This function makes a conditional HTTP request (HEAD or GET with If-None-Match/If-Modified-Since)
* to check if the cached CSS is still fresh without downloading the entire file.
*
* @param string $cssUrl The CSS URL
* @return array Result with 'valid' bool and 'should_refresh' bool
*/
function checkCssCacheFreshness($cssUrl) {
$cachePath = getCssCachePath($cssUrl);
// Check if cached file exists
if (!file_exists($cachePath)) {
return ['valid' => false, 'should_refresh' => true];
}
// Load metadata to get ETag and Last-Modified
$metadata = loadCssMetadata($cssUrl);
if ($metadata === null) {
// No metadata exists, cache is invalid
return ['valid' => false, 'should_refresh' => true];
}
// Check if cURL is available
if (!extension_loaded('curl')) {
// Can't check, use TTL fallback
$cacheFilemtime = filemtime($cachePath);
$cacheAge = time() - $cacheFilemtime;
$cacheTTL = 3600; // 1 hour
return [
'valid' => $cacheAge <= $cacheTTL,
'should_refresh' => $cacheAge > $cacheTTL,
'method' => 'ttl_fallback'
];
}
// Make conditional HTTP request to check if CSS has changed
$ch = curl_init($cssUrl);
if ($ch === false) {
// cURL init failed, use TTL fallback
$cacheFilemtime = filemtime($cachePath);