-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudit.php
More file actions
1581 lines (1370 loc) · 56.3 KB
/
Copy pathaudit.php
File metadata and controls
1581 lines (1370 loc) · 56.3 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
/**
* GEO Audit Tool - Backend PHP
* Version améliorée avec contournement renforcé des protections
* + Support services de scraping tiers (ScrapingBee, ScraperAPI, Browserless)
*/
define('GEO_AUDIT_VERSION', '1.2.0');
define('GEO_AUDIT_USER_AGENT', 'GEO-Audit-Bot/' . GEO_AUDIT_VERSION . ' (+https://audit.ticoet.me; contact@ticoet.fr)');
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/audit_errors.log');
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
$SCRAPING_CONFIG = loadScrapingConfig();
$input = json_decode(file_get_contents('php://input'), true);
$mode = $input['mode'] ?? 'url';
$pageType = $input['pageType'] ?? 'article';
if ($mode === 'html') {
$html = $input['html'] ?? '';
$url = $input['url'] ?? 'HTML copié-collé';
if (empty($html) || strlen($html) < 100) {
http_response_code(400);
echo json_encode(['error' => 'HTML invalide ou trop court']);
exit;
}
} else {
$url = filter_var($input['url'] ?? '', FILTER_VALIDATE_URL);
$useProxy = $input['useProxy'] ?? false;
$useScrapingService = $input['useScrapingService'] ?? false;
$identifyAsBot = $input['identifyAsBot'] ?? false;
if (!$url) {
http_response_code(400);
echo json_encode(['error' => 'URL invalide ou manquante']);
exit;
}
if (!function_exists('curl_init')) {
http_response_code(500);
echo json_encode(['error' => 'Extension CURL non disponible sur le serveur']);
exit;
}
try {
$html = fetchHTML($url, $useProxy, $useScrapingService, $identifyAsBot);
if (!$html) {
$hasScrapingService = !empty($SCRAPING_CONFIG['service']);
http_response_code(500);
echo json_encode([
'error' => 'Impossible de récupérer la page',
'details' => 'La page est protégée par Cloudflare ou un système anti-bot. ' .
'Toutes les méthodes de contournement ont échoué. ' .
($hasScrapingService
? 'Le service de scraping configuré n\'a pas pu contourner la protection.'
: 'Conseil : configurez un service de scraping (ScrapingBee, ScraperAPI) dans scraping-config.json pour de meilleurs résultats.') . ' ' .
'Sinon, utilisez le mode "Analyser du HTML" en copiant le code source depuis votre navigateur.',
'suggestion' => 'html_mode',
'scraping_configured' => $hasScrapingService
]);
exit;
}
} catch (Exception $e) {
error_log("Erreur fetch: " . $e->getMessage());
http_response_code(500);
echo json_encode([
'error' => 'Erreur lors de la récupération',
'details' => $e->getMessage()
]);
exit;
}
}
try {
$audit = analyzeHTML($html, $url, $pageType);
echo json_encode($audit, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
error_log("Erreur audit GEO: " . $e->getMessage());
http_response_code(500);
echo json_encode([
'error' => 'Erreur lors de l\'analyse',
'details' => $e->getMessage()
]);
}
/**
* Charge la configuration des services de scraping
*/
function loadScrapingConfig() {
$configFile = __DIR__ . '/scraping-config.json';
if (file_exists($configFile)) {
$config = json_decode(file_get_contents($configFile), true);
if ($config) {
return $config;
}
}
return [
'service' => '',
'api_key' => '',
'options' => []
];
}
/**
* Récupère le HTML d'une URL avec stratégies multiples
*/
function fetchHTML($url, $useProxy = false, $useScrapingService = false, $identifyAsBot = false) {
global $SCRAPING_CONFIG;
error_log("fetchHTML: Début - URL: $url, useProxy: " . ($useProxy ? 'true' : 'false') . ", useScrapingService: " . ($useScrapingService ? 'true' : 'false') . ", identifyAsBot: " . ($identifyAsBot ? 'true' : 'false'));
error_log("fetchHTML: Config service: " . ($SCRAPING_CONFIG['service'] ?? 'non défini') . ", API key présente: " . (!empty($SCRAPING_CONFIG['api_key']) ? 'oui' : 'non'));
// Si identification comme bot demandée, utiliser directement le User-Agent dédié
if ($identifyAsBot) {
$html = fetchHTMLAsBot($url);
if ($html && isValidHTML($html)) {
error_log("Succès avec User-Agent bot identifiable: " . GEO_AUDIT_USER_AGENT);
return $html;
}
error_log("fetchHTML: Échec avec User-Agent bot, tentative avec stratégies standard...");
}
// Stratégie 0: Service de scraping tiers (si demandé et configuré)
if ($useScrapingService && !empty($SCRAPING_CONFIG['service']) && !empty($SCRAPING_CONFIG['api_key'])) {
error_log("fetchHTML: Tentative avec service de scraping: " . $SCRAPING_CONFIG['service']);
$html = fetchWithScrapingService($url, $SCRAPING_CONFIG);
if ($html && isValidHTML($html)) {
error_log("Succès avec service de scraping: " . $SCRAPING_CONFIG['service']);
return $html;
}
error_log("fetchHTML: Échec du service de scraping, isValidHTML: " . ($html ? (isValidHTML($html) ? 'true' : 'false') : 'null'));
}
// Stratégie 1: Mode compatible avancé (si demandé)
if ($useProxy) {
$html = fetchWithAdvancedBypass($url);
if ($html && isValidHTML($html)) return $html;
}
// Stratégie 2: Headers réalistes (Chrome moderne)
$html = fetchHTMLWithRealHeaders($url);
if ($html && isValidHTML($html)) return $html;
// Stratégie 3: cURL basique avec User-Agent bot
$html = fetchHTMLBasic($url);
if ($html && isValidHTML($html)) return $html;
// Stratégie 4: file_get_contents avec contexte (dernier recours)
$html = fetchWithFileGetContents($url);
if ($html && isValidHTML($html)) return $html;
// Stratégie 5: Service de scraping en dernier recours (si configuré mais pas demandé)
if (!$useScrapingService && !empty($SCRAPING_CONFIG['service']) && !empty($SCRAPING_CONFIG['api_key'])) {
error_log("Tentative de fallback avec service de scraping...");
$html = fetchWithScrapingService($url, $SCRAPING_CONFIG);
if ($html && isValidHTML($html)) {
error_log("Succès fallback avec service de scraping: " . $SCRAPING_CONFIG['service']);
return $html;
}
}
return false;
}
/**
* Récupère le HTML via un service de scraping tiers
*/
function fetchWithScrapingService($url, $config) {
$service = strtolower($config['service']);
$apiKey = $config['api_key'];
$options = $config['options'] ?? [];
switch ($service) {
case 'scrapingbee':
return fetchWithScrapingBee($url, $apiKey, $options);
case 'scraperapi':
return fetchWithScraperAPI($url, $apiKey, $options);
case 'browserless':
return fetchWithBrowserless($url, $apiKey, $options);
case 'zenrows':
return fetchWithZenRows($url, $apiKey, $options);
default:
error_log("Service de scraping inconnu: $service");
return false;
}
}
/**
* ScrapingBee - https://www.scrapingbee.com/
* Excellent pour contourner Cloudflare avec JavaScript rendering
*/
function fetchWithScrapingBee($url, $apiKey, $options = []) {
error_log("ScrapingBee: Début de la requête pour URL: $url");
error_log("ScrapingBee: API Key (5 premiers chars): " . substr($apiKey, 0, 5) . "...");
$params = [
'api_key' => $apiKey,
'url' => $url,
'render_js' => $options['render_js'] ?? 'true',
'premium_proxy' => $options['premium_proxy'] ?? 'true',
'country_code' => $options['country_code'] ?? 'fr',
'block_ads' => 'true',
'block_resources' => 'false',
'wait' => $options['wait'] ?? '5000',
];
$apiUrl = 'https://app.scrapingbee.com/api/v1/?' . http_build_query($params);
error_log("ScrapingBee: URL API construite (longueur: " . strlen($apiUrl) . ")");
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
]);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
$totalTime = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
curl_close($ch);
error_log("ScrapingBee: Réponse reçue - HTTP $httpCode, Taille: " . strlen($html) . " chars, Temps: {$totalTime}s");
if ($error) {
error_log("ScrapingBee cURL Error: $error");
return false;
}
if ($httpCode === 200 && strlen($html) > 500) {
error_log("ScrapingBee: Succès pour URL: $url");
return $html;
}
error_log("ScrapingBee: Échec HTTP $httpCode pour URL: $url - Réponse: " . substr($html, 0, 500));
return false;
}
/**
* ScraperAPI - https://www.scraperapi.com/
* Bon rapport qualité/prix avec rotation d'IP automatique
*/
function fetchWithScraperAPI($url, $apiKey, $options = []) {
$params = [
'api_key' => $apiKey,
'url' => $url,
'render' => $options['render'] ?? 'true',
'country_code' => $options['country_code'] ?? 'fr',
'premium' => $options['premium'] ?? 'true',
];
$apiUrl = 'https://api.scraperapi.com/?' . http_build_query($params);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
]);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
error_log("ScraperAPI Error: $error");
return false;
}
if ($httpCode === 200 && strlen($html) > 500) {
error_log("ScraperAPI: Succès pour URL: $url");
return $html;
}
error_log("ScraperAPI: Échec HTTP $httpCode pour URL: $url");
return false;
}
/**
* Browserless - https://www.browserless.io/
* Headless Chrome complet dans le cloud
*/
function fetchWithBrowserless($url, $apiKey, $options = []) {
$apiUrl = 'https://chrome.browserless.io/content?token=' . $apiKey;
$payload = json_encode([
'url' => $url,
'waitFor' => $options['wait_for'] ?? 3000,
'gotoOptions' => [
'waitUntil' => 'networkidle2',
'timeout' => 60000
],
'userAgent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
]);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Cache-Control: no-cache'
],
CURLOPT_TIMEOUT => 90,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
]);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
error_log("Browserless Error: $error");
return false;
}
if ($httpCode === 200 && strlen($html) > 500) {
error_log("Browserless: Succès pour URL: $url");
return $html;
}
error_log("Browserless: Échec HTTP $httpCode pour URL: $url");
return false;
}
/**
* ZenRows - https://www.zenrows.com/
* Spécialisé anti-bot avec AI
*/
function fetchWithZenRows($url, $apiKey, $options = []) {
$params = [
'apikey' => $apiKey,
'url' => $url,
'js_render' => $options['js_render'] ?? 'true',
'antibot' => $options['antibot'] ?? 'true',
'premium_proxy' => $options['premium_proxy'] ?? 'true',
];
$apiUrl = 'https://api.zenrows.com/v1/?' . http_build_query($params);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 90,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
]);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
error_log("ZenRows Error: $error");
return false;
}
if ($httpCode === 200 && strlen($html) > 500) {
error_log("ZenRows: Succès pour URL: $url");
return $html;
}
error_log("ZenRows: Échec HTTP $httpCode pour URL: $url");
return false;
}
/**
* Vérifie si le HTML récupéré est valide (pas une page de challenge)
*/
function isValidHTML($html) {
if (empty($html) || strlen($html) < 500) {
return false;
}
$invalidPatterns = [
'Checking your browser',
'Just a moment...',
'Please wait while we verify',
'cf-browser-verification',
'challenge-platform',
'_cf_chl_opt',
'Cloudflare Ray ID',
'Enable JavaScript and cookies',
'Attention Required!',
'DDoS protection by',
'Incapsula incident ID',
'Access denied',
'Bot verification',
'please complete the security check'
];
foreach ($invalidPatterns as $pattern) {
if (stripos($html, $pattern) !== false) {
error_log("HTML invalide détecté: contient '$pattern'");
return false;
}
}
if (!preg_match('/<(html|head|body|div|article|main|section)/i', $html)) {
error_log("HTML invalide: pas de structure HTML standard");
return false;
}
return true;
}
/**
* Mode contournement avancé (multiples techniques)
*/
function fetchWithAdvancedBypass($url) {
$attempts = [
'fetchWithGoogleCacheProxy',
'fetchWithWebArchive',
'fetchAsGoogleBot',
'fetchWithCloudflareBypass',
'fetchWithRotatingUserAgents',
'fetchWithDelayAndRetry',
'fetchWithMobileUA'
];
foreach ($attempts as $method) {
if (function_exists($method)) {
$html = $method($url);
if ($html && isValidHTML($html)) {
error_log("Succès avec méthode: $method pour URL: $url");
return $html;
}
}
}
return false;
}
/**
* Tentative via Google Cache (contourne souvent les protections)
*/
function fetchWithGoogleCacheProxy($url) {
$cacheUrl = 'https://webcache.googleusercontent.com/search?q=cache:' . urlencode($url);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $cacheUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
CURLOPT_HTTPHEADER => [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: fr-FR,fr;q=0.9,en;q=0.8',
],
CURLOPT_ENCODING => '',
]);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200 && strlen($html) > 1000) {
$html = preg_replace('/<div[^>]*id="google-cache-hdr"[^>]*>.*?<\/div>/s', '', $html);
error_log("Succès via Google Cache pour URL: $url");
return $html;
}
return false;
}
/**
* Tentative via Web Archive (Wayback Machine)
*/
function fetchWithWebArchive($url) {
$archiveApiUrl = 'https://archive.org/wayback/available?url=' . urlencode($url);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $archiveApiUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_SSL_VERIFYPEER => false,
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if (isset($data['archived_snapshots']['closest']['url'])) {
$archiveUrl = $data['archived_snapshots']['closest']['url'];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $archiveUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
CURLOPT_ENCODING => '',
]);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200 && strlen($html) > 1000) {
error_log("Succès via Web Archive pour URL: $url");
return $html;
}
}
return false;
}
/**
* Se faire passer pour Googlebot (souvent whitelist)
*/
function fetchAsGoogleBot($url) {
$googleBotUAs = [
'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'Googlebot/2.1 (+http://www.google.com/bot.html)',
];
foreach ($googleBotUAs as $ua) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERAGENT => $ua,
CURLOPT_HTTPHEADER => [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.5',
'From: googlebot(at)googlebot.com',
],
CURLOPT_ENCODING => '',
]);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200 && strlen($html) > 1000) {
error_log("Succès avec Googlebot UA pour URL: $url");
return $html;
}
}
return false;
}
/**
* User-Agent mobile (parfois moins protégé)
*/
function fetchWithMobileUA($url) {
$mobileUAs = [
'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1',
'Mozilla/5.0 (Linux; Android 14; SM-S928B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36',
'Mozilla/5.0 (Linux; Android 14; Pixel 8 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36',
];
$randomUA = $mobileUAs[array_rand($mobileUAs)];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 45,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_USERAGENT => $randomUA,
CURLOPT_HTTPHEADER => [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: fr-FR,fr;q=0.9',
'Accept-Encoding: gzip, deflate',
'Upgrade-Insecure-Requests: 1',
'Sec-Fetch-Dest: document',
'Sec-Fetch-Mode: navigate',
'Sec-Fetch-Site: none',
'Sec-Fetch-User: ?1',
],
CURLOPT_ENCODING => '',
]);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200 && strlen($html) > 1000) {
error_log("Succès avec Mobile UA pour URL: $url");
return $html;
}
return false;
}
/**
* Contournement Cloudflare amélioré
*/
function fetchWithCloudflareBypass($url) {
$ch = curl_init();
// Headers Cloudflare-friendly
$headers = [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',
'Accept-Encoding: gzip, deflate, br',
'Cache-Control: max-age=0',
'Connection: keep-alive',
'Upgrade-Insecure-Requests: 1',
'Sec-Fetch-Dest: document',
'Sec-Fetch-Mode: navigate',
'Sec-Fetch-Site: none',
'Sec-Fetch-User: ?1',
'sec-ch-ua: "Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
'sec-ch-ua-mobile: ?0',
'sec-ch-ua-platform: "Windows"',
'DNT: 1',
'Sec-GPC: 1'
];
// Extraction du domaine pour le referer
$parsedUrl = parse_url($url);
$baseUrl = $parsedUrl['scheme'] . '://' . $parsedUrl['host'];
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 60,
CURLOPT_CONNECTTIMEOUT => 20,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_ENCODING => '',
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0,
CURLOPT_COOKIEJAR => '/tmp/cookies_' . md5($url) . '.txt',
CURLOPT_COOKIEFILE => '/tmp/cookies_' . md5($url) . '.txt',
CURLOPT_REFERER => $baseUrl,
CURLOPT_AUTOREFERER => true,
// Simulation de vraies connexions
CURLOPT_TCP_FASTOPEN => true,
CURLOPT_TCP_NODELAY => true,
]);
// Premier appel (peut déclencher un challenge)
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Si challenge Cloudflare détecté (503, 403, ou page challenge)
if ($httpCode == 503 || $httpCode == 403 || strpos($html, 'cloudflare') !== false) {
error_log("Challenge Cloudflare détecté, attente de 5 secondes...");
sleep(5); // Attendre le challenge
// Deuxième tentative
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
}
$error = curl_error($ch);
curl_close($ch);
// Nettoyer le fichier de cookies
@unlink('/tmp/cookies_' . md5($url) . '.txt');
if ($httpCode >= 200 && $httpCode < 400 && strlen($html) > 500) {
return $html;
}
if ($error) {
error_log("CURL Cloudflare Bypass Error: $error pour URL: $url");
}
return false;
}
/**
* Rotation de User-Agents (évite détection de bot)
*/
function fetchWithRotatingUserAgents($url) {
$userAgents = [
// Chrome Windows
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
// Firefox Windows
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0',
// Safari macOS
'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15',
// Edge Windows
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0',
// Chrome macOS
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
];
// Choisir un User-Agent aléatoire
$randomUA = $userAgents[array_rand($userAgents)];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 45,
CURLOPT_CONNECTTIMEOUT => 15,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_USERAGENT => $randomUA,
CURLOPT_HTTPHEADER => [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: fr-FR,fr;q=0.9,en;q=0.8',
'Accept-Encoding: gzip, deflate',
'Connection: keep-alive',
'Upgrade-Insecure-Requests: 1'
],
CURLOPT_ENCODING => '',
CURLOPT_COOKIEJAR => '',
]);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 200 && $httpCode < 400 && strlen($html) > 500) {
return $html;
}
return false;
}
/**
* Retry avec délai progressif (évite rate limiting)
*/
function fetchWithDelayAndRetry($url, $maxAttempts = 3) {
for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 60,
CURLOPT_CONNECTTIMEOUT => 20,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
CURLOPT_ENCODING => '',
]);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 200 && $httpCode < 400 && strlen($html) > 500) {
error_log("Succès à la tentative $attempt pour URL: $url");
return $html;
}
if ($attempt < $maxAttempts) {
$delay = $attempt * 2; // 2s, 4s, 6s...
error_log("Tentative $attempt échouée, attente de {$delay}s avant retry...");
sleep($delay);
}
}
return false;
}
/**
* Fetch avec headers réalistes (navigateur Chrome)
*/
function fetchHTMLWithRealHeaders($url) {
$ch = curl_init();
$headers = [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
'Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',
'Accept-Encoding: gzip, deflate, br',
'Cache-Control: max-age=0',
'Connection: keep-alive',
'Upgrade-Insecure-Requests: 1',
'Sec-Fetch-Dest: document',
'Sec-Fetch-Mode: navigate',
'Sec-Fetch-Site: none',
'Sec-Fetch-User: ?1',
'sec-ch-ua: "Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
'sec-ch-ua-mobile: ?0',
'sec-ch-ua-platform: "Windows"'
];
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 45,
CURLOPT_CONNECTTIMEOUT => 15,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_ENCODING => '',
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0,
CURLOPT_COOKIEFILE => '',
CURLOPT_REFERER => 'https://www.google.com/',
]);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
error_log("CURL Error Real Headers: $error pour URL: $url");
return false;
}
if ($httpCode >= 200 && $httpCode < 400) {
return $html;
}
error_log("HTTP Code $httpCode avec Real Headers pour URL: $url");
return false;
}
/**
* Fetch basique (fallback)
*/
function fetchHTMLBasic($url) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_USERAGENT => GEO_AUDIT_USER_AGENT,
CURLOPT_ENCODING => '',
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
]);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
error_log("CURL Error Basic: $error pour URL: $url");
return false;
}
if ($httpCode === 200) {
return $html;
}
error_log("HTTP Code $httpCode Basic pour URL: $url");
return false;
}
/**
* Récupère le HTML avec identification explicite comme bot
* Utilise le User-Agent GEO-Audit-Bot pour être identifiable dans les logs serveur
*/
function fetchHTMLAsBot($url) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_USERAGENT => GEO_AUDIT_USER_AGENT,
CURLOPT_ENCODING => '',
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_HTTPHEADER => [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: fr-FR,fr;q=0.9,en;q=0.8',
'Cache-Control: no-cache',
'X-GEO-Audit: true',
'X-Bot-Purpose: SEO/GEO Analysis'
],
]);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
error_log("CURL Error AsBot: $error pour URL: $url");
return false;
}
if ($httpCode === 200) {
error_log("fetchHTMLAsBot: Succès HTTP 200 pour URL: $url");
return $html;
}
error_log("HTTP Code $httpCode AsBot pour URL: $url");
return false;
}
/**
* file_get_contents avec contexte (dernier recours)
*/
function fetchWithFileGetContents($url) {
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36\r\n" .
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" .
"Accept-Language: fr-FR,fr;q=0.9\r\n",
'timeout' => 30,
'follow_location' => true,
'max_redirects' => 5,
'ignore_errors' => true
],
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false
]
]);
$html = @file_get_contents($url, false, $context);
if ($html && strlen($html) > 500) {
error_log("Succès avec file_get_contents pour URL: $url");
return $html;
}
return false;
}
// Les fonctions analyzeHTML, analyzeEntities, etc. restent identiques
// (Copier tout le reste du fichier audit.php original ici)
/**
* Détecte si le site utilise WordPress
*/
function detectWordPress($html, $xpath) {
$indicators = [
'wp-content' => strpos($html, 'wp-content') !== false,
'wp-includes' => strpos($html, 'wp-includes') !== false,
'wordpress' => stripos($html, 'wordpress') !== false,
'wp-json' => strpos($html, 'wp-json') !== false,
'woocommerce' => strpos($html, 'woocommerce') !== false,
'elementor' => strpos($html, 'elementor') !== false,
'yoast' => stripos($html, 'yoast') !== false,
'generator_wp' => preg_match('/<meta[^>]*name=["\']generator["\'][^>]*content=["\']WordPress/i', $html),
];
$score = 0;
foreach ($indicators as $value) {
if ($value) $score++;
}
return $score >= 2;
}
/**
* Analyse complète du HTML
*/
function analyzeHTML($html, $url, $pageType) {
$dom = new DOMDocument();