forked from feediron/ttrss_plugin-feediron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.php
1134 lines (1015 loc) · 38 KB
/
init.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
require_once "RecipeManager.php";
require_once "fi_Logger.php";
require_once "fi_Functions.php";
require_once "Json.php";
require_once "User.php";
require_once "PrefTab.php";
//Load Composer autoloader hiding errors
@include('vendor/autoload.php');
//Load Readability.php
use andreskrey\Readability\Readability as ReadabilityPHP;
use andreskrey\Readability\Configuration as ReadabilityPHPConf;
class Feediron extends Plugin implements IHandler
{
private $host;
private $charset;
private $json_error;
private $cache;
// Required API
function about()
{
return array(
1.20, // version
'Reforge your feeds', // description
'm42e', // author
false, // is_system
);
}
// Required API
function api_version()
{
return 2;
}
// Required API for adding the hooks
function init($host)
{
$this->host = $host;
$host->add_hook($host::HOOK_PREFS_TABS, $this);
$host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
}
// Required API, Django...
function csrf_ignore($method)
{
$csrf_ignored = array("index", "edit");
return array_search($method, $csrf_ignored) !== false;
}
// Allow only in active sessions
function before($method)
{
if ($_SESSION["uid"])
{
return true;
}
return false;
}
// Required API
function after()
{
return true;
}
// The hook to filter the article. Called for each article
function hook_article_filter($article)
{
Feediron_Logger::get()->set_log_level(0);
$link = $article["link"];
if ($link === null) {
return $article;
};
$config = $this->getConfigSection($link);
if ($config === false) {
$config = $this->getConfigSection($article['author']);
}
if ($config !== false)
{
if (version_compare(VERSION, '1.14.0', '<=')){
if (strpos($article['plugin_data'], $articleMarker) !== false)
{
return $article;
}
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "Article was not fetched yet: ".$link);
$article['plugin_data'] = $this->addArticleMarker($article, $articleMarker);
}
$link = $this->reformatUrl($article['link'], $config);
$NewContent = $this->getNewContent($link, $config);
// If xpath tags are to replaced tags completely
if( !empty( $NewContent['tags'] ) AND $NewContent['replace-tags'] ){
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "Replacing Tags");
// Overwrite Article tags, Also ensure no empty tags are returned
$article['tags'] = array_filter( $NewContent['tags'] );
// If xpath tags are to be prepended to existing tags
} elseif ( !empty( $NewContent['tags'] ) ) {
// Merge with in front of Article tags to avoid empty array issues
$taglist = array_merge($NewContent['tags'], $article['tags']);
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "Merging Tags: ".implode( ", ", $taglist));
// Ensure no empty tags are returned
$article['tags'] = array_filter( $taglist );
}
if (isset($NewContent['content']) && '' !== $NewContent['content']) $article['content'] = $NewContent['content'];
}
return $article;
}
//Creates a marker for the article processed with specific config
function getMarker($article, $config){
$articleMarker = mb_strtolower(get_class($this));
$articleMarker .= ",".$article['owner_uid'].",".md5(print_r($config, true)).":";
return $articleMarker;
}
// Removes old marker and adds new one
function addArticleMarker($article, $marker){
return $marker.preg_replace('/'.get_class($this).','.$article['owner_id'].',.*?:/','',$article['plugin_data']);
}
function getConfigSection($url)
{
if ($url === null) { return false; };
$data = $this->getConfig();
if(is_array($data)){
foreach ($data as $urlpart=>$config) { // Check for multiple URL's
foreach (explode("|", $urlpart) as $suburl){
if (preg_match('~' . preg_quote($suburl, '~') . '~', $url)) {
Feediron_Logger::get()->log_object(Feediron_Logger::LOG_TEST, "Config found for $suburl", $config);
return $config; // Return config if any url matched
}
}
}
}
return false;
}
// Load config
function getConfig()
{
$json_conf = $this->host->get($this, 'json_conf');
$data = json_decode($json_conf, true);
if(Feediron_Logger::get()->get_log_level() == 0){
Feediron_Logger::get()->set_log_level((isset($data['debug']) && $data['debug'])||!is_array($data));
}
if(!is_array($data)){
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "No Config found");
}
return $data;
}
// reformat an url with a given config
function reformatUrl($url, $config)
{
$link = trim($url);
if(is_array($config['reformat']))
{
$link = $this->reformat($link, $config['reformat']);
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "Reformated url: ".$link);
}
return $link;
}
// reformat a string with given options
function reformat($string, $options)
{
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Reformat ", $string);
foreach($options as $option)
{
Feediron_Logger::get()->log_object(Feediron_Logger::LOG_VERBOSE, "Reformat step with option ", $option);
switch($option['type'])
{
case 'replace':
$string = str_replace($option['search'], $option['replace'], $string);
break;
case 'regex':
$string = preg_replace($option['pattern'], $option['replace'], $string);
break;
}
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Step result ", $string);
}
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Result ", $string);
return $string;
}
// grep new content for a link and aplly config
function getNewContent($link, $config)
{
$links = $this->getLinks($link, $config);
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "Fetching ".count($links)." links");
Feediron_Logger::get()->log(Feediron_Logger::LOG_TEST, "Fetching ".count($links)." links", join("\n", $links));
$NewContent['content'] = "";
$NewContent['replace-tags'] = $config['replace-tags'];
foreach($links as $lnk)
{
$html = $this->getArticleContent($lnk, $config);
if( isset( $config['tags'] ) )
{
$NewContent['tags'] = $this->getArticleTags($html, $config['tags']);
}
Feediron_Logger::get()->log_html(Feediron_Logger::LOG_TEST, "Original Source ".$lnk.":", $html);
$html = $this->processArticle($html, $config, $lnk);
Feediron_Logger::get()->log_html(Feediron_Logger::LOG_TEST, "Modified Source ".$lnk.":", $html);
$NewContent['content'] .= $html;
}
return $NewContent;
}
//extract links for multipage articles
function getLinks($link, $config){
if (isset($config['multipage']))
{
$links = $this->fetch_links($link, $config);
}
else
{
$links = array($link);
}
return $links;
}
function getArticleContent($link, $config)
{
if(is_array($this->cache) && array_key_exists($link, $this->cache)){
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Fetching from cache");
return $this->cache[$link];
}
list($html, $content_type) = $this->get_content($link);
if (0 !== strncmp($content_type, 'text/', 5) && 0 !== strncmp($content_type, 'application/', 12))
{
// Likely an image/jpeg, etc ... Something not processable.
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "Response is _NOT_ HTML/XML/TEXT: $content_type");
return '';
}
$this->charset = false;
// Array of valid charsets for tidy functions
$valid_charsets = array(
"raw" => array("raw"),
"ascii" => array("ascii"),
"latin0" => array("latin0"),
"latin1" => array("latin1"),
"utf8" => array("utf8", "UTF-8", "ISO88591", "ISO-8859-1", "ISO8859-1"),
"iso2022" => array("iso2022"),
"mac" => array("mac"),
"win1252" => array("win1252"),
"ibm858" => array("ibm858"),
"utf16le" => array("utf16le"),
"utf16be" => array("utf16be"),
"utf16" => array("utf16"),
"big5" => array("big5"),
"shiftjis" => array("shiftjis")
);
if (!isset($config['force_charset']))
{
if ($content_type)
{
preg_match('/charset=(\S+)/', $content_type, $matches);
if (isset($matches[1]) && !empty($matches[1])) {
$this->charset = str_replace('"', "", html_entity_decode($matches[1]));
}
}
} elseif ( isset( $config['force_charset'] ) ) {
// use forced charset
$this->charset = $config['force_charset'];
} elseif ( mb_detect_encoding($html, 'UTF-8', true) == 'UTF-8' ) {
$this->charset = 'UTF-8';
}
Feediron_Logger::get()->log(Feediron_Logger::LOG_TEST, "charset:", $this->charset);
if ($this->charset && isset($config['force_unicode']) && $config['force_unicode'])
{
$html = iconv($this->charset, 'utf-8', $html);
$this->charset = 'utf-8';
Feediron_Logger::get()->log_html(Feediron_Logger::LOG_VERBOSE, "Changed charset to utf-8:", $html);
}
// Map Charset to valid_charsets
if ( isset($this->charset) ){
foreach($valid_charsets as $index => $alias) {
foreach($alias as $key => $value) {
if ($value == $this->charset) {
$this->charset = $index;
Feediron_Logger::get()->log(Feediron_Logger::LOG_TEST, "Valid Charset detected and mapped", $this->charset);
break 2;
}
}
}
}
// Use PHP tidy to fix source page if option tidy-source called
if (function_exists('tidy_parse_string') && $config['tidy-source'] == true && $this->charset !== false){
// Use forced or discovered charset of page
$tidy = tidy_parse_string($html, array('indent'=>true, 'show-body-only' => true), str_replace(["-", "–"], '', $this->charset));
$tidy->cleanRepair();
$html = $tidy->value;
}
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Writing into cache");
$this->cache[$link] = $html;
return $html;
}
function getArticleTags($html, $config)
{
switch ($config['type'])
{
case 'xpath':
$tags = $this->perform_tag_xpath($html, $config);
break;
case 'regex':
$tags = $this->perform_tag_regex($html, $config);
break;
case 'search':
$tags = $this->perform_tag_search($html, $config);
break;
default:
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "Unrecognized option: ".$config['type']);
break;
}
if(!$tags){
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "No tags saved");
return;
}
// Split tags
if( isset( $config['split'] ) )
{
$split_tags = array();
foreach( $tags as $key=>$tag )
{
$split_tags = array_merge($split_tags, explode( $config['split'], $tag ) );
}
$tags = $split_tags;
}
// Loop through tags indivdually
foreach( $tags as $key=>$tag )
{
// If set perform modify
if(is_array($config['modify']))
{
$tag = $this->reformat($tag, $config['modify']);
}
// Strip tags of html and ensure plain text
$tags[$key] = trim( preg_replace('/\s+/', ' ', strip_tags( $tag ) ) );
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "Tag saved: ".$tags[$key]);
}
$tags = array_filter($tags);
return $tags;
}
function perform_tag_regex($html, $config)
{
if(!is_array($config['pattern'])){
$patterns = array($config['pattern']);
}else{
$patterns = $config['pattern'];
}
if( !isset( $config['index'] ) ){
$index = 0;
} else {
$index = $config['index'];
}
// loop through regex pattern array
foreach( $patterns as $key=>$pattern ){
preg_match($pattern, $html, $match);
$tags[$key] = $match[$index];
}
return $tags;
}
function perform_tag_search($html, $config)
{
if(!is_array($config['pattern'])){
$patterns = array($config['pattern']);
}else{
$patterns = $config['pattern'];
}
if(!is_array($config['match'])){
$matches = array($config['match']);
}else{
$matches = $config['match'];
}
if( count($patterns) != count($matches) ){
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "Number of Patterns ".count($patterns)." doesn't equal number of Matches ".count($matches));
return;
}
$matches = array_combine ( $patterns, $matches );
// loop through regex pattern array
foreach( $matches as $pattern=>$match ){
if( preg_match($pattern, $html) && substr( $match, 0, 1 ) != "!" ){
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Tag search match", $pattern);
$tags[$pattern] .= $match;
} else if( !preg_match($pattern, $html) && substr( $match, 0, 1 ) == "!" ) {
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Tag inverted search match", $pattern);
$tags[$pattern] .= substr( $match, 1 );
}
}
return array_values( $tags );
}
function perform_tag_xpath($html, $config)
{
if(!is_array($config['xpath'])){
$xpaths = array($config['xpath']);
}else{
$xpaths = $config['xpath'];
}
// loop through xpath array
foreach( $xpaths as $key=>$xpath )
{
// set xpath in config
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Tag xpath", $xpath);
$newtag = $this->performXpath( $html, $config );
// Filter bad tags
if( $newtag && $newtag !== $html ){
$tags[$key] .= $newtag;
Feediron_Logger::get()->log_html(Feediron_Logger::LOG_TTRSS, "Tag data found", $tags[$key]);
}
}
return $tags;
}
function get_content($link)
{
global $fetch_last_content_type;
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, $link);
if (version_compare(VERSION, '1.7.9', '>='))
{
$html = fetch_file_contents($link);
$content_type = $fetch_last_content_type;
}
else
{
// fallback to file_get_contents()
$html = file_get_contents($link);
// try to fetch charset from HTTP headers
$headers = $http_response_header;
$content_type = false;
foreach ($headers as $h)
{
if (substr(strtolower($h), 0, 13) == 'content-type:')
{
$content_type = substr($h, 14);
// don't break here to find LATEST (if redirected) entry
}
}
}
return array( $html, $content_type);
}
function fetch_links($link, $config, $seenlinks = array())
{
Feediron_Logger::get()->log(Feediron_Logger::LOG_TEST, "fetching links from :".$lnk);
$html = $this->getArticleContent($link, $config);
$links = $this->extractlinks($html, $config);
if (count($links) == 0)
{
return array($link);
}
$links = $this->fixlinks($link, $links);
if (count(array_intersect($seenlinks, $links)) != 0)
{
Feediron_Logger::get()->log_object(Feediron_Logger::LOG_VERBOSE, "Break infinite loop for recursive multipage, link intersection",array_intersect($seenlinks, $links));
return array($link);
}
foreach ($links as $lnk)
{
Feediron_Logger::get()->log(Feediron_Logger::LOG_TEST, "link:".$lnk);
/* If recursive mode is active fetch links from newly fetched link */
if(isset($config['multipage']['recursive']) && $config['multipage']['recursive'])
{
$links = $this->fetch_links($lnk, $config, array($links, $link));
}
}
if(isset($config['multipage']['append']) && $config['multipage']['append'])
{
array_unshift($links, $link);
}
/* Avoid link dupplication */
$links = array_unique($links);
return $links;
}
function extractlinks($html, $config)
{
$doc = $this->getDOM($html);
$links = array();
$xpath = new DOMXPath($doc);
/* Extract the links based on xpath */
$entries = $xpath->query('(//'.$config['multipage']['xpath'].')');
if ($entries->length < 1){
return array();
}
if($this->loglevel == Feediron_Logger::LOG_VERBOSE){
$log_entries = array_map( array($this, 'getHtmlNode') , $entries);
Feediron_Logger::get()->log_html(Feediron_Logger::LOG_VERBOSE, "Found ".count($entries)." link elements:", join("\n", $log_entries));
}
foreach($entries as $entry)
{
$links[] = $entry->getAttribute('href');
}
return $links;
}
function getHtmlNode($node){
if (is_object($node)){
$newdoc = new DOMDocument();
if ($node->nodeType == XML_ATTRIBUTE_NODE) {
// appendChild will fail, so make it a text node
$imported = $newdoc->createTextNode($node->value);
} else {
$cloned = $node->cloneNode(true);
$imported = $newdoc->importNode($cloned,true);
}
$newdoc->appendChild($imported);
return $newdoc->saveHTML();
} else {
return $node;
}
}
function getDOM($html){
$doc = new DOMDocument();
if ($this->charset) {
$html = '<?xml encoding="' . $this->charset . '">' . $html;
}
libxml_use_internal_errors(true);
$doc->loadHTML($html);
if(!$doc)
{
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "The content is not a valid xml format");
if($this->debug)
{
foreach (libxml_get_errors() as $value)
{
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, $value);
}
}
return new DOMDocument();
}
return $doc;
}
function fixlinks($link, $links)
{
$retlinks = array();
foreach($links as $lnk)
{
$retlinks[] = $this->resolve_url($link, $lnk);
}
return $retlinks;
}
/**
* Does the reverse of parse_url (creates a URL from an associative array of components)
*/
function unparse_url($parsed_url) {
$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
$port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
$user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
$pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : '';
$pass = ($user || $pass) ? "$pass@" : '';
$path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
$query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
$fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
return "$scheme$user$pass$host$port$path$query$fragment";
}
/**
* Resolve a URL relative to a base path. Based on RFC 2396 section 5.2.
*/
function resolve_url($base, $url) {
if (!strlen($base)) return $url;
// Step 2
if (!strlen($url)) return $base;
// Step 3
if (preg_match('!^[a-z]+:!i', $url)) return $url;
$base = parse_url($base);
if ($url{0} == "#") {
// Step 2 (fragment)
$base['fragment'] = substr($url, 1);
return $this->unparse_url($base);
}
unset($base['fragment']);
unset($base['query']);
if (substr($url, 0, 2) == "//") {
// Step 4
return $this->unparse_url(array(
'scheme'=>$base['scheme'],
'path'=>substr($url,2),
));
} else if ($url{0} == "/") {
// Step 5
$base['path'] = $url;
} else {
// Step 6
$path = explode('/', isset($base['path']) ? $base['path'] : "");
$url_path = explode('/', $url);
// Step 6a: drop file from base
array_pop($path);
// Step 6b, 6c, 6e: append url while removing "." and ".." from
// the directory portion
$end = array_pop($url_path);
foreach ($url_path as $segment) {
if ($segment == '.') {
// skip
} else if ($segment == '..' && $path && $path[sizeof($path)-1] != '..') {
array_pop($path);
} else {
$path[] = $segment;
}
}
// Step 6d, 6f: remove "." and ".." from file portion
if ($end == '.') {
$path[] = '';
} else if ($end == '..' && $path && $path[sizeof($path)-1] != '..') {
$path[sizeof($path)-1] = '';
} else {
$path[] = $end;
}
// Step 6h
$base['path'] = join('/', $path);
}
// Step 7
return $this->unparse_url($base);
}
function processArticle($html, $config, $link)
{
switch ($config['type'])
{
case 'readability':
$html = $this->performReadability($html, $config, $link);
break;
case 'split':
$html = $this->performSplit($html, $config);
break;
case 'xpath':
$html = $this->performXpath($html, $config);
break;
default:
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "Unrecognized option: ".$config['type']);
break;
}
if(is_array($config['modify']))
{
$html = $this->reformat($html, $config['modify']);
}
// if we've got Tidy, let's clean it up for output
if (function_exists('tidy_parse_string') && $config['tidy'] !== false && $this->charset !== false) {
try {
$tidy = tidy_parse_string($html, array('indent'=>true, 'show-body-only' => true), str_replace(["-", "–"], '', $this->charset));
$tidy->cleanRepair();
$html = $tidy->value;
} catch (Exception $e) {
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Error running tidy", $e);
} catch (Throwable $t) {
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Error running tidy", $t);
}
}
return $html;
}
function performReadability($html, $config, $link){
if (class_exists(ReadabilityPHP::class)) {
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Using Readability.php");
$configuration = new ReadabilityPHPConf();
if( isset( $config['relativeurl'] ) ) {
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Readability.php fixing relative URLS ".$config['relativeurl']);
$configuration
->setFixRelativeURLs( true )
->setOriginalURL( $config['relativeurl'] );
}
if( isset( $config['normalize'] ) && is_bool( $config['normalize'] ) ) {
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Readability.php Normalizing content");
$configuration
->setNormalizeEntities( $config['normalize'] );
}
if( isset( $config['removebyline'] ) && is_bool( $config['removebyline'] ) ) {
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Readability.php Removing ByLine");
$configuration
->setArticleByLine( $config['removebyline'] );
}
//Load Readability with Configuration
$readability = new ReadabilityPHP( $configuration );
try {
$readability->parse($html);
} catch (Exception $e) {
//Return unmodified html if Readability.php fails
Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "Readability.php failed to find content");
return $html;
}
if( isset( $config['prependimage'] ) && ( $config['prependimage'] ) ) {
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Readability.php Prepending Main Image");
$image = $readability->getImage();
$content = '<img src="'.$image.'"></img>';
$content .= $readability->getContent();
}
elseif( isset( $config['mainimage'] ) && ( $config['mainimage'] ) ) {
$image = $readability->getImage();
$content = '<img src="'.$image.'"></img>';
}
elseif( isset( $config['appendimages'] ) && ( $config['apendimages'] ) ) {
$images = $readability->getImages();
$content = $readability->getContent();
foreach ( $images as $image ) {
$content.='<img src="'.$image.'"></img><br>';
}
}
elseif( isset( $config['allimages'] ) && ( $config['allimages'] ) ) {
$images = $readability->getImages();
foreach ( $images as $image ) {
$content.='<img src="'.$image.'"></img><br>';
}
} else {
$content = $readability->getContent();
}
}
else {
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Using Legacy Readability");
require_once 'php-readability/Readability.php';
require_once 'php-readability/JSLikeHTMLElement.php';
$readability = new Readability\Readability($html, $link);
$readability->debug = false;
$readability->convertLinksToFootnotes = true;
$result = $readability->init();
if (!$result) {
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Readability failed to find content");
return $html;
}
else {
$content = $readability->getContent()->innerHTML;
Feediron_Logger::get()->log_html(Feediron_Logger::LOG_VERBOSE, "Readability modified Source ".$lnk.":", $html);
}
}
// Perform xpath on readability output
if (isset($config['xpath'])){
$html = $this->performXpath($content, $config);
// If no xpath for readability output perform simple cleanup
} elseif(($cconfig = $this->getCleanupConfig($config))!== false) {
$html = $content;
foreach($cconfig as $cleanup){
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Cleaning up", $cleanup);
$html = preg_replace($cleanup, '', $html);
Feediron_Logger::get()->log_html(Feediron_Logger::LOG_VERBOSE, "cleanup result", $html);
}
} else {
// If no extra config just return the content
$html = $content;
}
return $html;
}
function performSplit($html, $config){
$orig_html = $html;
foreach($config['steps'] as $step)
{
Feediron_Logger::get()->log_object(Feediron_Logger::LOG_VERBOSE, "Perform step: ", $step);
if(isset($step['after']))
{
$result = preg_split ($step['after'], $html);
$html = $result[1];
}
if(isset($step['before']))
{
$result = preg_split ($step['before'], $html);
$html = $result[0];
}
Feediron_Logger::get()->log_html(Feediron_Logger::LOG_VERBOSE, "Step result", $html);
}
if(strlen($html) == 0)
{
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "removed all content, reverting");
return $orig_html;
}
if(($cconfig = $this->getCleanupConfig($config))!== false)
{
foreach($cconfig as $cleanup)
{
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Cleaning up", $cleanup);
$html = preg_replace($cleanup, '', $html);
Feediron_Logger::get()->log_html(Feediron_Logger::LOG_VERBOSE, "cleanup result", $html);
}
}
return $html;
}
function performXpath($html, $config)
{
$doc = $this->getDOM($html);
$basenode = false;
$xpathdom = new DOMXPath($doc);
if(!is_array($config['xpath'])){
$xpaths = array($config['xpath']);
}else{
$xpaths = $config['xpath'];
}
$htmlout = array();
foreach($xpaths as $key=>$xpath){
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "Perfoming xpath", $xpath);
$index = 0;
if(is_array($xpath) && array_key_exists('index', $xpath)){
$index = $xpath['index'];
$xpath = $xpath['xpath'];
}
$entries = $xpathdom->query('(//'.$xpath.')'); // find main DIV according to config
if ($entries->length > 0) {
$basenode = $entries->item($index);
}
if (!$basenode && count($xpaths) == ( $key + 1 )) {
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "removed all content, reverting");
return $html;
} elseif (!$basenode && count($xpaths) > 1){
continue;
}
Feediron_Logger::get()->log_html(Feediron_Logger::LOG_VERBOSE, "Extracted node", $this->getHtmlNode($basenode));
// remove nodes from cleanup configuration
$basenode = $this->cleanupNode($xpathdom, $basenode, $config);
//render nested nodes to html
$inner_html = $this->getInnerHtml($basenode);
if (!$inner_html){
//if there's no nested nodes, render the node itself
// Apply patch from https://github.com/m42e/ttrss_plugin-feediron/files/743016/feediron.txt
try{ $inner_html = $basenode->ownerDocument->saveXML($basenode); }
catch (Exception $e) { Feediron_Logger::get()->log(Feediron_Logger::LOG_TTRSS, "feediron error: {$e->getMessage()}"); }
}
array_push($htmlout, $inner_html);
}
$content = join((array_key_exists('join_element', $config)?$config['join_element']:''), $htmlout);
if(array_key_exists('start_element', $config)){
Feediron_Logger::get()->log_html(Feediron_Logger::LOG_VERBOSE, "Adding start element", $config['start_element']);
$content = $config['start_element'].$content;
}
if(array_key_exists('end_element', $config)){
Feediron_Logger::get()->log_html(Feediron_Logger::LOG_VERBOSE, "Adding end element", $config['end_element']);
$content = $content.$config['end_element'];
}
return $content;
}
function getInnerHtml( $node ) {
$innerHTML= '';
$children = $node->childNodes;
foreach ($children as $child) {
$innerHTML .= $child->ownerDocument->saveXML( $child );
}
return $innerHTML;
}
function cleanupNode($xpath, $basenode, $config)
{
if(($cconfig = $this->getCleanupConfig($config))!== false)
{
foreach ($cconfig as $cleanup)
{
Feediron_Logger::get()->log(Feediron_Logger::LOG_VERBOSE, "cleanup", $cleanup);
if(strpos($cleanup, "./") !== 0)
{
$cleanup = '//'.$cleanup;
}
$nodelist = $xpath->query($cleanup, $basenode);
foreach ($nodelist as $node)
{
if ($node instanceof DOMAttr)
{
$node->ownerElement->removeAttributeNode($node);
}
else
{
$node->parentNode->removeChild($node);
}
}
Feediron_Logger::get()->log_html(Feediron_Logger::LOG_VERBOSE, "Node after cleanup", $this->getHtmlNode($basenode));
}
}
return $basenode;
}
function getCleanupConfig($config)
{
$cconfig = false;
if (isset($config['cleanup']))
{
$cconfig = $config['cleanup'];
if (!is_array($cconfig))
{
$cconfig = array($cconfig);
}
}
Feediron_Logger::get()->log_object(Feediron_Logger::LOG_VERBOSE, "Cleanup config", $cconfig);
return $cconfig;
}
function hook_prefs_tabs($args)
{
print '<div id="feedironConfigTab" dojoType="dijit.layout.ContentPane"
href="backend.php?op=feediron"
title="' . __('FeedIron') . '"></div>';
}
function index()
{
$pluginhost = PluginHost::getInstance();
$json_conf = $pluginhost->get($this, 'json_conf');
$test_conf = $pluginhost->get($this, 'test_conf');
print Feediron_PrefTab::get_pref_tab($json_conf, $test_conf);
}
/*
* Storing the json reformat data
*/
function save()
{
$json_conf = $_POST['json_conf'];
$json_reply = array();
Feediron_Json::format($json_conf);
header('Content-Type: application/json');
if (is_null(json_decode($json_conf)))
{
$json_reply['success'] = false;
$json_reply['errormessage'] = __('Invalid JSON! ').json_last_error_msg();
$json_reply['json_error'] = Feediron_Json::get_error();
echo json_encode($json_reply);
return false;
}
$this->host->set($this, 'json_conf', Feediron_Json::format($json_conf));
$json_reply['success'] = true;
$json_reply['message'] = __('Configuration saved.');
$json_reply['json_conf'] = Feediron_Json::format($json_conf);
echo json_encode($json_reply);
}
function export(){
$conf = $this->getConfig();
$recipe2export = $_POST['recipe'];