Repository navigation
Expand file tree
/
Copy pathCore.php
More file actions
1558 lines (1346 loc) · 52.3 KB
/
Copy pathCore.php
File metadata and controls
1558 lines (1346 loc) · 52.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
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
/**
* 友链RSS聚合核心类 - 重写版
* 增强RSS检测和拉取功能,完善错误日志系统
*/
class FriendsRSS_Core
{
private $db;
private $options;
private $pluginOptions;
private $cacheDir;
private $logFile;
public function __construct()
{
$this->db = Typecho_Db::get();
$this->options = Typecho_Widget::widget('Widget_Options');
$this->pluginOptions = $this->options->plugin('FriendsRSS');
$this->cacheDir = __TYPECHO_ROOT_DIR__ . '/usr/cache/friends_rss/';
$this->logFile = __DIR__ . '/error.log';
// 确保缓存目录存在
if (!is_dir($this->cacheDir)) {
@mkdir($this->cacheDir, 0755, true);
}
// 确保RSS配置文件存在
$configFile = __DIR__ . '/rss_config.json';
if (!file_exists($configFile)) {
@file_put_contents($configFile, '{}', LOCK_EX);
}
}
/**
* 记录日志
*/
public function log($message, $level = 'INFO')
{
try {
$timestamp = date('Y-m-d H:i:s');
if (is_array($message) || is_object($message)) {
$message = print_r($message, true);
}
$logMessage = "[$timestamp] [$level] " . $message . "\n";
@file_put_contents($this->logFile, $logMessage, FILE_APPEND | LOCK_EX);
} catch (Exception $e) {
// 静默处理日志写入失败,避免循环错误
}
}
/**
* 获取友链列表
*/
public function getFriendLinks()
{
$prefix = $this->db->getPrefix();
$category = $this->pluginOptions->linkCategory ?: '';
$excludeUrls = $this->getExcludeUrls();
try {
// 如果指定了分类,先尝试获取该分类的友链
if (!empty($category)) {
$links = $this->db->fetchAll(
$this->db->select('name', 'url', 'description')
->from($prefix . 'links')
->where('sort = ?', $category)
->order('order', Typecho_Db::SORT_ASC)
);
// 如果指定分类有友链,过滤排除的网址后返回
if (!empty($links)) {
$filteredLinks = $this->filterExcludedUrls($links, $excludeUrls);
$this->log("成功获取友链列表(分类:{$category}),共 " . count($links) . " 个链接,排除 " . (count($links) - count($filteredLinks)) . " 个");
return $filteredLinks;
}
// 如果指定分类没有友链,记录日志并继续尝试获取所有友链
$this->log("指定分类 '{$category}' 没有找到友链,尝试获取所有友链");
}
// 获取所有友链(兼容只有一种友链的主题)
$links = $this->db->fetchAll(
$this->db->select('name', 'url', 'description')
->from($prefix . 'links')
->order('order', Typecho_Db::SORT_ASC)
);
// 过滤排除的网址
$filteredLinks = $this->filterExcludedUrls($links, $excludeUrls);
$this->log("成功获取所有友链列表,共 " . count($links) . " 个链接,排除 " . (count($links) - count($filteredLinks)) . " 个");
return $filteredLinks ?: array();
} catch (Exception $e) {
$this->log("获取友链列表失败: " . $e->getMessage(), 'ERROR');
return array();
}
}
/**
* 获取排除的网址列表
*/
private function getExcludeUrls()
{
$excludeUrls = $this->pluginOptions->excludeUrls ?: '';
if (empty($excludeUrls)) {
return array();
}
// 按行分割,去除空行和空白字符
$urls = array();
$lines = explode("\n", $excludeUrls);
foreach ($lines as $line) {
$line = trim($line);
if (!empty($line)) {
$urls[] = $line;
}
}
return $urls;
}
/**
* 过滤排除的网址
*/
private function filterExcludedUrls($links, $excludeUrls)
{
if (empty($excludeUrls)) {
return $links;
}
$filteredLinks = array();
foreach ($links as $link) {
$shouldExclude = false;
foreach ($excludeUrls as $excludeUrl) {
if (strpos($link['url'], $excludeUrl) !== false) {
$shouldExclude = true;
$this->log("排除友链: {$link['name']} ({$link['url']}) - 匹配排除规则: {$excludeUrl}");
break;
}
}
if (!$shouldExclude) {
$filteredLinks[] = $link;
}
}
return $filteredLinks;
}
/**
* 获取可用的友链分类
*/
public function getAvailableCategories()
{
$prefix = $this->db->getPrefix();
try {
$categories = $this->db->fetchAll(
$this->db->select('sort')
->from($prefix . 'links')
->group('sort')
->order('sort', Typecho_Db::SORT_ASC)
);
$result = array();
foreach ($categories as $cat) {
if (!empty($cat['sort'])) {
$result[] = $cat['sort'];
}
}
$this->log("获取到友链分类: " . implode(', ', $result));
return $result;
} catch (Exception $e) {
$this->log("获取友链分类失败: " . $e->getMessage(), 'ERROR');
return array();
}
}
/**
* 读取配置的时间间隔(小时)
* 未设置时使用默认值;显式设为 0 表示禁用(不会被默认值覆盖)
*/
public function getConfiguredInterval($key, $default)
{
if (!isset($this->pluginOptions->$key) || $this->pluginOptions->$key === '' || $this->pluginOptions->$key === null) {
return intval($default);
}
return intval($this->pluginOptions->$key);
}
/**
* 将间隔小时转为缓存秒数;0 表示定时禁用,缓存长期有效(仅强制刷新)
*/
private function getCacheTtlSeconds($intervalHours)
{
if ($intervalHours <= 0) {
return 10 * 365 * 86400;
}
return $intervalHours * 3600;
}
/**
* 判断定时任务是否到期
*/
public function isScheduleDue($statusFileName, $intervalHours)
{
if ($intervalHours <= 0) {
return false;
}
$statusFile = $this->cacheDir . $statusFileName;
if (!file_exists($statusFile)) {
return true;
}
$data = json_decode(@file_get_contents($statusFile), true);
if (!$data || !isset($data['last_run'])) {
return true;
}
return time() >= (intval($data['last_run']) + ($intervalHours * 3600));
}
/**
* 是否有任意定时任务到期(轻量检查,供访问触发)
*/
public function isAnyScheduleDue()
{
$detectInterval = $this->getConfiguredInterval('autoDetectInterval', 240);
$parseInterval = $this->getConfiguredInterval('autoRefreshInterval', 6);
return $this->isScheduleDue('detect_status.json', $detectInterval)
|| $this->isScheduleDue('cron_status.json', $parseInterval);
}
/**
* 写入定时任务状态
*/
public function writeScheduleStatus($statusFileName, $data)
{
if (!is_dir($this->cacheDir)) {
@mkdir($this->cacheDir, 0755, true);
}
$statusFile = $this->cacheDir . $statusFileName;
return file_put_contents($statusFile, json_encode($data, JSON_PRETTY_PRINT), LOCK_EX) !== false;
}
/**
* 尝试获取软定时触发锁,避免并发访客重复拉起任务
*/
public function tryAcquireSoftCronLock($ttl = 120)
{
$lockFile = $this->cacheDir . 'soft_cron_spawn.lock';
if (file_exists($lockFile) && (time() - filemtime($lockFile)) < $ttl) {
return false;
}
if (!is_dir($this->cacheDir)) {
@mkdir($this->cacheDir, 0755, true);
}
return @file_put_contents($lockFile, (string) time(), LOCK_EX) !== false;
}
/**
* 尝试获取任务执行锁
*/
private function tryAcquireCronRunLock($ttl = 1800)
{
$lockFile = $this->cacheDir . 'cron_running.lock';
if (file_exists($lockFile) && (time() - filemtime($lockFile)) < $ttl) {
return false;
}
if (!is_dir($this->cacheDir)) {
@mkdir($this->cacheDir, 0755, true);
}
return @file_put_contents($lockFile, (string) time(), LOCK_EX) !== false;
}
private function releaseCronRunLock()
{
$lockFile = $this->cacheDir . 'cron_running.lock';
if (file_exists($lockFile)) {
@unlink($lockFile);
}
}
/**
* 执行到期的定时任务(RSS检测 + 文章解析)
* 供 cron.php / action?do=cron / 访问触发软定时 调用
*/
public function runScheduledTasks($force = false)
{
$result = array(
'detect' => null,
'parse' => null,
'ran' => false,
'messages' => array()
);
if (!$this->tryAcquireCronRunLock()) {
$result['messages'][] = 'Cron already running';
return $result;
}
try {
return $this->doRunScheduledTasks($force, $result);
} finally {
$this->releaseCronRunLock();
}
}
/**
* 实际执行到期任务
*/
private function doRunScheduledTasks($force, $result)
{
$detectInterval = $this->getConfiguredInterval('autoDetectInterval', 240);
$parseInterval = $this->getConfiguredInterval('autoRefreshInterval', 6);
// 1) 定时检测 RSS 地址
if ($detectInterval <= 0) {
$result['messages'][] = 'Detect cron disabled (interval: 0)';
} elseif ($force || $this->isScheduleDue('detect_status.json', $detectInterval)) {
$links = $this->getFriendLinks();
$detectResults = $this->batchDetectRSS($links, null, true);
$successCount = array_sum(array_column($detectResults, 'success'));
$now = time();
$this->writeScheduleStatus('detect_status.json', array(
'last_run' => $now,
'success_count' => $successCount,
'total_count' => count($links),
'status' => 'success',
'next_run' => $now + ($detectInterval * 3600)
));
$result['detect'] = array(
'success' => $successCount,
'total' => count($links)
);
$result['ran'] = true;
$msg = "定时检测执行成功,成功 {$successCount}/" . count($links);
$result['messages'][] = $msg;
$this->log($msg, 'CRON');
} else {
$result['messages'][] = 'Detect not due yet';
}
// 2) 定时解析文章
if ($parseInterval <= 0) {
$result['messages'][] = 'Parse cron disabled (interval: 0)';
} elseif ($force || $this->isScheduleDue('cron_status.json', $parseInterval)) {
$articles = $this->getAggregatedArticles(true);
$now = time();
$this->writeScheduleStatus('cron_status.json', array(
'last_run' => $now,
'articles_count' => count($articles),
'status' => 'success',
'next_run' => $now + ($parseInterval * 3600)
));
$result['parse'] = array(
'articles_count' => count($articles)
);
$result['ran'] = true;
$msg = '定时解析执行成功,获取到 ' . count($articles) . ' 篇文章';
$result['messages'][] = $msg;
$this->log($msg, 'CRON');
} else {
$result['messages'][] = 'Parse not due yet';
}
return $result;
}
/**
* 优化的RSS URL检测(分轮检测策略)
*/
public function detectRSSUrl($siteUrl, $timeout = 2)
{
$siteUrl = rtrim($siteUrl, '/');
$cacheKey = md5($siteUrl . '_rss_detect');
$cacheFile = $this->cacheDir . 'rss_' . $cacheKey . '.json';
// 与定时检测间隔保持一致(0=禁用定时,缓存长期有效)
$detectInterval = $this->getConfiguredInterval('autoDetectInterval', 240);
$cacheTime = $this->getCacheTtlSeconds($detectInterval);
$this->log("开始检测RSS URL: $siteUrl (超时: {$timeout}s, 缓存: {$detectInterval}小时)");
// 检查缓存
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime) {
$cached = @file_get_contents($cacheFile);
if ($cached) {
$data = json_decode($cached, true);
if ($data && isset($data['rssUrl'])) {
$this->log("从缓存获取RSS URL: " . ($data['rssUrl'] ?: '未找到'));
return $data['rssUrl'] ?: false;
}
}
}
$detectedUrl = false;
try {
// 第一轮:快速检测最常用路径 /feed/ 和 /feed(最高成功率)
$this->log("第一轮:快速检测最常用路径");
$detectedUrl = $this->tryFirstRoundPaths($siteUrl, $timeout);
// 第二轮:如果第一轮失败,尝试HTML解析
if (!$detectedUrl) {
$this->log("第二轮:HTML解析检测");
$detectedUrl = $this->trySecondRoundHTML($siteUrl, $timeout);
}
// 第三轮:如果前两轮都失败,尝试其他常见路径
if (!$detectedUrl) {
$this->log("第三轮:其他常见路径检测");
$detectedUrl = $this->tryThirdRoundPaths($siteUrl, $timeout);
}
} catch (Exception $e) {
$this->log("RSS检测过程中发生异常: " . $e->getMessage(), 'ERROR');
}
// 缓存结果(包括失败的结果)
$cacheData = array(
'rssUrl' => $detectedUrl,
'lastCheck' => time(),
'siteUrl' => $siteUrl
);
@file_put_contents($cacheFile, json_encode($cacheData), LOCK_EX);
$this->log("RSS检测完成: " . ($detectedUrl ? "成功 - $detectedUrl" : "失败"));
return $detectedUrl;
}
/**
* 第一轮:快速检测最常用路径(成功率最高)
*/
private function tryFirstRoundPaths($siteUrl, $timeout)
{
$firstRoundPaths = array(
$siteUrl . '/feed/',
$siteUrl . '/feed'
);
foreach ($firstRoundPaths as $feedUrl) {
$this->log("第一轮尝试: $feedUrl");
if ($this->validateRSSContent($feedUrl, $timeout)) {
$this->log("第一轮成功找到RSS: $feedUrl");
return $feedUrl;
}
}
return false;
}
/**
* 第二轮:HTML解析检测
*/
private function trySecondRoundHTML($siteUrl, $timeout)
{
$this->log("开始HTML解析检测");
$htmlContent = $this->fetchContent($siteUrl, $timeout);
if ($htmlContent) {
$rssUrl = $this->parseRSSFromHTML($htmlContent, $siteUrl);
if ($rssUrl && $this->validateRSSContent($rssUrl, $timeout)) {
$this->log("HTML解析成功找到RSS: $rssUrl");
return $rssUrl;
}
}
return false;
}
/**
* 第三轮:其他常见路径检测(包含特殊网站类型)
*/
private function tryThirdRoundPaths($siteUrl, $timeout)
{
$thirdRoundPaths = array(
// 常见XML文件
$siteUrl . '/rss.xml',
$siteUrl . '/atom.xml',
// $siteUrl . '/feed.xml',
// $siteUrl . '/index.xml',
// $siteUrl . '/rss',
// WordPress路径
// $siteUrl . '/?feed=rss2',
// $siteUrl . '/index.php?feed=rss2',
// 博客路径
// $siteUrl . '/blog/feed',
// $siteUrl . '/blog/rss.xml',
// $siteUrl . '/posts/feed',
// $siteUrl . '/articles/feed',
// 其他常见路径
// $siteUrl . '/feeds/all.atom.xml',
// $siteUrl . '/feeds/posts/default',
// $siteUrl . '/rss/',
// $siteUrl . '/atom/',
);
foreach ($thirdRoundPaths as $feedUrl) {
$this->log("第三轮尝试: $feedUrl");
if ($this->validateRSSContent($feedUrl, $timeout)) {
$this->log("第三轮成功找到RSS: $feedUrl");
return $feedUrl;
}
}
return false;
}
/**
* 旧版本兼容:尝试常见的RSS路径(已废弃,使用分轮检测)
*/
private function tryCommonRSSPaths($siteUrl)
{
// 为了向后兼容保留此方法,但实际使用分轮检测
return $this->tryThirdRoundPaths($siteUrl, 8);
}
/**
* 增强的HTML RSS链接解析
*/
private function parseRSSFromHTML($html, $baseUrl)
{
// 多种RSS/Atom链接模式
$patterns = array(
// 标准RSS链接
'/<link[^>]*type=["\']application\/rss\+xml["\'][^>]*href=["\']([^"\'>]+)["\'][^>]*>/i',
'/<link[^>]*href=["\']([^"\'>]+)["\'][^>]*type=["\']application\/rss\+xml["\'][^>]*>/i',
// Atom链接
'/<link[^>]*type=["\']application\/atom\+xml["\'][^>]*href=["\']([^"\'>]+)["\'][^>]*>/i',
'/<link[^>]*href=["\']([^"\'>]+)["\'][^>]*type=["\']application\/atom\+xml["\'][^>]*>/i',
// 其他可能的RSS链接
'/<link[^>]*rel=["\']alternate["\'][^>]*type=["\']application\/rss\+xml["\'][^>]*href=["\']([^"\'>]+)["\'][^>]*>/i',
'/<link[^>]*rel=["\']alternate["\'][^>]*href=["\']([^"\'>]+)["\'][^>]*type=["\']application\/rss\+xml["\'][^>]*>/i',
);
foreach ($patterns as $pattern) {
if (preg_match($pattern, $html, $matches)) {
$rssUrl = trim($matches[1]);
// 处理相对URL
if (strpos($rssUrl, 'http') !== 0) {
if (strpos($rssUrl, '//') === 0) {
$rssUrl = 'https:' . $rssUrl;
} elseif (strpos($rssUrl, '/') === 0) {
$parsedUrl = parse_url($baseUrl);
$rssUrl = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . $rssUrl;
} else {
$rssUrl = rtrim($baseUrl, '/') . '/' . ltrim($rssUrl, '/');
}
}
$this->log("从HTML解析到RSS链接: $rssUrl");
return $rssUrl;
}
}
return false;
}
/**
* 验证RSS内容是否有效(支持超时设置)
*/
private function validateRSSContent($url, $timeout = 10)
{
try {
$content = $this->fetchContent($url, $timeout);
if (!$content) {
return false;
}
// 检查Content-Type
$headers = $this->getLastHeaders();
$contentType = '';
foreach ($headers as $header) {
if (stripos($header, 'content-type:') === 0) {
$contentType = strtolower($header);
break;
}
}
// 检查是否为XML内容类型
$isXmlContentType = (
strpos($contentType, 'xml') !== false ||
strpos($contentType, 'rss') !== false ||
strpos($contentType, 'atom') !== false
);
// 检查内容是否包含RSS/Atom标签
$hasRssContent = (
strpos($content, '<rss') !== false ||
strpos($content, '<feed') !== false ||
strpos($content, '<channel>') !== false ||
strpos($content, 'xmlns:atom') !== false ||
strpos($content, 'xmlns="http://www.w3.org/2005/Atom"') !== false
);
$isValid = $isXmlContentType || $hasRssContent;
if ($isValid) {
$this->log("RSS验证成功: $url");
} else {
$this->log("RSS验证失败: $url - 内容类型: $contentType");
}
return $isValid;
} catch (Exception $e) {
$this->log("RSS验证异常: $url - " . $e->getMessage(), 'ERROR');
return false;
}
}
/**
* 获取最后请求的HTTP响应头
*/
private $lastHeaders = array();
private function getLastHeaders()
{
return $this->lastHeaders;
}
/**
* 增强的内容获取函数(优化超时处理)
*/
private function fetchContent($url, $timeout = 2)
{
$this->lastHeaders = array();
$timeout = max(2, intval($timeout)); // 最少2秒超时
$startTime = microtime(true); // 记录开始时间
try {
// 优先使用cURL
if (function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, min(2, $timeout)); // 连接超时不超过总超时时间
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3); // 减少重定向次数
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; FriendsRSS/2.0; +' . $this->options->siteUrl . ')');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($curl, $header) {
$this->lastHeaders[] = trim($header);
return strlen($header);
});
$content = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
$this->log("cURL错误: $url - $error", 'WARN');
return false;
}
if ($httpCode >= 200 && $httpCode < 300 && $content !== false) {
$actualTime = round(microtime(true) - $startTime, 2); // 计算实际用时
$this->log("成功获取内容: $url (HTTP $httpCode, 用时: {$actualTime}s)");
return $content;
} else {
$this->log("HTTP错误: $url - 状态码: $httpCode", 'WARN');
}
}
// 备用方案:file_get_contents
if (function_exists('file_get_contents')) {
$context = stream_context_create(array(
'http' => array(
'timeout' => $timeout,
'user_agent' => 'Mozilla/5.0 (compatible; FriendsRSS/2.0; +' . $this->options->siteUrl . ')',
'follow_location' => 1,
'max_redirects' => 3
)
));
$content = @file_get_contents($url, false, $context);
if ($content !== false) {
$actualTime = round(microtime(true) - $startTime, 2); // 计算实际用时
$this->log("备用方案成功获取内容: $url (用时: {$actualTime}s)");
return $content;
}
}
} catch (Exception $e) {
$this->log("获取内容异常: $url - " . $e->getMessage(), 'WARN');
}
$this->log("获取内容失败: $url (超时: {$timeout}s)", 'WARN');
return false;
}
/**
* 增强的RSS解析功能
*/
public function parseRSS($rssUrl)
{
$this->log("开始解析RSS: $rssUrl");
try {
$content = $this->fetchContent($rssUrl, 20);
if (!$content) {
$this->log("无法获取RSS内容: $rssUrl", 'WARN');
return array();
}
// 清理和预处理XML内容
$content = $this->cleanXMLContent($content);
// 尝试解析XML
$xml = $this->parseXMLContent($content);
if (!$xml) {
$this->log("XML解析失败: $rssUrl", 'ERROR');
return array();
}
$articles = array();
$maxArticles = intval($this->pluginOptions->articlesPerBlog) ?: 5;
// RSS 2.0格式解析
if (isset($xml->channel->item)) {
$this->log("检测到RSS 2.0格式");
$articles = $this->parseRSS20($xml, $maxArticles);
}
// Atom格式解析
elseif (isset($xml->entry)) {
$this->log("检测到Atom格式");
$articles = $this->parseAtom($xml, $maxArticles);
}
// RSS 1.0格式解析
elseif (isset($xml->item)) {
$this->log("检测到RSS 1.0格式");
$articles = $this->parseRSS10($xml, $maxArticles);
} else {
$this->log("未识别的RSS格式: $rssUrl", 'WARN');
}
$this->log("成功解析RSS: " . $rssUrl . ",获得 " . count($articles) . " 篇文章");
return $articles;
} catch (Exception $e) {
$this->log("RSS解析异常: $rssUrl - " . $e->getMessage(), 'ERROR');
return array();
}
}
/**
* 清理XML内容
*/
private function cleanXMLContent($content)
{
// 移除BOM
$content = preg_replace('/^\xEF\xBB\xBF/', '', $content);
// 移除控制字符
$content = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $content);
// 修复常见的XML问题
$content = str_replace(' ', ' ', $content);
$content = preg_replace('/&(?!#?[a-zA-Z0-9]+;)/', '&', $content);
return trim($content);
}
/**
* 解析XML内容
*/
private function parseXMLContent($content)
{
try {
// 使用内部错误处理
$previousUseErrors = libxml_use_internal_errors(true);
// 禁用外部实体加载以提高安全性(仅在PHP 8.0以下版本需要)
$previousValue = null;
if (PHP_VERSION_ID < 80000 && function_exists('libxml_disable_entity_loader')) {
$previousValue = libxml_disable_entity_loader(true);
}
// 解析XML,使用安全选项
$xml = simplexml_load_string(
$content,
'SimpleXMLElement',
LIBXML_NOCDATA | LIBXML_NOENT | LIBXML_NONET
);
// 恢复设置
if ($previousValue !== null && function_exists('libxml_disable_entity_loader')) {
libxml_disable_entity_loader($previousValue);
}
libxml_use_internal_errors($previousUseErrors);
return $xml;
} catch (Exception $e) {
$this->log("XML解析错误: " . $e->getMessage(), 'ERROR');
return false;
}
}
/**
* 解析RSS 2.0格式
*/
private function parseRSS20($xml, $maxArticles)
{
$articles = array();
$count = 0;
foreach ($xml->channel->item as $item) {
if ($count >= $maxArticles) break;
try {
$article = $this->parseRSSItem($item);
if ($article) {
$articles[] = $article;
$count++;
}
} catch (Exception $e) {
$this->log("解析RSS条目错误: " . $e->getMessage(), 'WARN');
continue;
}
}
return $articles;
}
/**
* 解析Atom格式
*/
private function parseAtom($xml, $maxArticles)
{
$articles = array();
$count = 0;
foreach ($xml->entry as $entry) {
if ($count >= $maxArticles) break;
try {
$article = $this->parseAtomEntry($entry);
if ($article) {
$articles[] = $article;
$count++;
}
} catch (Exception $e) {
$this->log("解析Atom条目错误: " . $e->getMessage(), 'WARN');
continue;
}
}
return $articles;
}
/**
* 解析RSS 1.0格式
*/
private function parseRSS10($xml, $maxArticles)
{
$articles = array();
$count = 0;
foreach ($xml->item as $item) {
if ($count >= $maxArticles) break;
try {
$article = $this->parseRSSItem($item);
if ($article) {
$articles[] = $article;
$count++;
}
} catch (Exception $e) {
$this->log("解析RSS 1.0条目错误: " . $e->getMessage(), 'WARN');
continue;
}
}
return $articles;
}
/**
* 解析RSS条目
*/
private function parseRSSItem($item)
{
$title = $this->cleanText((string)$item->title);
$link = trim((string)$item->link);
if (empty($title) || empty($link)) {
return null;
}
// 解析发布时间
$pubDate = $this->parseDate($item);
// 解析描述
$description = $this->parseDescription($item);
// 解析作者
$author = $this->parseAuthor($item);
return array(
'title' => $title,
'link' => $this->upgradeToHttps($link),
'description' => $description,
'pubDate' => $pubDate,
'author' => $author
);
}
/**
* 解析Atom条目
*/
private function parseAtomEntry($entry)
{
$title = $this->cleanText((string)$entry->title);
// 解析链接
$link = '';
if (isset($entry->link)) {
if (isset($entry->link['href'])) {
$link = (string)$entry->link['href'];
} else {
$link = (string)$entry->link;
}
}
if (empty($title) || empty($link)) {
return null;
}
// 解析发布时间
$pubDate = 0;
if (isset($entry->published)) {
$pubDate = strtotime((string)$entry->published);
} elseif (isset($entry->updated)) {
$pubDate = strtotime((string)$entry->updated);
}
// 解析描述
$description = '';
if (isset($entry->summary)) {
$description = $this->cleanText((string)$entry->summary);
} elseif (isset($entry->content)) {
$description = $this->cleanText((string)$entry->content);
}
// 解析作者
$author = '';
if (isset($entry->author->name)) {
$author = $this->cleanText((string)$entry->author->name);
} elseif (isset($entry->author)) {
$author = $this->cleanText((string)$entry->author);
}
return array(
'title' => $title,
'link' => $this->upgradeToHttps(trim($link)),
'description' => $description,
'pubDate' => $pubDate ?: time(),
'author' => $author
);
}
/**
* 解析日期
*/
private function parseDate($item)
{
$dateFields = array('pubDate', 'date', 'published', 'updated');
foreach ($dateFields as $field) {
if (isset($item->$field)) {
$timestamp = strtotime((string)$item->$field);
if ($timestamp) {
return $timestamp;
}
}
}
// 尝试Dublin Core命名空间
$dcNamespace = $item->children('http://purl.org/dc/elements/1.1/');
if (isset($dcNamespace->date)) {
$timestamp = strtotime((string)$dcNamespace->date);
if ($timestamp) {
return $timestamp;
}
}
return time(); // 默认返回当前时间
}
/**
* 解析描述
*/
private function parseDescription($item)
{
$descriptionFields = array('description', 'summary', 'content:encoded', 'content');