-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathsyndicatedpost.class.php
2440 lines (2091 loc) · 82.6 KB
/
syndicatedpost.class.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 dirname(__FILE__) . '/feedtime.class.php';
require_once dirname(__FILE__) . '/syndicatedpostterm.class.php';
require_once dirname(__FILE__) . '/syndicatedpostxpathquery.class.php';
/**
* class SyndicatedPost: FeedWordPress uses to manage the conversion of
* incoming items from the feed parser into posts for the WordPress
* database. It contains several internal management methods primarily
* of interest to someone working on the FeedWordPress source, as well
* as some utility methods for extracting useful data from many
* different feed formats, which may be useful to FeedWordPress users
* who make use of feed data in PHP add-ons and filters.
*
* @version 2017.1018
*/
class SyndicatedPost {
/** @var MagpieRSS|null MagpieRSS representation. */
var $item = null;
/** @var SimplePie_Item|null SimplePie_Item representation. */
var $entry = null;
var $link = null;
var $feed = null;
var $feedmeta = null;
var $xmlns = array();
var $post = array();
var $named = array();
var $preset_terms = array();
var $feed_terms = array();
var $_freshness = null;
var $_wp_id = null;
var $_wp_post = null;
/**
* SyndicatedPost constructor: Given a feed item and the source from
* which it was taken, prepare a post that can be inserted into the
* WordPress database on request, or updated in place if it has already
* been syndicated.
*
* @param array $item The item syndicated from the feed.
* @param SyndicatedLink $source The feed it was syndicated from.
*/
public function __construct( $item, $source ) {
if ( empty( $item ) and empty( $source ) )
return;
if ( is_array( $item )
and isset( $item['simplepie'] )
and isset( $item['magpie'] ) ) :
$this->entry = $item['simplepie'];
$this->item = $item['magpie'];
$item = $item['magpie'];
elseif ( is_a( $item, 'SimplePie_Item' ) ) :
$this->entry = $item;
// convert to Magpie for compat purposes
$mpie = new MagpieFromSimplePie( $source->simplepie, $this->entry );
$this->item = $mpie->get_item();
// done with conversion object
$mpie = NULL; unset( $mpie );
else :
$this->item = $item;
endif;
$this->link = $source;
$this->feed = $source->magpie;
$this->feedmeta = $source->settings;
FeedWordPress::diagnostic( 'feed_items', 'Considering item [' . $this->guid() . '] "' . $this->entry->get_title().'"');
# Dealing with namespaces can get so fucking fucked.
$this->xmlns['forward'] = $source->magpie->_XMLNS_FAMILIAR;
$this->xmlns['reverse'] = array();
foreach ( $this->xmlns['forward'] as $url => $ns ) :
if ( ! isset( $this->xmlns['reverse'][ $ns ] ) ) :
$this->xmlns['reverse'][ $ns ] = array();
endif;
$this->xmlns['reverse'][ $ns ][] = $url;
endforeach;
// Fucking SimplePie.
$this->xmlns['reverse']['rss'][] = '';
// Trigger global syndicated_item filter.
$changed = apply_filters( 'syndicated_item', $this->item, $this );
$this->item = $changed;
// Allow for feed-specific syndicated_item filters.
$changed = apply_filters(
"syndicated_item_" . $source->uri(),
$this->item,
$this
);
$this->item = $changed;
# Filters can halt further processing by returning NULL
if ( is_null( $this->item ) ) :
$this->post = NULL;
else :
# Note that nothing is run through esc_sql() here.
# That's deliberate. The escaping is done at the point
# of insertion, not here, to avoid double-escaping and
# to avoid screwing with syndicated_post filters
$this->post['post_title'] = apply_filters(
'syndicated_item_title',
$this->entry->get_title(),
$this
);
$this->named['author'] = apply_filters(
'syndicated_item_author',
$this->author(),
$this
);
// This just gives us an alphanumeric name for the author.
// We look up (or create) the numeric ID for the author
// in SyndicatedPost::add().
$this->post['post_content'] = apply_filters(
'syndicated_item_content',
$this->content(),
$this
);
$excerpt = apply_filters( 'syndicated_item_excerpt', $this->excerpt(), $this );
if ( !empty( $excerpt ) ):
$this->post['post_excerpt'] = $excerpt;
endif;
// Dealing with timestamps in WordPress is so fucking fucked.
$offset = (int) get_option( 'gmt_offset' ) * 60 * 60;
$post_date_gmt = $this->published( array( 'default' => -1 ) );
$post_modified_gmt = $this->updated( array( 'default' => -1 ) );
$this->post['post_date_gmt'] = gmdate( 'Y-m-d H:i:s', $post_date_gmt );
$this->post['post_date'] = gmdate( 'Y-m-d H:i:s', $post_date_gmt + $offset );
$this->post['post_modified_gmt'] = gmdate( 'Y-m-d H:i:s', $post_modified_gmt );
$this->post['post_modified'] = gmdate( 'Y-m-d H:i:s', $post_modified_gmt + $offset );
// Use feed-level preferences or the global default.
$this->post['post_status'] = $this->link->syndicated_status( 'post', 'publish' );
$this->post['comment_status'] = $this->link->syndicated_status( 'comment', 'closed' );
$this->post['ping_status'] = $this->link->syndicated_status( 'ping', 'closed' );
// Unique ID (hopefully a unique tag: URI); failing that, the permalink
$this->post['guid'] = apply_filters( 'syndicated_item_guid', $this->guid(), $this );
// User-supplied custom settings to apply to each post.
// Do first so that FWP-generated custom settings will
// overwrite if necessary; thus preventing any munging.
$postMetaIn = $this->link->postmeta( array( "parsed" => true ) );
$postMetaOut = array();
foreach ( $postMetaIn as $key => $meta ) :
$postMetaOut[ $key ] = $meta->do_substitutions( $this );
endforeach;
foreach ( $postMetaOut as $key => $values ) :
if ( is_null( $values ) ) { // have chosen to replace value with empty string
$values = [ '' ];
}
$this->post['meta'][ $key ] = array();
foreach ( $values as $value ) :
$this->post['meta'][ $key ][] = apply_filters( "syndicated_post_meta_{$key}", $value, $this );
endforeach;
endforeach;
// RSS 2.0 / Atom 1.0 enclosure support
$enclosures = $this->entry->get_enclosures();
if ( is_array( $enclosures ) ) : foreach ( $enclosures as $enclosure ) :
$this->post['meta']['enclosure'][] =
apply_filters( 'syndicated_item_enclosure_url', $enclosure->get_link(), $this ) . "\n".
apply_filters( 'syndicated_item_enclosure_length', $enclosure->get_length(), $this ) . "\n".
apply_filters( 'syndicated_item_enclosure_type', $enclosure->get_type(), $this );
endforeach; endif;
// In case you want to point back to the blog this was
// syndicated from.
$sourcemeta['syndication_source'] = apply_filters(
'syndicated_item_source_title',
$this->link->name(),
$this
);
$sourcemeta['syndication_source_uri'] = apply_filters(
'syndicated_item_source_link',
$this->link->homepage(),
$this
);
$sourcemeta['syndication_source_id'] = apply_filters(
'syndicated_item_source_id',
$this->link->guid(),
$this
);
// Make use of atom:source data, if present in an aggregated feed
$entry_source = $this->source();
if ( ! is_null( $entry_source ) ) :
foreach ( $entry_source as $what => $value ) :
if ( ! is_null( $value ) ) :
if ( 'title' == $what ) : $key = 'syndication_source';
elseif ( 'feed' == $what ) : $key = 'syndication_feed';
else : $key = "syndication_source_{$what}";
endif;
$sourcemeta["{$key}_original"] = apply_filters(
'syndicated_item_original_source_' . $what,
$value,
$this
);
endif;
endforeach;
endif;
foreach ( $sourcemeta as $meta_key => $value ) :
if ( !is_null( $value ) ) :
$this->post['meta'][ $meta_key ] = $value;
endif;
endforeach;
// Store information on human-readable and machine-readable comment URIs
// Human-readable comment URI
$commentLink = apply_filters( 'syndicated_item_comments', $this->comment_link(), $this );
if ( ! is_null( $commentLink) ) : $this->post['meta']['rss:comments'] = $commentLink; endif;
// Machine-readable content feed URI
$commentFeed = apply_filters( 'syndicated_item_commentrss', $this->comment_feed(), $this );
if ( ! is_null( $commentFeed ) ) : $this->post['meta']['wfw:commentRSS'] = $commentFeed; endif;
// Yeah, yeah, now I know that it's supposed to be
// wfw:commentRss. Oh well. Path dependence, sucka.
// Store information to identify the feed that this came from
if ( isset( $this->feedmeta['link/uri'] ) ) :
$this->post['meta']['syndication_feed'] = $this->feedmeta['link/uri'];
endif;
if ( isset( $this->feedmeta['link/id'] ) ) :
$this->post['meta']['syndication_feed_id'] = $this->feedmeta['link/id'];
endif;
if ( isset( $this->item['source_link_self'] ) ) :
$this->post['meta']['syndication_feed_original'] = $this->item['source_link_self'];
endif;
// In case you want to know the external permalink...
$this->post['meta']['syndication_permalink'] = apply_filters( 'syndicated_item_link', $this->permalink() );
// Store a hash of the post content for checking whether something needs to be updated
$this->post['meta']['syndication_item_hash'] = $this->update_hash();
// Categories, Tags, and other Terms: from settings assignments (global settings, subscription settings),
// and from feed assignments (item metadata, post content)
$this->preset_terms = apply_filters( 'syndicated_item_preset_terms', $this->get_terms_from_settings(), $this );
$this->feed_terms = apply_filters( 'syndicated_item_feed_terms', $this->get_terms_from_feeds(), $this );
$this->post['post_type'] = apply_filters(
'syndicated_post_type',
$this->link->setting( 'syndicated post type', 'syndicated_post_type', 'post' ),
$this
);
endif;
} /* SyndicatedPost::__construct() */
#####################################
#### EXTRACT DATA FROM FEED ITEM ####
#####################################
function substitution_function ($name) {
$ret = NULL;
switch ($name) :
// Allowed PHP string functions
case 'trim':
case 'ltrim':
case 'rtrim':
case 'strtoupper':
case 'strtolower':
case 'urlencode':
case 'urldecode':
$ret = $name;
endswitch;
return $ret;
}
/**
* SyndicatedPost::query uses an XPath-like syntax to query arbitrary
* elements within the syndicated item.
*
* @param string $path
* @returns array of string values representing contents of matching
* elements or attributes
*/
public function query ($path) {
$xq = new SyndicatedPostXPathQuery(array("path" => $path));
$feedChannel = array_merge(
$this->get_feed_root_element(),
$this->get_feed_channel_elements()
);
$matches = $xq->match(array(
"type" => $this->link->simplepie->get_type(),
"xmlns" => $this->xmlns,
"map" => array(
"/" => array($this->entry->data),
"item" => array($this->entry->data),
"feed" => $feedChannel,
"channel" => $feedChannel
),
"context" => $this->entry->data,
"parent" => $feedChannel,
));
return $matches;
} /* SyndicatedPost::query() */
function get_feed_root_element () {
$matches = array();
foreach ($this->link->simplepie->data['child'] as $ns => $root) :
foreach ($root as $element => $data) :
$matches = array_merge($matches, $data);
endforeach;
endforeach;
return $matches;
} /* SyndicatedPost::get_feed_root_element() */
function get_feed_channel_elements () {
$rss = array(
SIMPLEPIE_NAMESPACE_RSS_090,
SIMPLEPIE_NAMESPACE_RSS_10,
'http://backend.userland.com/RSS2',
SIMPLEPIE_NAMESPACE_RSS_20,
);
$matches = array();
foreach ($rss as $ns) :
$data = $this->link->simplepie->get_feed_tags($ns, 'channel');
if ( !is_null($data)) :
$matches = array_merge($matches, $data);
endif;
endforeach;
return $matches;
} /* SyndicatedPost::get_feed_channel_elements() */
public function get_categories ($params = array()) {
return $this->entry->get_categories();
}
public function title ($params = array()) {
return $this->entry->get_title();
} /* SyndicatedPost::title () */
public function content ($params = array())
{
$params = wp_parse_args($params, array(
"full only" => false,
));
$content = NULL;
// FIXME: This is one of the main places in the code still using
// the outmoded SimplePie - to - Magpie construction. We could
// replace using SimplePie_Item::get_tags() here. (Or if really
// ambitious we could attempt to just use
// SimplePie_Item::get_content() with content-only set to TRUE
// and some sanitization in effect. -CJ 1jul14
// atom:content, standard method of providing full HTML content
// in Atom feeds.
if (isset($this->item['atom_content'])) :
$content = $this->item['atom_content'];
elseif (isset($this->item['atom']['atom_content'])) :
$content = $this->item['atom']['atom_content'];
// Some exotics: back in the day, before widespread convergence
// on content:encoding, some RSS feeds took advantage of XML
// namespaces to use an inline xhtml:body or xhtml:div element
// for full-content HTML. (E.g. Sam Ruby's feed, IIRC.)
elseif (isset($this->item['xhtml']['body'])) :
$content = $this->item['xhtml']['body'];
elseif (isset($this->item['xhtml']['div'])) :
$content = $this->item['xhtml']['div'];
// content:encoded, most common method of providing full HTML in
// RSS 2.0 feeds.
elseif (isset($this->item['content']['encoded']) and $this->item['content']['encoded']):
$content = $this->item['content']['encoded'];
// Fall back on elements that sometimes may contain full HTML
// but sometimes not.
elseif ( ! $params['full only']) :
// description element is sometimes used for full HTML
// sometimes for summary text in RSS. (By the letter of
// the standard, it should just be for summary text.)
if (isset($this->item['description'])) :
$content = $this->item['description'];
endif;
endif;
return $content;
} /* SyndicatedPost::content() */
public function excerpt () {
# Identify and sanitize excerpt: atom:summary, or rss:description
$excerpt = $this->entry->get_description();
# Many RSS feeds use rss:description, inadvisably, to
# carry the entire post (typically with escaped HTML).
# If that's what happened, we don't want the full
# content for the excerpt.
$content = $this->content();
// Ignore whitespace, case, and tag cruft.
$theExcerpt = preg_replace('/\s+/', '', strtolower(strip_tags(html_entity_decode($excerpt))));
$theContent = preg_replace('/\s+/', '', strtolower(strip_tags(html_entity_decode($content))));
if ( empty($excerpt) or $theExcerpt == $theContent ) :
# If content is available, generate an excerpt.
if ( strlen(trim($content)) > 0 ) :
$excerpt = strip_tags($content);
if (strlen($excerpt) > 255) :
if (is_object($this->link) and is_object($this->link->simplepie)) :
$encoding = $this->link->simplepie->get_encoding();
else :
$encoding = get_option('blog_charset', 'utf8');
endif;
$excerpt = mb_substr($excerpt,0,252,$encoding).'...';
endif;
endif;
endif;
return $excerpt;
} /* SyndicatedPost::excerpt() */
/**
* SyndicatedPost::permalink: returns the permalink for the post, as provided by the
* source feed.
*
* @return string The URL of the original permalink for this syndicated post
*/
public function permalink () {
// Handles explicit <link> elements and also RSS 2.0 cases with
// <guid isPermaLink="true">, etc. Hooray!
$permalink = $this->entry->get_link();
return $permalink;
} /* SyndicatedPost::permalink () */
public function created ($params = array()) {
$unfiltered = false; // $default = NULL; // seems to be unused on this function (gwyneth 20230916)
extract($params);
$date = '';
if (isset($this->item['dc']['created'])) :
$date = $this->item['dc']['created'];
elseif (isset($this->item['dcterms']['created'])) :
$date = $this->item['dcterms']['created'];
elseif (isset($this->item['created'])): // Atom 0.3
$date = $this->item['created'];
endif;
$time = new FeedTime($date);
$tstamp = $time->timestamp();
if ( ! $unfiltered) :
apply_filters('syndicated_item_created', $tstamp, $this);
endif;
return $tstamp;
} /* SyndicatedPost::created() */
public function published ($params = array(), $default = NULL) {
$fallback = true; $unfiltered = false;
if ( !is_array($params)) : // Old style
$fallback = $params;
else : // New style
extract($params);
endif;
$date = '';
$tstamp = null;
# RSS is a fucking mess. Figure out whether we have a date in
# <dc:date>, <issued>, <pubDate>, etc., and get it into Unix
# epoch format for reformatting. If we can't find anything,
# we'll use the last-updated time.
if (isset($this->item['dc']['date'])): // Dublin Core
$date = $this->item['dc']['date'];
elseif (isset($this->item['dcterms']['issued'])) : // Dublin Core extensions
$date = $this->item['dcterms']['issued'];
elseif (isset($this->item['published'])) : // Atom 1.0
$date = $this->item['published'];
elseif (isset($this->item['issued'])): // Atom 0.3
$date = $this->item['issued'];
elseif (isset($this->item['pubdate'])): // RSS 2.0
$date = $this->item['pubdate'];
endif;
if (strlen($date) > 0) :
$time = new FeedTime($date);
$tstamp = $time->timestamp();
elseif ($fallback) : // Fall back to <updated> / <modified> if present
$tstamp = $this->updated(/*fallback=*/ false, /*default=*/ $default);
endif;
# If everything failed, then default to the current time.
if (is_null($tstamp)) :
if (-1 == $default) :
$tstamp = time();
else :
$tstamp = $default;
endif;
endif;
if ( ! $unfiltered) :
$tstamp = apply_filters('syndicated_item_published', $tstamp, $this);
endif;
return $tstamp;
} /* SyndicatedPost::published() */
public function updated ($params = array(), $default = -1) {
$fallback = true; $unfiltered = false;
if ( !is_array($params)) : // Old style
$fallback = $params;
else : // New style
extract($params);
endif;
$date = '';
$tstamp = null;
# As far as I know, only dcterms and Atom have reliable ways to
# specify when something was *modified* last. If neither is
# available, then we'll try to get the time of publication.
if (isset($this->item['dc']['modified'])) : // Not really correct
$date = $this->item['dc']['modified'];
elseif (isset($this->item['dcterms']['modified'])) : // Dublin Core extensions
$date = $this->item['dcterms']['modified'];
elseif (isset($this->item['modified'])): // Atom 0.3
$date = $this->item['modified'];
elseif (isset($this->item['updated'])): // Atom 1.0
$date = $this->item['updated'];
endif;
if (strlen($date) > 0) :
$time = new FeedTime($date);
$tstamp = $time->timestamp();
elseif ($fallback) : // Fall back to issued / dc:date
$tstamp = $this->published(/*fallback=*/ false, /*default=*/ $default);
endif;
# If everything failed, then default to the current time.
if (is_null($tstamp)) :
if (-1 == $default) :
$tstamp = time();
else :
$tstamp = $default;
endif;
endif;
if ( ! $unfiltered) :
$tstamp = apply_filters('syndicated_item_updated', $tstamp, $this);
endif;
return $tstamp;
} /* SyndicatedPost::updated() */
var $_hashes = array();
function stored_hashes ($id = NULL) {
if (is_null($id)) :
$id = $this->wp_id();
endif;
if ( !isset($this->_hashes[$id])) :
$this->_hashes[$id] = get_post_custom_values(
'syndication_item_hash', $id
);
if (is_null($this->_hashes[$id])) :
$this->_hashes[$id] = array();
endif;
endif;
return $this->_hashes[$id];
}
function update_hash ($hashed = true) {
// Basis for tracking possible changes to item.
$hash = array(
"title" => $this->entry->get_title(),
"link" => $this->permalink(),
"content" => $this->content(),
"excerpt" => $this->excerpt(),
);
if ($hashed) :
$hash = md5(serialize($hash));
endif;
return $hash;
} /* SyndicatedPost::update_hash() */
/**
* SyndicatedPost::normalize_guid_prefix(): generates a normalized URL
* prefix (including scheme, authority, full path, and the beginning of
* a query string) for creating guids that conform to WordPress's
* internal constraints on the URL space for valid guids. To create a
* normalized guid, just concatenate a valid URL query parameter value
* to the returned URL.
*
* @return string The URL prefix generated.
*
* @uses trailingslashit()
* @uses home_url()
* @uses apply_filters()
*/
static function normalize_guid_prefix () {
$url = trailingslashit(home_url(/*path=*/ '', /*scheme=*/ 'http'));
return apply_filters('syndicated_item_guid_normalized_prefix', $url . '?guid=');
} /* SyndicatedPost::normalize_guid_prefix() */
static function normalize_guid ($guid) {
$guid = trim($guid);
if (preg_match('/^[0-9a-z]{32}$/i', $guid)) : // MD5
$guid = SyndicatedPost::normalize_guid_prefix().strtolower($guid);
elseif ((strlen(esc_url($guid)) == 0) or (esc_url($guid) != $guid)) :
$guid = SyndicatedPost::normalize_guid_prefix().md5($guid);
endif;
$guid = trim($guid);
return $guid;
} /* SyndicatedPost::normalize_guid() */
static function alternative_guid_prefix () {
$url = trailingslashit(home_url(/*path=*/ '', /*scheme=*/ 'https'));
return apply_filters('syndicated_item_guid_normalized_prefix', $url . '?guid=');
}
static function alternative_guid ($guid) {
$guid = trim($guid);
if (preg_match('/^[0-9a-z]{32}$/i', $guid)) : // MD5
$guid = SyndicatedPost::alternative_guid_prefix().strtolower($guid);
elseif ((strlen(esc_url($guid)) == 0) or (esc_url($guid) != $guid)) :
$guid = SyndicatedPost::alternative_guid_prefix().md5($guid);
endif;
$guid = trim($guid);
return $guid;
} /* SyndicatedPost::normalize_guid() */
public function guid () {
$guid = null;
if (isset($this->item['id'])): // Atom 0.3 / 1.0
$guid = $this->item['id'];
elseif (isset($this->item['atom']['id'])) : // Namespaced Atom
$guid = $this->item['atom']['id'];
elseif (isset($this->item['guid'])) : // RSS 2.0
$guid = $this->item['guid'];
elseif (isset($this->item['dc']['identifier'])) : // yeah, right
$guid = $this->item['dc']['identifier'];
endif;
// Un-set or too long to use as-is. Generate a tag: URI.
if (is_null($guid) or strlen($guid) > 250) :
// In case we need to check this again
$original_guid = $guid;
// The feed does not seem to have provided us with a
// usable unique identifier, so we'll have to cobble
// together a tag: URI that might work for us. The base
// of the URI will be the host name of the feed source ...
$bits = parse_url($this->link->uri());
$guid = 'tag:'.$bits['host'];
// Some ill-mannered feeds (for example, certain feeds
// coming from Google Calendar) have extraordinarily long
// guids -- so long that they exceed the 255 character
// width of the WordPress guid field. But if the string
// gets clipped by MySQL, uniqueness tests will fail
// forever after and the post will be endlessly
// reduplicated. So, instead, Guids Of A Certain Length
// are hashed down into a nice, manageable tag: URI.
if ( !is_null($original_guid)) :
$guid .= ',2010-12-03:id.'.md5($original_guid);
// If we have a date of creation, then we can use that
// to uniquely identify the item. (On the other hand, if
// the feed producer was consicentious enough to
// generate dates of creation, she probably also was
// conscientious enough to generate unique identifiers.)
elseif ( !is_null($this->created())) :
$guid .= '://post.'.date('YmdHis', $this->created());
// Otherwise, use both the URI of the item, *and* the
// item's title. We have to use both because titles are
// often not unique, and sometimes links aren't unique
// either (e.g. Bitch (S)HITLIST, Mozilla Dot Org news,
// some podcasts). But it's rare to have *both* the same
// title *and* the same link for two different items. So
// this is about the best we can do.
else :
$link = $this->permalink();
if (is_null($link)) : $link = $this->link->uri(); endif;
$guid .= '://'.md5($link.'/'.$this->title());
endif;
endif;
return $guid;
} /* SyndicatedPost::guid() */
public function author () {
$author = array ();
$aa = $this->entry->get_authors();
if (is_countable($aa) and count($aa) > 0) :
$a = reset($aa);
$author = array(
'name' => $a->get_name(),
'email' => $a->get_email(),
'uri' => $a->get_link(),
);
endif;
if (FEEDWORDPRESS_COMPATIBILITY) :
// Search through the MagpieRSS elements: Atom, Dublin Core, RSS
if (isset($this->item['author_name'])):
$author['name'] = $this->item['author_name'];
elseif (isset($this->item['dc']['creator'])):
$author['name'] = $this->item['dc']['creator'];
elseif (isset($this->item['dc']['contributor'])):
$author['name'] = $this->item['dc']['contributor'];
elseif (isset($this->feed->channel['dc']['creator'])) :
$author['name'] = $this->feed->channel['dc']['creator'];
elseif (isset($this->feed->channel['dc']['contributor'])) :
$author['name'] = $this->feed->channel['dc']['contributor'];
elseif (isset($this->feed->channel['author_name'])) :
$author['name'] = $this->feed->channel['author_name'];
elseif ($this->feed->is_rss() and isset($this->item['author'])) :
// The author element in RSS is allegedly an
// e-mail address, but lots of people don't use
// it that way. So let's make of it what we can.
$author = parse_email_with_realname($this->item['author']);
if ( !isset($author['name'])) :
if (isset($author['email'])) :
$author['name'] = $author['email'];
else :
$author['name'] = $this->feed->channel['title'];
endif;
endif;
endif;
endif;
if ( !isset($author['name']) or is_null($author['name'])) :
// Nothing found. Try some crappy defaults.
if ($this->link->name()) :
$author['name'] = $this->link->name();
else :
$url = parse_url($this->link->uri());
$author['name'] = $url['host'];
endif;
endif;
if (FEEDWORDPRESS_COMPATIBILITY) :
if (isset($this->item['author_email'])):
$author['email'] = $this->item['author_email'];
elseif (isset($this->feed->channel['author_email'])) :
$author['email'] = $this->feed->channel['author_email'];
endif;
if (isset($this->item['author_uri'])):
$author['uri'] = $this->item['author_uri'];
elseif (isset($this->item['author_url'])):
$author['uri'] = $this->item['author_url'];
elseif (isset($this->feed->channel['author_uri'])) :
$author['uri'] = $this->item['author_uri'];
elseif (isset($this->feed->channel['author_url'])) :
$author['uri'] = $this->item['author_url'];
elseif (isset($this->feed->channel['link'])) :
$author['uri'] = $this->feed->channel['link'];
endif;
endif;
return $author;
} /* SyndicatedPost::author() */
/**
* SyndicatedPost::get_terms_from_settings(): Return an array of terms to associate with the incoming
* post based on the Categories, Tags, and other terms associated with each new post by the user's
* settings (global and feed-specific).
*
* @since 2016.0331
* @return array of lists, each element has the taxonomy for a key ('category', 'post_tag', etc.),
* and a list of term codes (either alphanumeric names, or ID numbers encoded in a format that
* SyndicatedLink::category_ids() can understand) within that taxonomy
*
*/
public function get_terms_from_settings () {
// Categories: start with default categories, if any.
$cats = array();
if ('no' != $this->link->setting('add/category', NULL, 'yes')) :
$fc = get_option("feedwordpress_syndication_cats");
if ($fc) :
$cats = array_merge($cats, explode("\n", $fc));
endif;
endif;
$fc = $this->link->setting('cats',NULL, array());
if (is_array($fc)) :
$cats = array_merge($cats, $fc);
endif;
$preset_terms['category'] = $cats;
// Tags: start with default tags, if any
$tags = array();
if ('no' != $this->link->setting('add/post_tag', NULL, 'yes')) :
$ft = get_option("feedwordpress_syndication_tags", NULL);
$tags = (is_null($ft) ? array() : explode(FEEDWORDPRESS_CAT_SEPARATOR, $ft));
endif;
$ft = $this->link->setting('tags', NULL, array());
if (is_array($ft)) :
$tags = array_merge($tags, $ft);
endif;
$preset_terms['post_tag'] = $tags;
$taxonomies = $this->link->taxonomies();
$feedTerms = $this->link->setting('terms', NULL, array());
$globalTerms = get_option('feedwordpress_syndication_terms', array());
$specials = array('category' => 'cats', 'post_tag' => 'tags');
foreach ($taxonomies as $tax) :
// category and tag settings have already previously been handled
// but if this is from another taxonomy, then...
if ( !isset($specials[$tax])) :
$terms = array();
// See if we should get the globals
if ('no' != $this->link->setting("add/$tax", NULL, 'yes')) :
if (isset($globalTerms[$tax])) :
$terms = $globalTerms[$tax];
endif;
endif;
// Now merge in the locals
if (isset($feedTerms[$tax])) :
$terms = array_merge($terms, $feedTerms[$tax]);
endif;
// That's all, folks.
$preset_terms[$tax] = $terms;
endif;
endforeach;
return $preset_terms;
} /* SyndicatedPost::get_terms_from_settings () */
/**
* SyndicatedPost::get_terms_from_feeds(): Return an array of terms to associate with the incoming
* post based on the contents of the subscribed feed (atom:category and rss:category elements, dc:subject
* elements, tags embedded using microformats in the post content, etc.)
*
* @since 2016.0331
* @return array of lists, each element has the taxonomy for a key ('category', 'post_tag', etc.),
* and a list of alphanumeric term names
*/
public function get_terms_from_feeds () {
// Now add categories from the post, if we have 'em
$cats = array();
$post_cats = $this->entry->get_categories();
if (is_array($post_cats)) : foreach ($post_cats as $cat) :
$cat_name = $cat->get_term();
if ( ! $cat_name) : $cat_name = $cat->get_label(); endif;
if ($this->link->setting('cat_split', NULL, NULL)) :
$pcre = "\007".$this->feedmeta['cat_split']."\007";
$cats = array_merge(
$cats,
preg_split(
$pcre,
$cat_name,
-1 /*=no limit*/,
PREG_SPLIT_NO_EMPTY
)
);
else :
$cats[] = $cat_name;
endif;
endforeach; endif;
$feed_terms['category'] = apply_filters('syndicated_item_categories', $cats, $this);
// Scan post for /a[@rel='tag'] and use as tags if present
$tags = $this->inline_tags();
$feed_terms['post_tag'] = apply_filters('syndicated_item_tags', $tags, $this);
return $feed_terms;
} /* SyndicatedPost::get_terms_from_feeds () */
/**
* SyndicatedPost::inline_tags: Return a list of all the tags embedded
* in post content using the a[@rel="tag"] microformat.
*
* @since 2010.0630
* @return array of string values containing the name of each tag
*/
function inline_tags () {
$tags = array();
$content = $this->content();
$pattern = FeedWordPressHTML::tagWithAttributeRegex('a', 'rel', 'tag');
preg_match_all($pattern, $content, $refs, PREG_SET_ORDER);
if (is_countable($refs) and count($refs) > 0) :
foreach ($refs as $ref) :
$tag = FeedWordPressHTML::tagWithAttributeMatch($ref);
$tags[] = $tag['content'];
endforeach;
endif;
return $tags;
}
/**
* SyndicatedPost::isTaggedAs: Test whether a feed item is
* tagged / categorized with a given string. Case and leading and
* trailing whitespace are ignored.
*
* @param string $tag Tag to check for
*
* @return bool Whether or not at least one of the categories / tags on
* $this->item is set to $tag (modulo case and leading and trailing
* whitespace)
*/
function isTaggedAs ($tag) {
$desiredTag = strtolower(trim($tag)); // Normalize case and whitespace
// Check to see if this is tagged with $tag
$currentCategory = 'category';
$currentCategoryNumber = 1;
// If we have the new MagpieRSS, the number of category elements
// on this item is stored under index "category#".
if (isset($this->item['category#'])) :
$numberOfCategories = (int) $this->item['category#'];
// We REALLY shouldn't have the old and busted MagpieRSS, but in
// case we do, it doesn't support multiple categories, but there
// might still be a single value under the "category" index.
elseif (isset($this->item['category'])) :
$numberOfCategories = 1;
// No standard category or tag elements on this feed item.
else :
$numberOfCategories = 0;
endif;
$isSoTagged = false; // Innocent until proven guilty
// Loop through category elements; if there are multiple
// elements, they are indexed as category, category#2,
// category#3, ... category#N
while ($currentCategoryNumber <= $numberOfCategories) :
if ($desiredTag == strtolower(trim($this->item[$currentCategory]))) :
$isSoTagged = true; // Got it!
break;
endif;
$currentCategoryNumber += 1;
$currentCategory = 'category#'.$currentCategoryNumber;
endwhile;
return $isSoTagged;
} /* SyndicatedPost::isTaggedAs() */
/**
* SyndicatedPost::enclosures: returns an array with any enclosures
* that may be attached to this syndicated item.
*
* @param string $type If you only want enclosures that match a certain
* MIME type or group of MIME types, you can limit the enclosures
* that will be returned to only those with a MIME type which
* matches this regular expression.
* @return array
*/
function enclosures( $type = '/.*/' ) {
$enclosures = array();
if ( isset( $this->item['enclosure#'] ) ) :
// Loop through enclosure, enclosure#2, enclosure#3, ....
for ( $i = 1; $i <= $this->item['enclosure#']; $i++ ) :
$eid = ( ( $i > 1 ) ? "#{$i}" : "" ); // this was set as #{$id} — was that a typo? (gwyneth 20230919)
// Does it match the type we want?
if ( preg_match($type, $this->item["enclosure{$eid}@type"] ) ) :
$enclosures[] = array(
"url" => $this->item["enclosure{$eid}@url"],
"type" => $this->item["enclosure{$eid}@type"],
"length" => $this->item["enclosure{$eid}@length"],