-
-
Notifications
You must be signed in to change notification settings - Fork 888
/
Copy pathfeedController.php
1167 lines (1052 loc) · 39.4 KB
/
feedController.php
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
declare(strict_types=1);
/**
* Controller to handle every feed actions.
*/
class FreshRSS_feed_Controller extends FreshRSS_ActionController {
/**
* This action is called before every other action in that class. It is
* the common boiler plate for every action. It is triggered by the
* underlying framework.
*/
#[\Override]
public function firstAction(): void {
if (!FreshRSS_Auth::hasAccess()) {
// Token is useful in the case that anonymous refresh is forbidden
// and CRON task cannot be used with php command so the user can
// set a CRON task to refresh his feeds by using token inside url
$token = FreshRSS_Context::userConf()->token;
$token_param = Minz_Request::paramString('token');
$token_is_ok = ($token != '' && $token == $token_param);
$action = Minz_Request::actionName();
$allow_anonymous_refresh = FreshRSS_Context::systemConf()->allow_anonymous_refresh;
if ($action !== 'actualize' ||
!($allow_anonymous_refresh || $token_is_ok)) {
Minz_Error::error(403);
}
}
}
/**
* @param array<string,mixed> $attributes
* @throws FreshRSS_AlreadySubscribed_Exception
* @throws FreshRSS_BadUrl_Exception
* @throws FreshRSS_Feed_Exception
* @throws FreshRSS_FeedNotAdded_Exception
* @throws Minz_FileNotExistException
*/
public static function addFeed(string $url, string $title = '', int $cat_id = 0, string $new_cat_name = '',
string $http_auth = '', array $attributes = [], int $kind = FreshRSS_Feed::KIND_RSS): FreshRSS_Feed {
FreshRSS_UserDAO::touch();
if (function_exists('set_time_limit')) {
@set_time_limit(300);
}
$catDAO = FreshRSS_Factory::createCategoryDao();
$url = trim($url);
/** @var string|null $urlHooked */
$urlHooked = Minz_ExtensionManager::callHook('check_url_before_add', $url);
if ($urlHooked === null) {
throw new FreshRSS_FeedNotAdded_Exception($url);
}
$url = $urlHooked;
$cat = null;
if ($cat_id > 0) {
$cat = $catDAO->searchById($cat_id);
}
if ($cat === null && $new_cat_name != '') {
$new_cat_id = $catDAO->addCategory(['name' => $new_cat_name]);
$cat_id = $new_cat_id > 0 ? $new_cat_id : $cat_id;
$cat = $catDAO->searchById($cat_id);
}
if ($cat === null) {
$catDAO->checkDefault();
}
$feed = new FreshRSS_Feed($url); //Throws FreshRSS_BadUrl_Exception
$title = trim($title);
if ($title !== '') {
$feed->_name($title);
}
$feed->_kind($kind);
$feed->_attributes($attributes);
$feed->_httpAuth($http_auth);
if ($cat === null) {
$feed->_categoryId(FreshRSS_CategoryDAO::DEFAULTCATEGORYID);
} else {
$feed->_category($cat);
}
switch ($kind) {
case FreshRSS_Feed::KIND_RSS:
case FreshRSS_Feed::KIND_RSS_FORCED:
$feed->load(true); //Throws FreshRSS_Feed_Exception, Minz_FileNotExistException
break;
case FreshRSS_Feed::KIND_HTML_XPATH:
case FreshRSS_Feed::KIND_XML_XPATH:
$feed->_website($url);
break;
}
$feedDAO = FreshRSS_Factory::createFeedDao();
if ($feedDAO->searchByUrl($feed->url())) {
throw new FreshRSS_AlreadySubscribed_Exception($url, $feed->name());
}
/** @var FreshRSS_Feed|null $feed */
$feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed);
if ($feed === null) {
throw new FreshRSS_FeedNotAdded_Exception($url);
}
$id = $feedDAO->addFeedObject($feed);
if (!$id) {
// There was an error in database… we cannot say what here.
throw new FreshRSS_FeedNotAdded_Exception($url);
}
$feed->_id($id);
// Ok, feed has been added in database. Now we have to refresh entries.
[, , $nb_new_articles] = self::actualizeFeeds($id, $url);
if ($nb_new_articles > 0) {
self::commitNewEntries();
}
return $feed;
}
/**
* This action subscribes to a feed.
*
* It can be reached by both GET and POST requests.
*
* GET request displays a form to add and configure a feed.
* Request parameter is:
* - url_rss (default: false)
*
* POST request adds a feed in database.
* Parameters are:
* - url_rss (default: false)
* - category (default: false)
* - http_user (default: false)
* - http_pass (default: false)
* It tries to get website information from RSS feed.
* If no category is given, feed is added to the default one.
*
* If url_rss is false, nothing happened.
*/
public function addAction(): void {
$url = Minz_Request::paramString('url_rss');
if ($url === '') {
// No url, do nothing
Minz_Request::forward([
'c' => 'subscription',
'a' => 'index',
], true);
}
$feedDAO = FreshRSS_Factory::createFeedDao();
$url_redirect = [
'c' => 'subscription',
'a' => 'add',
'params' => [],
];
$limits = FreshRSS_Context::systemConf()->limits;
$this->view->feeds = $feedDAO->listFeeds();
if (count($this->view->feeds) >= $limits['max_feeds']) {
Minz_Request::bad(_t('feedback.sub.feed.over_max', $limits['max_feeds']), $url_redirect);
}
if (Minz_Request::isPost()) {
$cat = Minz_Request::paramInt('category');
// HTTP information are useful if feed is protected behind a
// HTTP authentication
$user = Minz_Request::paramString('http_user');
$pass = Minz_Request::paramString('http_pass');
$http_auth = '';
if ($user != '' && $pass != '') { //TODO: Sanitize
$http_auth = $user . ':' . $pass;
}
$cookie = Minz_Request::paramString('curl_params_cookie');
$cookie_file = Minz_Request::paramBoolean('curl_params_cookiefile');
$max_redirs = Minz_Request::paramInt('curl_params_redirects');
$useragent = Minz_Request::paramString('curl_params_useragent');
$proxy_address = Minz_Request::paramString('curl_params');
$proxy_type = Minz_Request::paramString('proxy_type');
$request_method = Minz_Request::paramString('curl_method');
$request_fields = Minz_Request::paramString('curl_fields', true);
$opts = [];
if ($proxy_type !== '') {
$opts[CURLOPT_PROXY] = $proxy_address;
$opts[CURLOPT_PROXYTYPE] = (int)$proxy_type;
}
if ($cookie !== '') {
$opts[CURLOPT_COOKIE] = $cookie;
}
if ($cookie_file) {
// Pass empty cookie file name to enable the libcurl cookie engine
// without reading any existing cookie data.
$opts[CURLOPT_COOKIEFILE] = '';
}
if ($max_redirs !== 0) {
$opts[CURLOPT_MAXREDIRS] = $max_redirs;
$opts[CURLOPT_FOLLOWLOCATION] = 1;
}
if ($useragent !== '') {
$opts[CURLOPT_USERAGENT] = $useragent;
}
if ($request_method === 'POST') {
$opts[CURLOPT_POST] = true;
if ($request_fields !== '') {
$opts[CURLOPT_POSTFIELDS] = $request_fields;
if (json_decode($request_fields, true) !== null) {
$opts[CURLOPT_HTTPHEADER] = ['Content-Type: application/json'];
}
}
}
$attributes = [
'curl_params' => empty($opts) ? null : $opts,
];
$attributes['ssl_verify'] = Minz_Request::paramTernary('ssl_verify');
$timeout = Minz_Request::paramInt('timeout');
$attributes['timeout'] = $timeout > 0 ? $timeout : null;
$feed_kind = Minz_Request::paramInt('feed_kind') ?: FreshRSS_Feed::KIND_RSS;
if ($feed_kind === FreshRSS_Feed::KIND_HTML_XPATH || $feed_kind === FreshRSS_Feed::KIND_XML_XPATH) {
$xPathSettings = [];
if (Minz_Request::paramString('xPathFeedTitle') !== '') {
$xPathSettings['feedTitle'] = Minz_Request::paramString('xPathFeedTitle', true);
}
if (Minz_Request::paramString('xPathItem') !== '') {
$xPathSettings['item'] = Minz_Request::paramString('xPathItem', true);
}
if (Minz_Request::paramString('xPathItemTitle') !== '') {
$xPathSettings['itemTitle'] = Minz_Request::paramString('xPathItemTitle', true);
}
if (Minz_Request::paramString('xPathItemContent') !== '') {
$xPathSettings['itemContent'] = Minz_Request::paramString('xPathItemContent', true);
}
if (Minz_Request::paramString('xPathItemUri') !== '') {
$xPathSettings['itemUri'] = Minz_Request::paramString('xPathItemUri', true);
}
if (Minz_Request::paramString('xPathItemAuthor') !== '') {
$xPathSettings['itemAuthor'] = Minz_Request::paramString('xPathItemAuthor', true);
}
if (Minz_Request::paramString('xPathItemTimestamp') !== '') {
$xPathSettings['itemTimestamp'] = Minz_Request::paramString('xPathItemTimestamp', true);
}
if (Minz_Request::paramString('xPathItemTimeFormat') !== '') {
$xPathSettings['itemTimeFormat'] = Minz_Request::paramString('xPathItemTimeFormat', true);
}
if (Minz_Request::paramString('xPathItemThumbnail') !== '') {
$xPathSettings['itemThumbnail'] = Minz_Request::paramString('xPathItemThumbnail', true);
}
if (Minz_Request::paramString('xPathItemCategories') !== '') {
$xPathSettings['itemCategories'] = Minz_Request::paramString('xPathItemCategories', true);
}
if (Minz_Request::paramString('xPathItemUid') !== '') {
$xPathSettings['itemUid'] = Minz_Request::paramString('xPathItemUid', true);
}
if (!empty($xPathSettings)) {
$attributes['xpath'] = $xPathSettings;
}
} elseif ($feed_kind === FreshRSS_Feed::KIND_JSON_DOTPATH) {
$jsonSettings = [];
if (Minz_Request::paramString('jsonFeedTitle') !== '') {
$jsonSettings['feedTitle'] = Minz_Request::paramString('jsonFeedTitle', true);
}
if (Minz_Request::paramString('jsonItem') !== '') {
$jsonSettings['item'] = Minz_Request::paramString('jsonItem', true);
}
if (Minz_Request::paramString('jsonItemTitle') !== '') {
$jsonSettings['itemTitle'] = Minz_Request::paramString('jsonItemTitle', true);
}
if (Minz_Request::paramString('jsonItemContent') !== '') {
$jsonSettings['itemContent'] = Minz_Request::paramString('jsonItemContent', true);
}
if (Minz_Request::paramString('jsonItemUri') !== '') {
$jsonSettings['itemUri'] = Minz_Request::paramString('jsonItemUri', true);
}
if (Minz_Request::paramString('jsonItemAuthor') !== '') {
$jsonSettings['itemAuthor'] = Minz_Request::paramString('jsonItemAuthor', true);
}
if (Minz_Request::paramString('jsonItemTimestamp') !== '') {
$jsonSettings['itemTimestamp'] = Minz_Request::paramString('jsonItemTimestamp', true);
}
if (Minz_Request::paramString('jsonItemTimeFormat') !== '') {
$jsonSettings['itemTimeFormat'] = Minz_Request::paramString('jsonItemTimeFormat', true);
}
if (Minz_Request::paramString('jsonItemThumbnail') !== '') {
$jsonSettings['itemThumbnail'] = Minz_Request::paramString('jsonItemThumbnail', true);
}
if (Minz_Request::paramString('jsonItemCategories') !== '') {
$jsonSettings['itemCategories'] = Minz_Request::paramString('jsonItemCategories', true);
}
if (Minz_Request::paramString('jsonItemUid') !== '') {
$jsonSettings['itemUid'] = Minz_Request::paramString('jsonItemUid', true);
}
if (!empty($jsonSettings)) {
$attributes['json_dotpath'] = $jsonSettings;
}
}
try {
$feed = self::addFeed($url, '', $cat, '', $http_auth, $attributes, $feed_kind);
} catch (FreshRSS_BadUrl_Exception $e) {
// Given url was not a valid url!
Minz_Log::warning($e->getMessage());
Minz_Request::bad(_t('feedback.sub.feed.invalid_url', $url), $url_redirect);
return;
} catch (FreshRSS_Feed_Exception $e) {
// Something went bad (timeout, server not found, etc.)
Minz_Log::warning($e->getMessage());
Minz_Request::bad(_t('feedback.sub.feed.internal_problem', _url('index', 'logs')), $url_redirect);
return;
} catch (Minz_FileNotExistException $e) {
// Cache directory doesn’t exist!
Minz_Log::error($e->getMessage());
Minz_Request::bad(_t('feedback.sub.feed.internal_problem', _url('index', 'logs')), $url_redirect);
return;
} catch (FreshRSS_AlreadySubscribed_Exception $e) {
Minz_Request::bad(_t('feedback.sub.feed.already_subscribed', $e->feedName()), $url_redirect);
return;
} catch (FreshRSS_FeedNotAdded_Exception $e) {
Minz_Request::bad(_t('feedback.sub.feed.not_added', $e->url()), $url_redirect);
return;
}
// Entries are in DB, we redirect to feed configuration page.
$url_redirect['a'] = 'feed';
$url_redirect['params']['id'] = '' . $feed->id();
Minz_Request::good(_t('feedback.sub.feed.added', $feed->name()), $url_redirect);
} else {
// GET request: we must ask confirmation to user before adding feed.
FreshRSS_View::prependTitle(_t('sub.feed.title_add') . ' · ');
$catDAO = FreshRSS_Factory::createCategoryDao();
$this->view->categories = $catDAO->listCategories(false) ?: [];
$this->view->feed = new FreshRSS_Feed($url);
try {
// We try to get more information about the feed.
$this->view->feed->load(true);
$this->view->load_ok = true;
} catch (Exception $e) {
$this->view->load_ok = false;
}
$feed = $feedDAO->searchByUrl($this->view->feed->url());
if ($feed) {
// Already subscribe so we redirect to the feed configuration page.
$url_redirect['a'] = 'feed';
$url_redirect['params']['id'] = $feed->id();
Minz_Request::good(_t('feedback.sub.feed.already_subscribed', $feed->name()), $url_redirect);
}
}
}
/**
* This action remove entries from a given feed.
*
* It should be reached by a POST action.
*
* Parameter is:
* - id (default: false)
*/
public function truncateAction(): void {
$id = Minz_Request::paramInt('id');
$url_redirect = [
'c' => 'subscription',
'a' => 'index',
'params' => ['id' => $id],
];
if (!Minz_Request::isPost()) {
Minz_Request::forward($url_redirect, true);
}
$feedDAO = FreshRSS_Factory::createFeedDao();
$n = $feedDAO->truncate($id);
invalidateHttpCache();
if ($n === false) {
Minz_Request::bad(_t('feedback.sub.feed.error'), $url_redirect);
} else {
Minz_Request::good(_t('feedback.sub.feed.n_entries_deleted', $n), $url_redirect);
}
}
/**
* @return array{0:int,1:FreshRSS_Feed|null,2:int} Number of updated feeds, first feed or null, number of new articles
* @throws FreshRSS_BadUrl_Exception
*/
public static function actualizeFeeds(?int $feed_id = null, ?string $feed_url = null, ?int $maxFeeds = null, ?SimplePie $simplePiePush = null): array {
if (function_exists('set_time_limit')) {
@set_time_limit(300);
}
if (!is_int($feed_id) || $feed_id <= 0) {
$feed_id = null;
}
if (!is_string($feed_url) || trim($feed_url) === '') {
$feed_url = null;
}
if (!is_int($maxFeeds) || $maxFeeds <= 0) {
$maxFeeds = PHP_INT_MAX;
}
$feedDAO = FreshRSS_Factory::createFeedDao();
$entryDAO = FreshRSS_Factory::createEntryDao();
// Create a list of feeds to actualize.
$feeds = [];
if ($feed_id !== null || $feed_url !== null) {
$feed = $feed_id !== null ? $feedDAO->searchById($feed_id) : $feedDAO->searchByUrl($feed_url);
if ($feed !== null && $feed->id() > 0) {
$feeds[] = $feed;
$feed_id = $feed->id();
}
} else {
$feeds = $feedDAO->listFeedsOrderUpdate(-1);
// Hydrate category for each feed to avoid that each feed has to make an SQL request
$categories = [];
$catDAO = FreshRSS_Factory::createCategoryDao();
foreach ($catDAO->listCategories(false, false) as $category) {
$categories[$category->id()] = $category;
}
foreach ($feeds as $feed) {
$category = $categories[$feed->categoryId()] ?? null;
if ($category !== null) {
$feed->_category($category);
}
}
}
// WebSub (PubSubHubbub) support
$pubsubhubbubEnabledGeneral = FreshRSS_Context::systemConf()->pubsubhubbub_enabled;
$pshbMinAge = time() - (3600 * 24); //TODO: Make a configuration.
$updated_feeds = 0;
$nb_new_articles = 0;
foreach ($feeds as $feed) {
/** @var FreshRSS_Feed|null $feed */
$feed = Minz_ExtensionManager::callHook('feed_before_actualize', $feed);
if (null === $feed) {
continue;
}
$url = $feed->url(); //For detection of HTTP 301
$pubSubHubbubEnabled = $pubsubhubbubEnabledGeneral && $feed->pubSubHubbubEnabled();
if ($simplePiePush === null && $feed_id === null && $pubSubHubbubEnabled && ($feed->lastUpdate() > $pshbMinAge)) {
//$text = 'Skip pull of feed using PubSubHubbub: ' . $url;
//Minz_Log::debug($text);
//Minz_Log::debug($text, PSHB_LOG);
continue; //When PubSubHubbub is used, do not pull refresh so often
}
if ($feed->mute()) {
continue; //Feed refresh is disabled
}
$mtime = $feed->cacheModifiedTime() ?: 0;
$ttl = $feed->ttl();
if ($ttl === FreshRSS_Feed::TTL_DEFAULT) {
$ttl = FreshRSS_Context::userConf()->ttl_default;
}
if ($simplePiePush === null && $feed_id === null && (time() <= $feed->lastUpdate() + $ttl)) {
//Too early to refresh from source, but check whether the feed was updated by another user
$ε = 10; // negligible offset errors in seconds
if ($mtime <= 0 ||
$feed->lastUpdate() + $ε >= $mtime ||
time() + $ε >= $mtime + FreshRSS_Context::systemConf()->limits['cache_duration']) { // is cache still valid?
continue; //Nothing newer from other users
}
Minz_Log::debug('Feed ' . $feed->url(false) . ' was updated at ' . date('c', $feed->lastUpdate()) .
', and at ' . date('c', $mtime) . ' by another user; take advantage of newer cache.');
}
if (!$feed->lock()) {
Minz_Log::notice('Feed already being actualized: ' . $feed->url(false));
continue;
}
$feedIsNew = $feed->lastUpdate() <= 0;
$feedIsEmpty = false;
$feedIsUnchanged = false;
try {
if ($simplePiePush !== null) {
$simplePie = $simplePiePush; //Used by WebSub
} elseif ($feed->kind() === FreshRSS_Feed::KIND_HTML_XPATH) {
$simplePie = $feed->loadHtmlXpath();
if ($simplePie === null) {
throw new FreshRSS_Feed_Exception('HTML+XPath Web scraping failed for [' . $feed->url(false) . ']');
}
} elseif ($feed->kind() === FreshRSS_Feed::KIND_XML_XPATH) {
$simplePie = $feed->loadHtmlXpath();
if ($simplePie === null) {
throw new FreshRSS_Feed_Exception('XML+XPath parsing failed for [' . $feed->url(false) . ']');
}
} elseif ($feed->kind() === FreshRSS_Feed::KIND_JSON_DOTPATH) {
$simplePie = $feed->loadJson();
if ($simplePie === null) {
throw new FreshRSS_Feed_Exception('JSON dotpath parsing failed for [' . $feed->url(false) . ']');
}
} elseif ($feed->kind() === FreshRSS_Feed::KIND_JSONFEED) {
$simplePie = $feed->loadJson();
if ($simplePie === null) {
throw new FreshRSS_Feed_Exception('JSON Feed parsing failed for [' . $feed->url(false) . ']');
}
} else {
$simplePie = $feed->load(false, $feedIsNew);
}
if ($simplePie === null) {
// Feed is cached and unchanged
$newGuids = [];
$entries = [];
$feedIsEmpty = false; // We do not know
$feedIsUnchanged = true;
} else {
$newGuids = $feed->loadGuids($simplePie);
$entries = $feed->loadEntries($simplePie);
$feedIsEmpty = $simplePiePush !== null && empty($newGuids);
$feedIsUnchanged = false;
}
$mtime = $feed->cacheModifiedTime() ?: time();
} catch (FreshRSS_Feed_Exception $e) {
Minz_Log::warning($e->getMessage());
$feedDAO->updateLastUpdate($feed->id(), true);
if ($e->getCode() === 410) {
// HTTP 410 Gone
Minz_Log::warning('Muting gone feed: ' . $feed->url(false));
$feedDAO->mute($feed->id(), true);
}
$feed->unlock();
continue;
}
$needFeedCacheRefresh = false;
$nbMarkedUnread = 0;
if (count($newGuids) > 0) {
if ($feed->attributeBoolean('read_when_same_title_in_feed') === null) {
$readWhenSameTitleInFeed = (int)FreshRSS_Context::userConf()->mark_when['same_title_in_feed'];
} elseif ($feed->attributeBoolean('read_when_same_title_in_feed') === false) {
$readWhenSameTitleInFeed = 0;
} else {
$readWhenSameTitleInFeed = $feed->attributeInt('read_when_same_title_in_feed') ?? 0;
}
if ($readWhenSameTitleInFeed > 0) {
$titlesAsRead = array_flip($feedDAO->listTitles($feed->id(), $readWhenSameTitleInFeed));
} else {
$titlesAsRead = [];
}
$mark_updated_article_unread = $feed->attributeBoolean('mark_updated_article_unread') ?? FreshRSS_Context::userConf()->mark_updated_article_unread;
// For this feed, check existing GUIDs already in database.
$existingHashForGuids = $entryDAO->listHashForFeedGuids($feed->id(), $newGuids) ?: [];
/** @var array<string,bool> $newGuids */
$newGuids = [];
// Add entries in database if possible.
/** @var FreshRSS_Entry $entry */
foreach ($entries as $entry) {
if (isset($newGuids[$entry->guid()])) {
continue; //Skip subsequent articles with same GUID
}
$newGuids[$entry->guid()] = true;
$entry->_lastSeen($mtime);
if (isset($existingHashForGuids[$entry->guid()])) {
$existingHash = $existingHashForGuids[$entry->guid()];
if (strcasecmp($existingHash, $entry->hash()) !== 0) {
//This entry already exists but has been updated
$entry->_isUpdated(true);
//Minz_Log::debug('Entry with GUID `' . $entry->guid() . '` updated in feed ' . $feed->url(false) .
//', old hash ' . $existingHash . ', new hash ' . $entry->hash());
$entry->_isFavorite(null); // Do not change favourite state
$entry->_isRead($mark_updated_article_unread ? false : null); //Change is_read according to policy.
if ($mark_updated_article_unread) {
Minz_ExtensionManager::callHook('entry_auto_unread', $entry, 'updated_article');
}
$entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
if (!($entry instanceof FreshRSS_Entry)) {
// An extension has returned a null value, there is nothing to insert.
continue;
}
$entry->applyFilterActions($titlesAsRead);
if ($readWhenSameTitleInFeed > 0) {
$titlesAsRead[$entry->title()] = true;
}
if (!$entry->isRead()) {
$needFeedCacheRefresh = true; //Maybe
$nbMarkedUnread++;
}
// If the entry has changed, there is a good chance for the full content to have changed as well.
$entry->loadCompleteContent(true);
if (!$entryDAO->inTransaction()) {
$entryDAO->beginTransaction();
}
$entryDAO->updateEntry($entry->toArray());
}
} else {
$entry->_isUpdated(false);
$id = uTimeString();
$entry->_id($id);
$entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry);
if (!($entry instanceof FreshRSS_Entry)) {
// An extension has returned a null value, there is nothing to insert.
continue;
}
$entry->applyFilterActions($titlesAsRead);
if ($readWhenSameTitleInFeed > 0) {
$titlesAsRead[$entry->title()] = true;
}
if ($pubSubHubbubEnabled && !$simplePiePush) { //We use push, but have discovered an article by pull!
$text = 'An article was discovered by pull although we use PubSubHubbub!: Feed ' .
SimplePie_Misc::url_remove_credentials($url) .
' GUID ' . $entry->guid();
Minz_Log::warning($text, PSHB_LOG);
Minz_Log::warning($text);
$pubSubHubbubEnabled = false;
$feed->pubSubHubbubError(true);
}
if (!$entryDAO->inTransaction()) {
$entryDAO->beginTransaction();
}
$entryDAO->addEntry($entry->toArray(), true);
$nb_new_articles++;
}
}
// N.B.: Applies to _entry table and not _entrytmp:
$entryDAO->updateLastSeen($feed->id(), array_keys($newGuids), $mtime);
} elseif ($feedIsUnchanged) {
// Feed cache was unchanged, so mark as seen the same entries as last time
if (!$entryDAO->inTransaction()) {
$entryDAO->beginTransaction();
}
$entryDAO->updateLastSeenUnchanged($feed->id(), $mtime);
}
unset($entries);
if (rand(0, 30) === 1) { // Remove old entries once in 30.
if (!$entryDAO->inTransaction()) {
$entryDAO->beginTransaction();
}
$nb = $feed->cleanOldEntries();
if ($nb > 0) {
$needFeedCacheRefresh = true;
}
}
$feedDAO->updateLastUpdate($feed->id(), false, $mtime);
if ($feed->keepMaxUnread() !== null && ($feed->nbNotRead() + $nbMarkedUnread > $feed->keepMaxUnread())) {
Minz_Log::debug('Existing unread entries (' . ($feed->nbNotRead() + $nbMarkedUnread) . ') exceeding max number of ' .
$feed->keepMaxUnread() . ' for [' . $feed->url(false) . ']');
$needFeedCacheRefresh |= ($feed->markAsReadMaxUnread() != false);
}
if ($simplePiePush === null) {
// Do not call for WebSub events, as we do not know the list of articles still on the upstream feed.
$needFeedCacheRefresh |= ($feed->markAsReadUponGone($feedIsEmpty, $mtime) != false);
}
if ($needFeedCacheRefresh) {
$feedDAO->updateCachedValues($feed->id());
}
if ($entryDAO->inTransaction()) {
$entryDAO->commit();
}
$feedProperties = [];
if ($pubsubhubbubEnabledGeneral && $feed->hubUrl() && $feed->selfUrl()) { //selfUrl has priority for WebSub
if ($feed->selfUrl() !== $url) { // https://github.com/pubsubhubbub/PubSubHubbub/wiki/Moving-Feeds-or-changing-Hubs
$selfUrl = checkUrl($feed->selfUrl());
if ($selfUrl) {
Minz_Log::debug('WebSub unsubscribe ' . $feed->url(false));
if (!$feed->pubSubHubbubSubscribe(false)) { //Unsubscribe
Minz_Log::warning('Error while WebSub unsubscribing from ' . $feed->url(false));
}
$feed->_url($selfUrl, false);
Minz_Log::notice('Feed ' . $url . ' canonical address moved to ' . $feed->url(false));
$feedDAO->updateFeed($feed->id(), ['url' => $feed->url()]);
}
}
} elseif ($feed->url() !== $url) { // HTTP 301 Moved Permanently
Minz_Log::notice('Feed ' . SimplePie_Misc::url_remove_credentials($url) .
' moved permanently to ' . SimplePie_Misc::url_remove_credentials($feed->url(false)));
$feedProperties['url'] = $feed->url();
}
if ($simplePie != null) {
if ($feed->name(true) === '') {
//HTML to HTML-PRE //ENT_COMPAT except '&'
$name = strtr(html_only_entity_decode($simplePie->get_title()), ['<' => '<', '>' => '>', '"' => '"']);
$feed->_name($name);
$feedProperties['name'] = $feed->name(false);
}
if (trim($feed->website()) === '') {
$website = html_only_entity_decode($simplePie->get_link());
$feed->_website($website == '' ? $feed->url() : $website);
$feedProperties['website'] = $feed->website();
$feed->faviconPrepare();
}
if (trim($feed->description()) === '') {
$description = html_only_entity_decode($simplePie->get_description());
if ($description !== '') {
$feed->_description($description);
$feedProperties['description'] = $feed->description();
}
}
}
if (!empty($feedProperties)) {
$ok = $feedDAO->updateFeed($feed->id(), $feedProperties);
if (!$ok && $feedIsNew) {
//Cancel adding new feed in case of database error at first actualize
$feedDAO->deleteFeed($feed->id());
$feed->unlock();
break;
}
}
$feed->faviconPrepare();
if ($pubsubhubbubEnabledGeneral && $feed->pubSubHubbubPrepare()) {
Minz_Log::notice('WebSub subscribe ' . $feed->url(false));
if (!$feed->pubSubHubbubSubscribe(true)) { //Subscribe
Minz_Log::warning('Error while WebSub subscribing to ' . $feed->url(false));
}
}
$feed->unlock();
$updated_feeds++;
unset($feed);
gc_collect_cycles();
if ($updated_feeds >= $maxFeeds) {
break;
}
}
return [$updated_feeds, reset($feeds) ?: null, $nb_new_articles];
}
/**
* @return int|false The number of articles marked as read, of false if error
*/
private static function keepMaxUnreads() {
$affected = 0;
$entryDAO = FreshRSS_Factory::createEntryDao();
$newUnreadEntriesPerFeed = $entryDAO->newUnreadEntriesPerFeed();
$feedDAO = FreshRSS_Factory::createFeedDao();
$feeds = $feedDAO->listFeedsOrderUpdate(-1);
foreach ($feeds as $feed) {
if (!empty($newUnreadEntriesPerFeed[$feed->id()]) && $feed->keepMaxUnread() !== null &&
($feed->nbNotRead() + $newUnreadEntriesPerFeed[$feed->id()] > $feed->keepMaxUnread())) {
Minz_Log::debug('New unread entries (' . ($feed->nbNotRead() + $newUnreadEntriesPerFeed[$feed->id()]) . ') exceeding max number of ' .
$feed->keepMaxUnread() . ' for [' . $feed->url(false) . ']');
$n = $feed->markAsReadMaxUnread();
if ($n === false) {
$affected = false;
break;
} else {
$affected += $n;
}
}
}
if ($feedDAO->updateCachedValues() === false) {
$affected = false;
}
return $affected;
}
/**
* Auto-add labels to new articles.
* @param int $nbNewEntries The number of top recent entries to process.
* @return int|false The number of new labels added, or false in case of error.
*/
private static function applyLabelActions(int $nbNewEntries) {
$tagDAO = FreshRSS_Factory::createTagDao();
$labels = FreshRSS_Context::labels();
$labels = array_filter($labels, static function (FreshRSS_Tag $label) {
return !empty($label->filtersAction('label'));
});
if (count($labels) <= 0) {
return 0;
}
$entryDAO = FreshRSS_Factory::createEntryDao();
/** @var array<array{id_tag:int,id_entry:string}> $applyLabels */
$applyLabels = [];
foreach (FreshRSS_Entry::fromTraversable($entryDAO->selectAll($nbNewEntries)) as $entry) {
foreach ($labels as $label) {
$label->applyFilterActions($entry, $applyLabel);
if ($applyLabel) {
$applyLabels[] = [
'id_tag' => $label->id(),
'id_entry' => $entry->id(),
];
}
}
}
return $tagDAO->tagEntries($applyLabels);
}
public static function commitNewEntries(): void {
$entryDAO = FreshRSS_Factory::createEntryDao();
['all' => $nbNewEntries, 'unread' => $nbNewUnreadEntries] = $entryDAO->countNewEntries();
if ($nbNewEntries > 0) {
if (!$entryDAO->inTransaction()) {
$entryDAO->beginTransaction();
}
if ($entryDAO->commitNewEntries()) {
self::applyLabelActions($nbNewEntries);
if ($nbNewUnreadEntries > 0) {
self::keepMaxUnreads();
}
}
if ($entryDAO->inTransaction()) {
$entryDAO->commit();
}
}
}
/**
* This action actualizes entries from one or several feeds.
*
* Parameters are:
* - id (default: null): Feed ID, or set to -1 to commit new articles to the main database
* - url (default: null): Feed URL (instead of feed ID)
* - maxFeeds (default: 10): Max number of feeds to refresh
* - noCommit (default: 0): Set to 1 to prevent committing the new articles to the main database
* If id and url are not specified, all the feeds are actualized, within the limits of maxFeeds.
*/
public function actualizeAction(): int {
Minz_Session::_param('actualize_feeds', false);
$id = Minz_Request::paramInt('id');
$url = Minz_Request::paramString('url');
$maxFeeds = Minz_Request::paramInt('maxFeeds') ?: 10;
$noCommit = ($_POST['noCommit'] ?? 0) == 1;
if ($id === -1 && !$noCommit) { //Special request only to commit & refresh DB cache
$updated_feeds = 0;
$feed = null;
self::commitNewEntries();
} else {
if ($id === 0 && $url === '') {
// Case of a batch refresh (e.g. cron)
$databaseDAO = FreshRSS_Factory::createDatabaseDAO();
$databaseDAO->minorDbMaintenance();
Minz_ExtensionManager::callHookVoid('freshrss_user_maintenance');
FreshRSS_feed_Controller::commitNewEntries();
FreshRSS_category_Controller::refreshDynamicOpmls();
}
[$updated_feeds, $feed, $nbNewArticles] = self::actualizeFeeds($id, $url, $maxFeeds);
if (!$noCommit && $nbNewArticles > 0) {
FreshRSS_feed_Controller::commitNewEntries();
}
}
if (Minz_Request::paramBoolean('ajax')) {
// Most of the time, ajax request is for only one feed. But since
// there are several parallel requests, we should return that there
// are several updated feeds.
Minz_Request::setGoodNotification(_t('feedback.sub.feed.actualizeds'));
// No layout in ajax request.
$this->view->_layout(null);
} elseif ($feed instanceof FreshRSS_Feed) {
// Redirect to the main page with correct notification.
Minz_Request::good(_t('feedback.sub.feed.actualized', $feed->name()), [
'params' => ['get' => 'f_' . $id]
]);
} elseif ($updated_feeds >= 1) {
Minz_Request::good(_t('feedback.sub.feed.n_actualized', $updated_feeds), []);
} else {
Minz_Request::good(_t('feedback.sub.feed.no_refresh'), []);
}
return $updated_feeds;
}
/**
* @throws Minz_ConfigurationNamespaceException
* @throws Minz_PDOConnectionException
*/
public static function renameFeed(int $feed_id, string $feed_name): bool {
if ($feed_id <= 0 || $feed_name === '') {
return false;
}
FreshRSS_UserDAO::touch();
$feedDAO = FreshRSS_Factory::createFeedDao();
return $feedDAO->updateFeed($feed_id, ['name' => $feed_name]) === 1;
}
public static function moveFeed(int $feed_id, int $cat_id, string $new_cat_name = ''): bool {
if ($feed_id <= 0 || ($cat_id <= 0 && $new_cat_name === '')) {
return false;
}
FreshRSS_UserDAO::touch();
$catDAO = FreshRSS_Factory::createCategoryDao();
if ($cat_id > 0) {
$cat = $catDAO->searchById($cat_id);
$cat_id = $cat === null ? 0 : $cat->id();
}
if ($cat_id <= 1 && $new_cat_name != '') {
$cat_id = $catDAO->addCategory(['name' => $new_cat_name]);
}
if ($cat_id <= 1) {
$catDAO->checkDefault();
$cat_id = FreshRSS_CategoryDAO::DEFAULTCATEGORYID;
}
$feedDAO = FreshRSS_Factory::createFeedDao();
return $feedDAO->updateFeed($feed_id, ['category' => $cat_id]) === 1;
}
/**
* This action changes the category of a feed.
*
* This page must be reached by a POST request.
*
* Parameters are:
* - f_id (default: false)
* - c_id (default: false)
* If c_id is false, default category is used.
*
* @todo should handle order of the feed inside the category.
*/
public function moveAction(): void {
if (!Minz_Request::isPost()) {
Minz_Request::forward(['c' => 'subscription'], true);
}
$feed_id = Minz_Request::paramInt('f_id');
$cat_id = Minz_Request::paramInt('c_id');
if (self::moveFeed($feed_id, $cat_id)) {
// TODO: return something useful
// Log a notice to prevent "Empty IF statement" warning in PHP_CodeSniffer
Minz_Log::notice('Moved feed `' . $feed_id . '` in the category `' . $cat_id . '`');
} else {
Minz_Log::warning('Cannot move feed `' . $feed_id . '` in the category `' . $cat_id . '`');
Minz_Error::error(404);
}
}
public static function deleteFeed(int $feed_id): bool {
FreshRSS_UserDAO::touch();
$feedDAO = FreshRSS_Factory::createFeedDao();
if ($feedDAO->deleteFeed($feed_id)) {
// TODO: Delete old favicon
// Remove related queries
/** @var array<array{'get'?:string,'name'?:string,'order'?:string,'search'?:string,'state'?:int,'url'?:string}> $queries */
$queries = remove_query_by_get('f_' . $feed_id, FreshRSS_Context::userConf()->queries);
FreshRSS_Context::userConf()->queries = $queries;
FreshRSS_Context::userConf()->save();
return true;
}
return false;
}
/**
* This action deletes a feed.
*
* This page must be reached by a POST request.
* If there are related queries, they are deleted too.
*
* Parameters are:
* - id (default: false)
*/
public function deleteAction(): void {
$from = Minz_Request::paramString('from');
$id = Minz_Request::paramInt('id');
switch ($from) {
case 'stats':
$redirect_url = ['c' => 'stats', 'a' => 'idle'];
break;
case 'normal':
$get = Minz_Request::paramString('get');
if ($get) {
$redirect_url = ['c' => 'index', 'a' => 'normal', 'params' => ['get' => $get]];
} else {
$redirect_url = ['c' => 'index', 'a' => 'normal'];
}
break;
default:
$redirect_url = ['c' => 'subscription', 'a' => 'index'];
if (!Minz_Request::isPost()) {
Minz_Request::forward($redirect_url, true);
}