PluginProbe
FeedWordPress / 2011.0531
FeedWordPress v2011.0531
trunk 0.8 0.9 0.91 0.95 0.96 0.97 0.98 0.981 0.99 0.991 0.992 0.993 2008.1030 2008.1101 2008.1105 2008.1214 2009.0612 2009.0613 2009.0618 2009.0707 2009.1111 2009.1112 2010.0127 2010.0528 All 65 releases
← All changes | syndicatedpost.class.php +902 -1201 trunk2011.0531 View file →
@@ -1,8 +1,6 @@
1 1 <?php
2 -require_once dirname(__FILE__) . '/feedtime.class.php';
3 -require_once dirname(__FILE__) . '/syndicatedpostterm.class.php';
4 -require_once dirname(__FILE__) . '/syndicatedpostxpathquery.class.php';
2 +require_once(dirname(__FILE__).'/feedtime.class.php');
5 3
6 4 /**
7 5 * class SyndicatedPost: FeedWordPress uses to manage the conversion of
8 6 * incoming items from the feed parser into posts for the WordPress
@@ -11,31 +9,28 @@
11 9 * as some utility methods for extracting useful data from many
12 10 * different feed formats, which may be useful to FeedWordPress users
13 11 * who make use of feed data in PHP add-ons and filters.
14 12 *
15 - * @version 2017.1018
13 + * @version 2010.0905
16 14 */
17 15 class SyndicatedPost {
18 - /** @var MagpieRSS|null MagpieRSS representation. */
19 - var $item = null;
20 - /** @var SimplePie_Item|null SimplePie_Item representation. */
21 - var $entry = null;
16 + var $item = null; // MagpieRSS representation
17 + var $entry = null; // SimplePie_Item representation
22 18
23 19 var $link = null;
24 20 var $feed = null;
25 21 var $feedmeta = null;
22 +
23 + var $xmlns = array ();
26 24
27 - var $xmlns = array();
25 + var $post = array ();
28 26
29 - var $post = array();
30 -
31 - var $named = array();
32 - var $preset_terms = array();
33 - var $feed_terms = array();
34 -
27 + var $named = array ();
28 + var $preset_terms = array ();
29 + var $feed_terms = array ();
30 +
35 31 var $_freshness = null;
36 32 var $_wp_id = null;
37 - var $_wp_post = null;
38 33
39 34 /**
40 35 * SyndicatedPost constructor: Given a feed item and the source from
41 36 * which it was taken, prepare a post that can be inserted into the
@@ -44,68 +39,81 @@
44 39 *
45 40 * @param array $item The item syndicated from the feed.
46 41 * @param SyndicatedLink $source The feed it was syndicated from.
47 42 */
48 - public function __construct( $item, $source ) {
49 - if ( empty( $item ) and empty( $source ) )
50 - return;
43 + function SyndicatedPost ($item, &$source) {
44 + global $wpdb;
51 45
52 - if ( is_array( $item )
53 - and isset( $item['simplepie'] )
54 - and isset( $item['magpie'] ) ) :
46 + if (is_array($item)
47 + and isset($item['simplepie'])
48 + and isset($item['magpie'])) :
55 49 $this->entry = $item['simplepie'];
56 50 $this->item = $item['magpie'];
57 51 $item = $item['magpie'];
58 - elseif ( is_a( $item, 'SimplePie_Item' ) ) :
52 + elseif (is_a($item, 'SimplePie_Item')) :
59 53 $this->entry = $item;
60 -
54 +
61 55 // convert to Magpie for compat purposes
62 - $mpie = new MagpieFromSimplePie( $source->simplepie, $this->entry );
63 - $this->item = $mpie->get_item();
64 -
56 + $mp = new MagpieFromSimplePie($source->simplepie, $this->entry);
57 + $this->item = $mp->get_item();
58 +
65 59 // done with conversion object
66 - $mpie = NULL; unset( $mpie );
60 + $mp = NULL; unset($mp);
67 61 else :
68 62 $this->item = $item;
69 63 endif;
70 64
71 - $this->link = $source;
65 + $this->link =& $source;
72 66 $this->feed = $source->magpie;
73 67 $this->feedmeta = $source->settings;
74 68
75 - FeedWordPress::diagnostic( 'feed_items', 'Considering item [' . $this->guid() . '] "' . $this->entry->get_title().'"');
69 + FeedWordPress::diagnostic('feed_items', 'Considering item ['.$this->guid().'] "'.$this->entry->get_title().'"');
76 70
77 71 # Dealing with namespaces can get so fucking fucked.
78 72 $this->xmlns['forward'] = $source->magpie->_XMLNS_FAMILIAR;
79 73 $this->xmlns['reverse'] = array();
80 - foreach ( $this->xmlns['forward'] as $url => $ns ) :
81 - if ( ! isset( $this->xmlns['reverse'][ $ns ] ) ) :
82 - $this->xmlns['reverse'][ $ns ] = array();
74 + foreach ($this->xmlns['forward'] as $url => $ns) :
75 + if (!isset($this->xmlns['reverse'][$ns])) :
76 + $this->xmlns['reverse'][$ns] = array();
83 77 endif;
84 - $this->xmlns['reverse'][ $ns ][] = $url;
78 + $this->xmlns['reverse'][$ns][] = $url;
85 79 endforeach;
86 -
80 +
87 81 // Fucking SimplePie.
88 82 $this->xmlns['reverse']['rss'][] = '';
89 83
84 + # These globals were originally an ugly kludge around a bug in
85 + # apply_filters from WordPress 1.5. The bug was fixed in 1.5.1,
86 + # and I sure hope at this point that nobody writing filters for
87 + # FeedWordPress is still relying on them.
88 + #
89 + # Anyway, I hereby declare them DEPRECATED as of 8 February
90 + # 2010. I'll probably remove the globals within 1-2 releases in
91 + # the interests of code hygiene and memory usage. If you
92 + # currently use them in your filters, I advise you switch off to
93 + # accessing the public members SyndicatedPost::feed and
94 + # SyndicatedPost::feedmeta.
95 +
96 + global $fwp_channel, $fwp_feedmeta;
97 + $fwp_channel = $this->feed; $fwp_feedmeta = $this->feedmeta;
98 +
90 99 // Trigger global syndicated_item filter.
91 - $changed = apply_filters( 'syndicated_item', $this->item, $this );
100 + $changed = apply_filters('syndicated_item', $this->item, $this);
92 101 $this->item = $changed;
93 -
102 +
94 103 // Allow for feed-specific syndicated_item filters.
95 104 $changed = apply_filters(
96 - "syndicated_item_" . $source->uri(),
105 + "syndicated_item_".$source->uri(),
97 106 $this->item,
98 107 $this
99 108 );
100 109 $this->item = $changed;
101 -
110 +
102 111 # Filters can halt further processing by returning NULL
103 - if ( is_null( $this->item ) ) :
112 + if (is_null($this->item)) :
104 113 $this->post = NULL;
105 114 else :
106 -
107 - # Note that nothing is run through esc_sql() here.
115 + # Note that nothing is run through $wpdb->escape() here.
108 116 # That's deliberate. The escaping is done at the point
109 117 # of insertion, not here, to avoid double-escaping and
110 118 # to avoid screwing with syndicated_post filters
111 119
@@ -110,16 +118,14 @@
110 118 # to avoid screwing with syndicated_post filters
111 119
112 120 $this->post['post_title'] = apply_filters(
113 121 'syndicated_item_title',
114 - $this->entry->get_title(),
115 - $this
122 + $this->entry->get_title(), $this
116 123 );
117 124
118 125 $this->named['author'] = apply_filters(
119 126 'syndicated_item_author',
120 - $this->author(),
121 - $this
127 + $this->author(), $this
122 128 );
123 129 // This just gives us an alphanumeric name for the author.
124 130 // We look up (or create) the numeric ID for the author
125 131 // in SyndicatedPost::add().
@@ -125,68 +131,95 @@
125 131 // in SyndicatedPost::add().
126 132
127 133 $this->post['post_content'] = apply_filters(
128 134 'syndicated_item_content',
129 - $this->content(),
130 - $this
135 + $this->content(), $this
131 136 );
132 -
133 - $excerpt = apply_filters( 'syndicated_item_excerpt', $this->excerpt(), $this );
134 -
135 - if ( !empty( $excerpt ) ):
137 +
138 + $excerpt = apply_filters('syndicated_item_excerpt', $this->excerpt(), $this);
139 + if (!empty($excerpt)):
136 140 $this->post['post_excerpt'] = $excerpt;
137 141 endif;
138 142
139 143 // Dealing with timestamps in WordPress is so fucking fucked.
140 - $offset = (int) get_option( 'gmt_offset' ) * 60 * 60;
141 - $post_date_gmt = $this->published( array( 'default' => -1 ) );
142 - $post_modified_gmt = $this->updated( array( 'default' => -1 ) );
144 + $offset = (int) get_option('gmt_offset') * 60 * 60;
145 + $post_date_gmt = $this->published(array('default' => -1));
146 + $post_modified_gmt = $this->updated(array('default' => -1));
143 147
144 - $this->post['post_date_gmt'] = gmdate( 'Y-m-d H:i:s', $post_date_gmt );
145 - $this->post['post_date'] = gmdate( 'Y-m-d H:i:s', $post_date_gmt + $offset );
146 - $this->post['post_modified_gmt'] = gmdate( 'Y-m-d H:i:s', $post_modified_gmt );
147 - $this->post['post_modified'] = gmdate( 'Y-m-d H:i:s', $post_modified_gmt + $offset );
148 + $this->post['post_date_gmt'] = gmdate('Y-m-d H:i:s', $post_date_gmt);
149 + $this->post['post_date'] = gmdate('Y-m-d H:i:s', $post_date_gmt + $offset);
150 + $this->post['post_modified_gmt'] = gmdate('Y-m-d H:i:s', $post_modified_gmt);
151 + $this->post['post_modified'] = gmdate('Y-m-d H:i:s', $post_modified_gmt + $offset);
148 152
149 153 // Use feed-level preferences or the global default.
150 - $this->post['post_status'] = $this->link->syndicated_status( 'post', 'publish' );
151 - $this->post['comment_status'] = $this->link->syndicated_status( 'comment', 'closed' );
152 - $this->post['ping_status'] = $this->link->syndicated_status( 'ping', 'closed' );
154 + $this->post['post_status'] = $this->link->syndicated_status('post', 'publish');
155 + $this->post['comment_status'] = $this->link->syndicated_status('comment', 'closed');
156 + $this->post['ping_status'] = $this->link->syndicated_status('ping', 'closed');
153 157
154 158 // Unique ID (hopefully a unique tag: URI); failing that, the permalink
155 - $this->post['guid'] = apply_filters( 'syndicated_item_guid', $this->guid(), $this );
159 + $this->post['guid'] = apply_filters('syndicated_item_guid', $this->guid(), $this);
156 160
157 - // User-supplied custom settings to apply to each post.
158 - // Do first so that FWP-generated custom settings will
159 - // overwrite if necessary; thus preventing any munging.
160 - $postMetaIn = $this->link->postmeta( array( "parsed" => true ) );
161 + // 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
162 + $default_custom_settings = get_option('feedwordpress_custom_settings');
163 + if ($default_custom_settings and !is_array($default_custom_settings)) :
164 + $default_custom_settings = unserialize($default_custom_settings);
165 + endif;
166 + if (!is_array($default_custom_settings)) :
167 + $default_custom_settings = array();
168 + endif;
169 +
170 + $custom_settings = (isset($this->link->settings['postmeta']) ? $this->link->settings['postmeta'] : null);
171 + if ($custom_settings and !is_array($custom_settings)) :
172 + $custom_settings = unserialize($custom_settings);
173 + endif;
174 + if (!is_array($custom_settings)) :
175 + $custom_settings = array();
176 + endif;
177 +
178 + $postMetaIn = array_merge($default_custom_settings, $custom_settings);
161 179 $postMetaOut = array();
162 180
163 - foreach ( $postMetaIn as $key => $meta ) :
164 - $postMetaOut[ $key ] = $meta->do_substitutions( $this );
181 + // Big ugly fuckin loop to do any element substitutions
182 + // that we may need.
183 + foreach ($postMetaIn as $key => $values) :
184 + if (is_string($values)) : $values = array($values); endif;
185 +
186 + $postMetaOut[$key] = array();
187 + foreach ($values as $value) :
188 + if (preg_match('/\$\( ([^)]+) \)/x', $value, $ref)) :
189 + $elements = $this->query($ref[1]);
190 + foreach ($elements as $element) :
191 + $postMetaOut[$key][] = str_replace(
192 + $ref[0],
193 + $element,
194 + $value
195 + );
196 + endforeach;
197 + else :
198 + $postMetaOut[$key][] = $value;
199 + endif;
200 + endforeach;
165 201 endforeach;
166 202
167 - foreach ( $postMetaOut as $key => $values ) :
168 - if ( is_null( $values ) ) { // have chosen to replace value with empty string
169 - $values = [ '' ];
170 - }
171 - $this->post['meta'][ $key ] = array();
172 - foreach ( $values as $value ) :
173 - $this->post['meta'][ $key ][] = apply_filters( "syndicated_post_meta_{$key}", $value, $this );
203 + foreach ($postMetaOut as $key => $values) :
204 + $this->post['meta'][$key] = array();
205 + foreach ($values as $value) :
206 + $this->post['meta'][$key][] = apply_filters("syndicated_post_meta_{$key}", $value, $this);
174 207 endforeach;
175 208 endforeach;
176 -
209 +
177 210 // RSS 2.0 / Atom 1.0 enclosure support
178 211 $enclosures = $this->entry->get_enclosures();
179 - if ( is_array( $enclosures ) ) : foreach ( $enclosures as $enclosure ) :
212 + if (is_array($enclosures)) : foreach ($enclosures as $enclosure) :
180 213 $this->post['meta']['enclosure'][] =
181 - apply_filters( 'syndicated_item_enclosure_url', $enclosure->get_link(), $this ) . "\n".
182 - apply_filters( 'syndicated_item_enclosure_length', $enclosure->get_length(), $this ) . "\n".
183 - apply_filters( 'syndicated_item_enclosure_type', $enclosure->get_type(), $this );
214 + apply_filters('syndicated_item_enclosure_url', $enclosure->get_link(), $this)."\n".
215 + apply_filters('syndicated_item_enclosure_length', $enclosure->get_length(), $this)."\n".
216 + apply_filters('syndicated_item_enclosure_type', $enclosure->get_type(), $this);
184 217 endforeach; endif;
185 218
186 219 // In case you want to point back to the blog this was
187 220 // syndicated from.
188 -
221 +
189 222 $sourcemeta['syndication_source'] = apply_filters(
190 223 'syndicated_item_source_title',
191 224 $this->link->name(),
192 225 $this
@@ -200,21 +233,21 @@
200 233 'syndicated_item_source_id',
201 234 $this->link->guid(),
202 235 $this
203 236 );
204 -
237 +
205 238 // Make use of atom:source data, if present in an aggregated feed
206 239 $entry_source = $this->source();
207 - if ( ! is_null( $entry_source ) ) :
208 - foreach ( $entry_source as $what => $value ) :
209 - if ( ! is_null( $value ) ) :
210 - if ( 'title' == $what ) : $key = 'syndication_source';
211 - elseif ( 'feed' == $what ) : $key = 'syndication_feed';
212 - else : $key = "syndication_source_{$what}";
240 + if (!is_null($entry_source)) :
241 + foreach ($entry_source as $what => $value) :
242 + if (!is_null($value)) :
243 + if ($what=='title') : $key = 'syndication_source';
244 + elseif ($what=='feed') : $key = 'syndication_feed';
245 + else : $key = "syndication_source_${what}";
213 246 endif;
214 -
215 - $sourcemeta["{$key}_original"] = apply_filters(
216 - 'syndicated_item_original_source_' . $what,
247 +
248 + $sourcemeta["${key}_original"] = apply_filters(
249 + 'syndicated_item_original_source_'.$what,
217 250 $value,
218 251 $this
219 252 );
220 253 endif;
@@ -219,79 +252,136 @@
219 252 );
220 253 endif;
221 254 endforeach;
222 255 endif;
223 -
224 - foreach ( $sourcemeta as $meta_key => $value ) :
225 - if ( !is_null( $value ) ) :
226 - $this->post['meta'][ $meta_key ] = $value;
256 +
257 + foreach ($sourcemeta as $meta_key => $value) :
258 + if (!is_null($value)) :
259 + $this->post['meta'][$meta_key] = $value;
227 260 endif;
228 261 endforeach;
229 262
230 263 // Store information on human-readable and machine-readable comment URIs
231 -
264 +
232 265 // Human-readable comment URI
233 - $commentLink = apply_filters( 'syndicated_item_comments', $this->comment_link(), $this );
234 - if ( ! is_null( $commentLink) ) : $this->post['meta']['rss:comments'] = $commentLink; endif;
266 + $commentLink = apply_filters('syndicated_item_comments', $this->comment_link(), $this);
267 + if (!is_null($commentLink)) : $this->post['meta']['rss:comments'] = $commentLink; endif;
235 268
236 269 // Machine-readable content feed URI
237 - $commentFeed = apply_filters( 'syndicated_item_commentrss', $this->comment_feed(), $this );
238 - if ( ! is_null( $commentFeed ) ) : $this->post['meta']['wfw:commentRSS'] = $commentFeed; endif;
270 + $commentFeed = apply_filters('syndicated_item_commentrss', $this->comment_feed(), $this);
271 + if (!is_null($commentFeed)) : $this->post['meta']['wfw:commentRSS'] = $commentFeed; endif;
239 272 // Yeah, yeah, now I know that it's supposed to be
240 273 // wfw:commentRss. Oh well. Path dependence, sucka.
241 274
242 275 // Store information to identify the feed that this came from
243 - if ( isset( $this->feedmeta['link/uri'] ) ) :
276 + if (isset($this->feedmeta['link/uri'])) :
244 277 $this->post['meta']['syndication_feed'] = $this->feedmeta['link/uri'];
245 278 endif;
246 - if ( isset( $this->feedmeta['link/id'] ) ) :
279 + if (isset($this->feedmeta['link/id'])) :
247 280 $this->post['meta']['syndication_feed_id'] = $this->feedmeta['link/id'];
248 281 endif;
249 282
250 - if ( isset( $this->item['source_link_self'] ) ) :
283 + if (isset($this->item['source_link_self'])) :
251 284 $this->post['meta']['syndication_feed_original'] = $this->item['source_link_self'];
252 285 endif;
253 286
254 287 // In case you want to know the external permalink...
255 - $this->post['meta']['syndication_permalink'] = apply_filters( 'syndicated_item_link', $this->permalink() );
288 + $this->post['meta']['syndication_permalink'] = apply_filters('syndicated_item_link', $this->permalink());
256 289
257 290 // Store a hash of the post content for checking whether something needs to be updated
258 291 $this->post['meta']['syndication_item_hash'] = $this->update_hash();
259 292
260 - // Categories, Tags, and other Terms: from settings assignments (global settings, subscription settings),
261 - // and from feed assignments (item metadata, post content)
262 - $this->preset_terms = apply_filters( 'syndicated_item_preset_terms', $this->get_terms_from_settings(), $this );
263 - $this->feed_terms = apply_filters( 'syndicated_item_feed_terms', $this->get_terms_from_feeds(), $this );
293 + // Categories: start with default categories, if any.
294 + $cats = array();
295 + if ('no' != $this->link->setting('add/category', NULL, 'yes')) :
296 + $fc = get_option("feedwordpress_syndication_cats");
297 + if ($fc) :
298 + $cats = array_merge($cats, explode("\n", $fc));
299 + endif;
300 + endif;
264 301
265 - $this->post['post_type'] = apply_filters(
266 - 'syndicated_post_type',
267 - $this->link->setting( 'syndicated post type', 'syndicated_post_type', 'post' ),
268 - $this
269 - );
302 + $fc = $this->link->setting('cats', NULL, array());
303 + if (is_array($fc)) :
304 + $cats = array_merge($cats, $fc);
305 + endif;
306 + $this->preset_terms['category'] = $cats;
307 +
308 + // Now add categories from the post, if we have 'em
309 + $cats = array();
310 + $post_cats = $this->entry->get_categories();
311 + if (is_array($post_cats)) : foreach ($post_cats as $cat) :
312 + $cat_name = $cat->get_term();
313 + if (!$cat_name) : $cat_name = $cat->get_label(); endif;
314 +
315 + if ($this->link->setting('cat_split', NULL, NULL)) :
316 + $pcre = "\007".$this->feedmeta['cat_split']."\007";
317 + $cats = array_merge(
318 + $cats,
319 + preg_split(
320 + $pcre,
321 + $cat_name,
322 + -1 /*=no limit*/,
323 + PREG_SPLIT_NO_EMPTY
324 + )
325 + );
326 + else :
327 + $cats[] = $cat_name;
328 + endif;
329 + endforeach; endif;
330 +
331 + $this->feed_terms['category'] = apply_filters('syndicated_item_categories', $cats, $this);
332 +
333 + // Tags: start with default tags, if any
334 + $tags = array();
335 + if ('no' != $this->link->setting('add/post_tag', NULL, 'yes')) :
336 + $ft = get_option("feedwordpress_syndication_tags", NULL);
337 + $tags = (is_null($ft) ? array() : explode(FEEDWORDPRESS_CAT_SEPARATOR, $ft));
338 + endif;
339 +
340 + $ft = $this->link->setting('tags', NULL, array());
341 + if (is_array($ft)) :
342 + $tags = array_merge($tags, $ft);
343 + endif;
344 + $this->preset_terms['post_tag'] = $tags;
345 +
346 + // Scan post for /a[@rel='tag'] and use as tags if present
347 + $tags = $this->inline_tags();
348 + $this->feed_terms['post_tag'] = apply_filters('syndicated_item_tags', $tags, $this);
349 +
350 + $taxonomies = $this->link->taxonomies();
351 + $feedTerms = $this->link->setting('terms', NULL, array());
352 + $globalTerms = get_option('feedwordpress_syndication_terms', array());
353 +
354 + $specials = array('category' => 'cats', 'post_tag' => 'tags');
355 + foreach ($taxonomies as $tax) :
356 + if (!isset($specials[$tax])) :
357 + $terms = array();
358 +
359 + // See if we should get the globals
360 + if ('no' != $this->link->setting("add/$tax", NULL, 'yes')) :
361 + if (isset($globalTerms[$tax])) :
362 + $terms = $globalTerms[$tax];
363 + endif;
364 + endif;
365 +
366 + // Now merge in the locals
367 + if (isset($feedTerms[$tax])) :
368 + $terms = array_merge($terms, $feedTerms[$tax]);
369 + endif;
370 +
371 + // That's all, folks.
372 + $this->preset_terms[$tax] = $terms;
373 + endif;
374 + endforeach;
375 +
376 + $this->post['post_type'] = apply_filters('syndicated_post_type', $this->link->setting('syndicated post type', 'syndicated_post_type', 'post'), $this);
270 377 endif;
271 - } /* SyndicatedPost::__construct() */
378 + } /* SyndicatedPost::SyndicatedPost() */
272 379
273 380 #####################################
274 381 #### EXTRACT DATA FROM FEED ITEM ####
275 382 #####################################
276 -
277 - function substitution_function ($name) {
278 - $ret = NULL;
279 -
280 - switch ($name) :
281 - // Allowed PHP string functions
282 - case 'trim':
283 - case 'ltrim':
284 - case 'rtrim':
285 - case 'strtoupper':
286 - case 'strtolower':
287 - case 'urlencode':
288 - case 'urldecode':
289 - $ret = $name;
290 - endswitch;
291 - return $ret;
292 - }
293 -
383 +
294 384 /**
295 385 * SyndicatedPost::query uses an XPath-like syntax to query arbitrary
296 386 * elements within the syndicated item.
297 387 *
@@ -298,29 +388,100 @@
298 388 * @param string $path
299 389 * @returns array of string values representing contents of matching
300 390 * elements or attributes
301 391 */
302 - public function query ($path) {
303 - $xq = new SyndicatedPostXPathQuery(array("path" => $path));
392 + function query ($path) {
393 + $urlHash = array();
304 394
305 - $feedChannel = array_merge(
306 - $this->get_feed_root_element(),
307 - $this->get_feed_channel_elements()
308 - );
395 + // Allow {url} notation for namespaces. URLs will contain : and /, so...
396 + preg_match_all('/{([^}]+)}/', $path, $match, PREG_SET_ORDER);
397 + foreach ($match as $ref) :
398 + $urlHash[md5($ref[1])] = $ref[1];
399 + endforeach;
400 +
401 + foreach ($urlHash as $hash => $url) :
402 + $path = str_replace('{'.$url.'}', '{#'.$hash.'}', $path);
403 + endforeach;
309 404
310 - $matches = $xq->match(array(
311 - "type" => $this->link->simplepie->get_type(),
312 - "xmlns" => $this->xmlns,
313 - "map" => array(
314 - "/" => array($this->entry->data),
315 - "item" => array($this->entry->data),
316 - "feed" => $feedChannel,
317 - "channel" => $feedChannel
318 - ),
319 - "context" => $this->entry->data,
320 - "parent" => $feedChannel,
321 - ));
405 + $path = explode('/', $path);
406 + foreach ($path as $index => $node) :
407 + if (preg_match('/{#([^}]+)}/', $node, $ref)) :
408 + if (isset($urlHash[$ref[1]])) :
409 + $path[$index] = str_replace(
410 + '{#'.$ref[1].'}',
411 + '{'.$urlHash[$ref[1]].'}',
412 + $node
413 + );
414 + endif;
415 + endif;
416 + endforeach;
322 417
418 + // Start out with a get_item_tags query.
419 + $node = '';
420 + while (strlen($node)==0 and !is_null($node)) :
421 + $node = array_shift($path);
422 + endwhile;
423 +
424 + switch ($node) :
425 + case 'feed' :
426 + case 'channel' :
427 + $node = array_shift($path);
428 + $data = $this->get_feed_root_element();
429 + $data = array_merge($data, $this->get_feed_channel_elements());
430 + break;
431 + case 'item' :
432 + $node = array_shift($path);
433 + default :
434 + $data = array($this->entry->data);
435 + $method = NULL;
436 + endswitch;
437 +
438 + while (!is_null($node)) :
439 + if (strlen($node) > 0) :
440 + $matches = array();
441 +
442 + list($axis, $element) = $this->xpath_name_and_axis($node);
443 +
444 + foreach ($data as $datum) :
445 + if (!is_string($datum) and isset($datum[$axis])) :
446 + foreach ($datum[$axis] as $ns => $elements) :
447 + if (isset($elements[$element])) :
448 + // Potential match.
449 + // Check namespace.
450 + if (is_string($elements[$element])) : // Attribute
451 + $addenda = array($elements[$element]);
452 + $contexts = array($datum);
453 + else : // Element
454 + $addenda = $elements[$element];
455 + $contexts = $elements[$element];
456 + endif;
457 +
458 + foreach ($addenda as $index => $addendum) :
459 + $context = $contexts[$index];
460 +
461 + $namespaces = $this->xpath_possible_namespaces($node, $context);
462 + if (in_array($ns, $namespaces)) :
463 + $matches[] = $addendum;
464 + endif;
465 + endforeach;
466 + endif;
467 + endforeach;
468 + endif;
469 + endforeach;
470 +
471 + $data = $matches;
472 + endif;
473 + $node = array_shift($path);
474 + endwhile;
475 +
476 + $matches = array();
477 + foreach ($data as $datum) :
478 + if (is_string($datum)) :
479 + $matches[] = $datum;
480 + elseif (isset($datum['data'])) :
481 + $matches[] = $datum['data'];
482 + endif;
483 + endforeach;
323 484 return $matches;
324 485 } /* SyndicatedPost::query() */
325 486
326 487 function get_feed_root_element () {
@@ -339,13 +500,13 @@
339 500 SIMPLEPIE_NAMESPACE_RSS_10,
340 501 'http://backend.userland.com/RSS2',
341 502 SIMPLEPIE_NAMESPACE_RSS_20,
342 503 );
343 -
504 +
344 505 $matches = array();
345 506 foreach ($rss as $ns) :
346 507 $data = $this->link->simplepie->get_feed_tags($ns, 'channel');
347 - if ( !is_null($data)) :
508 + if (!is_null($data)) :
348 509 $matches = array_merge($matches, $data);
349 510 endif;
350 511 endforeach;
351 512 return $matches;
@@ -350,116 +511,139 @@
350 511 endforeach;
351 512 return $matches;
352 513 } /* SyndicatedPost::get_feed_channel_elements() */
353 514
354 - public function get_categories ($params = array()) {
355 - return $this->entry->get_categories();
356 - }
515 + function xpath_default_namespace () {
516 + // Get the default namespace.
517 + $type = $this->link->simplepie->get_type();
518 + if ($type & SIMPLEPIE_TYPE_ATOM_10) :
519 + $defaultNS = SIMPLEPIE_NAMESPACE_ATOM_10;
520 + elseif ($type & SIMPLEPIE_TYPE_ATOM_03) :
521 + $defaultNS = SIMPLEPIE_NAMESPACE_ATOM_03;
522 + elseif ($type & SIMPLEPIE_TYPE_RSS_090) :
523 + $defaultNS = SIMPLEPIE_NAMESPACE_RSS_090;
524 + elseif ($type & SIMPLEPIE_TYPE_RSS_10) :
525 + $defaultNS = SIMPLEPIE_NAMESPACE_RSS_10;
526 + elseif ($type & SIMPLEPIE_TYPE_RSS_20) :
527 + $defaultNS = SIMPLEPIE_NAMESPACE_RSS_20;
528 + else :
529 + $defaultNS = SIMPLEPIE_NAMESPACE_RSS_20;
530 + endif;
531 + return $defaultNS;
532 + } /* SyndicatedPost::xpath_default_namespace() */
357 533
358 - public function title ($params = array()) {
359 - return $this->entry->get_title();
360 - } /* SyndicatedPost::title () */
534 + function xpath_name_and_axis ($node) {
535 + $ns = NULL; $element = NULL;
361 536
362 - public function content ($params = array())
363 - {
364 - $params = wp_parse_args($params, array(
365 - "full only" => false,
366 - ));
537 + if (substr($node, 0, 1)=='@') :
538 + $axis = 'attribs'; $node = substr($node, 1);
539 + else :
540 + $axis = 'child';
541 + endif;
367 542
368 - $content = NULL;
543 + if (preg_match('/^{([^}]*)}(.*)$/', $node, $ref)) :
544 + $element = $ref[2];
545 + elseif (strpos($node, ':') !== FALSE) :
546 + list($xmlns, $element) = explode(':', $node, 2);
547 + else :
548 + $element = $node;
549 + endif;
550 + return array($axis, $element);
551 + } /* SyndicatedPost::xpath_local_name () */
369 552
370 - // FIXME: This is one of the main places in the code still using
371 - // the outmoded SimplePie - to - Magpie construction. We could
372 - // replace using SimplePie_Item::get_tags() here. (Or if really
373 - // ambitious we could attempt to just use
374 - // SimplePie_Item::get_content() with content-only set to TRUE
375 - // and some sanitization in effect. -CJ 1jul14
553 + function xpath_possible_namespaces ($node, $datum = array()) {
554 + $ns = NULL; $element = NULL;
376 555
377 - // atom:content, standard method of providing full HTML content
378 - // in Atom feeds.
556 + if (substr($node, 0, 1)=='@') :
557 + $attr = '@'; $node = substr($node, 1);
558 + else :
559 + $attr = '';
560 + endif;
561 +
562 + if (preg_match('/^{([^}]*)}(.*)$/', $node, $ref)) :
563 + $ns = array($ref[1]);
564 + elseif (strpos($node, ':') !== FALSE) :
565 + list($xmlns, $element) = explode(':', $node, 2);
566 +
567 + if (isset($this->xmlns['reverse'][$xmlns])) :
568 + $ns = $this->xmlns['reverse'][$xmlns];
569 + else :
570 + $ns = array($xmlns);
571 + endif;
572 +
573 + // Fucking SimplePie. For attributes in default xmlns.
574 + $defaultNS = $this->xpath_default_namespace();
575 + if (isset($this->xmlns['forward'][$defaultNS])
576 + and ($xmlns==$this->xmlns['forward'][$defaultNS])) :
577 + $ns[] = '';
578 + endif;
579 +
580 + if (isset($datum['xmlns'])) :
581 + if (isset($datum['xmlns'][$xmlns])) :
582 + $ns[] = $datum['xmlns'][$xmlns];
583 + endif;
584 + endif;
585 + else :
586 + // Often in SimplePie, the default namespace gets stored
587 + // as an empty string rather than a URL.
588 + $ns = array($this->xpath_default_namespace(), '');
589 + endif;
590 + return array_unique($ns);
591 + } /* SyndicatedPost::xpath_possible_namespaces() */
592 +
593 + function content () {
594 + $content = NULL;
379 595 if (isset($this->item['atom_content'])) :
380 596 $content = $this->item['atom_content'];
381 - elseif (isset($this->item['atom']['atom_content'])) :
382 - $content = $this->item['atom']['atom_content'];
383 -
384 - // Some exotics: back in the day, before widespread convergence
385 - // on content:encoding, some RSS feeds took advantage of XML
386 - // namespaces to use an inline xhtml:body or xhtml:div element
387 - // for full-content HTML. (E.g. Sam Ruby's feed, IIRC.)
388 597 elseif (isset($this->item['xhtml']['body'])) :
389 598 $content = $this->item['xhtml']['body'];
390 599 elseif (isset($this->item['xhtml']['div'])) :
391 600 $content = $this->item['xhtml']['div'];
392 -
393 - // content:encoded, most common method of providing full HTML in
394 - // RSS 2.0 feeds.
395 601 elseif (isset($this->item['content']['encoded']) and $this->item['content']['encoded']):
396 602 $content = $this->item['content']['encoded'];
397 -
398 - // Fall back on elements that sometimes may contain full HTML
399 - // but sometimes not.
400 - elseif ( ! $params['full only']) :
401 -
402 - // description element is sometimes used for full HTML
403 - // sometimes for summary text in RSS. (By the letter of
404 - // the standard, it should just be for summary text.)
405 - if (isset($this->item['description'])) :
406 - $content = $this->item['description'];
407 - endif;
408 -
603 + elseif (isset($this->item['description'])) :
604 + $content = $this->item['description'];
409 605 endif;
410 -
411 606 return $content;
412 607 } /* SyndicatedPost::content() */
413 608
414 - public function excerpt () {
609 + function excerpt () {
415 610 # Identify and sanitize excerpt: atom:summary, or rss:description
416 611 $excerpt = $this->entry->get_description();
417 -
612 +
418 613 # Many RSS feeds use rss:description, inadvisably, to
419 614 # carry the entire post (typically with escaped HTML).
420 615 # If that's what happened, we don't want the full
421 616 # content for the excerpt.
422 617 $content = $this->content();
618 +
619 + // Ignore whitespace, case, and tag cruft.
620 + $theExcerpt = preg_replace('/\s+/', '', strtolower(strip_tags($excerpt)));
621 + $theContent = preg_replace('/\s+/', '', strtolower(strip_tags($content)));
423 622
424 - // Ignore whitespace, case, and tag cruft.
425 - $theExcerpt = preg_replace('/\s+/', '', strtolower(strip_tags(html_entity_decode($excerpt))));
426 - $theContent = preg_replace('/\s+/', '', strtolower(strip_tags(html_entity_decode($content))));
427 623 if ( empty($excerpt) or $theExcerpt == $theContent ) :
428 624 # If content is available, generate an excerpt.
429 625 if ( strlen(trim($content)) > 0 ) :
430 626 $excerpt = strip_tags($content);
431 627 if (strlen($excerpt) > 255) :
432 - if (is_object($this->link) and is_object($this->link->simplepie)) :
433 - $encoding = $this->link->simplepie->get_encoding();
434 - else :
435 - $encoding = get_option('blog_charset', 'utf8');
436 - endif;
437 - $excerpt = mb_substr($excerpt,0,252,$encoding).'...';
628 + $excerpt = substr($excerpt,0,252).'...';
438 629 endif;
439 630 endif;
440 631 endif;
441 -
442 632 return $excerpt;
443 633 } /* SyndicatedPost::excerpt() */
444 634
445 - /**
446 - * SyndicatedPost::permalink: returns the permalink for the post, as provided by the
447 - * source feed.
448 - *
449 - * @return string The URL of the original permalink for this syndicated post
450 - */
451 - public function permalink () {
635 + function permalink () {
452 636 // Handles explicit <link> elements and also RSS 2.0 cases with
453 637 // <guid isPermaLink="true">, etc. Hooray!
454 638 $permalink = $this->entry->get_link();
455 639 return $permalink;
456 - } /* SyndicatedPost::permalink () */
640 + }
457 641
458 - public function created ($params = array()) {
459 - $unfiltered = false; // $default = NULL; // seems to be unused on this function (gwyneth 20230916)
642 + function created ($params = array()) {
643 + $unfiltered = false; $default = NULL;
460 644 extract($params);
461 -
645 +
462 646 $date = '';
463 647 if (isset($this->item['dc']['created'])) :
464 648 $date = $this->item['dc']['created'];
465 649 elseif (isset($this->item['dcterms']['created'])) :
@@ -468,25 +652,25 @@
468 652 $date = $this->item['created'];
469 653 endif;
470 654
471 655 $time = new FeedTime($date);
472 - $tstamp = $time->timestamp();
473 - if ( ! $unfiltered) :
474 - apply_filters('syndicated_item_created', $tstamp, $this);
656 + $ts = $time->timestamp();
657 + if (!$unfiltered) :
658 + apply_filters('syndicated_item_created', $ts, $this);
475 659 endif;
476 - return $tstamp;
660 + return $ts;
477 661 } /* SyndicatedPost::created() */
478 662
479 - public function published ($params = array(), $default = NULL) {
663 + function published ($params = array(), $default = NULL) {
480 664 $fallback = true; $unfiltered = false;
481 - if ( !is_array($params)) : // Old style
665 + if (!is_array($params)) : // Old style
482 666 $fallback = $params;
483 667 else : // New style
484 668 extract($params);
485 669 endif;
486 -
670 +
487 671 $date = '';
488 - $tstamp = null;
672 + $ts = null;
489 673
490 674 # RSS is a fucking mess. Figure out whether we have a date in
491 675 # <dc:date>, <issued>, <pubDate>, etc., and get it into Unix
492 676 # epoch format for reformatting. If we can't find anything,
@@ -501,34 +685,34 @@
501 685 $date = $this->item['issued'];
502 686 elseif (isset($this->item['pubdate'])): // RSS 2.0
503 687 $date = $this->item['pubdate'];
504 688 endif;
505 -
689 +
506 690 if (strlen($date) > 0) :
507 691 $time = new FeedTime($date);
508 - $tstamp = $time->timestamp();
692 + $ts = $time->timestamp();
509 693 elseif ($fallback) : // Fall back to <updated> / <modified> if present
510 - $tstamp = $this->updated(/*fallback=*/ false, /*default=*/ $default);
694 + $ts = $this->updated(/*fallback=*/ false, /*default=*/ $default);
511 695 endif;
512 -
696 +
513 697 # If everything failed, then default to the current time.
514 - if (is_null($tstamp)) :
698 + if (is_null($ts)) :
515 699 if (-1 == $default) :
516 - $tstamp = time();
700 + $ts = time();
517 701 else :
518 - $tstamp = $default;
702 + $ts = $default;
519 703 endif;
520 704 endif;
521 -
522 - if ( ! $unfiltered) :
523 - $tstamp = apply_filters('syndicated_item_published', $tstamp, $this);
705 +
706 + if (!$unfiltered) :
707 + $ts = apply_filters('syndicated_item_published', $ts, $this);
524 708 endif;
525 - return $tstamp;
709 + return $ts;
526 710 } /* SyndicatedPost::published() */
527 711
528 - public function updated ($params = array(), $default = -1) {
712 + function updated ($params = array(), $default = -1) {
529 713 $fallback = true; $unfiltered = false;
530 - if ( !is_array($params)) : // Old style
714 + if (!is_array($params)) : // Old style
531 715 $fallback = $params;
532 716 else : // New style
533 717 extract($params);
534 718 endif;
@@ -533,9 +717,9 @@
533 717 extract($params);
534 718 endif;
535 719
536 720 $date = '';
537 - $tstamp = null;
721 + $ts = null;
538 722
539 723 # As far as I know, only dcterms and Atom have reliable ways to
540 724 # specify when something was *modified* last. If neither is
541 725 # available, then we'll try to get the time of publication.
@@ -547,29 +731,29 @@
547 731 $date = $this->item['modified'];
548 732 elseif (isset($this->item['updated'])): // Atom 1.0
549 733 $date = $this->item['updated'];
550 734 endif;
551 -
735 +
552 736 if (strlen($date) > 0) :
553 737 $time = new FeedTime($date);
554 - $tstamp = $time->timestamp();
738 + $ts = $time->timestamp();
555 739 elseif ($fallback) : // Fall back to issued / dc:date
556 - $tstamp = $this->published(/*fallback=*/ false, /*default=*/ $default);
740 + $ts = $this->published(/*fallback=*/ false, /*default=*/ $default);
557 741 endif;
558 -
742 +
559 743 # If everything failed, then default to the current time.
560 - if (is_null($tstamp)) :
744 + if (is_null($ts)) :
561 745 if (-1 == $default) :
562 - $tstamp = time();
746 + $ts = time();
563 747 else :
564 - $tstamp = $default;
748 + $ts = $default;
565 749 endif;
566 750 endif;
567 751
568 - if ( ! $unfiltered) :
569 - $tstamp = apply_filters('syndicated_item_updated', $tstamp, $this);
752 + if (!$unfiltered) :
753 + apply_filters('syndicated_item_updated', $ts, $this);
570 754 endif;
571 - return $tstamp;
755 + return $ts;
572 756 } /* SyndicatedPost::updated() */
573 757
574 758 var $_hashes = array();
575 759 function stored_hashes ($id = NULL) {
@@ -576,85 +760,35 @@
576 760 if (is_null($id)) :
577 761 $id = $this->wp_id();
578 762 endif;
579 763
580 - if ( !isset($this->_hashes[$id])) :
764 + if (!isset($this->_hashes[$id])) :
581 765 $this->_hashes[$id] = get_post_custom_values(
582 766 'syndication_item_hash', $id
583 767 );
584 - if (is_null($this->_hashes[$id])) :
585 - $this->_hashes[$id] = array();
586 - endif;
587 768 endif;
588 769 return $this->_hashes[$id];
589 770 }
590 771
591 - function update_hash ($hashed = true) {
592 - // Basis for tracking possible changes to item.
593 - $hash = array(
594 - "title" => $this->entry->get_title(),
595 - "link" => $this->permalink(),
596 - "content" => $this->content(),
597 - "excerpt" => $this->excerpt(),
598 - );
599 -
600 - if ($hashed) :
601 - $hash = md5(serialize($hash));
602 - endif;
603 -
604 - return $hash;
772 + function update_hash () {
773 + return md5(serialize($this->item));
605 774 } /* SyndicatedPost::update_hash() */
606 775
607 - /**
608 - * SyndicatedPost::normalize_guid_prefix(): generates a normalized URL
609 - * prefix (including scheme, authority, full path, and the beginning of
610 - * a query string) for creating guids that conform to WordPress's
611 - * internal constraints on the URL space for valid guids. To create a
612 - * normalized guid, just concatenate a valid URL query parameter value
613 - * to the returned URL.
614 - *
615 - * @return string The URL prefix generated.
616 - *
617 - * @uses trailingslashit()
618 - * @uses home_url()
619 - * @uses apply_filters()
620 - */
621 - static function normalize_guid_prefix () {
622 - $scheme = 'http';
623 - $url = trailingslashit(home_url(/*path=*/ '', $scheme));
624 - return apply_filters('syndicated_item_guid_normalized_prefix', $url . '?guid=', $scheme);
625 - } /* SyndicatedPost::normalize_guid_prefix() */
626 -
627 - static function normalize_guid ($guid) {
628 - $guid = trim($guid);
776 + /*static*/ function normalize_guid_prefix () {
777 + return trailingslashit(get_bloginfo('url')).'?guid=';
778 + }
779 +
780 + /*static*/ function normalize_guid ($guid) {
629 781 if (preg_match('/^[0-9a-z]{32}$/i', $guid)) : // MD5
630 - $guid = SyndicatedPost::normalize_guid_prefix().strtolower($guid);
631 - elseif ((strlen(esc_url($guid)) == 0) or (esc_url($guid) != $guid)) :
782 + $guid = SyndicatedPost::normalize_Guid_prefix().strtolower($guid);
783 + elseif (strlen(esc_url($guid)) == 0) :
632 784 $guid = SyndicatedPost::normalize_guid_prefix().md5($guid);
633 785 endif;
634 - $guid = trim($guid);
635 -
786 +
636 787 return $guid;
637 788 } /* SyndicatedPost::normalize_guid() */
638 -
639 - static function alternative_guid_prefix () {
640 - $scheme = 'https';
641 - $url = trailingslashit(home_url(/*path=*/ '', $scheme));
642 - return apply_filters('syndicated_item_guid_normalized_prefix', $url . '?guid=', $scheme);
643 - }
644 - static function alternative_guid ($guid) {
645 - $guid = trim($guid);
646 - if (preg_match('/^[0-9a-z]{32}$/i', $guid)) : // MD5
647 - $guid = SyndicatedPost::alternative_guid_prefix().strtolower($guid);
648 - elseif ((strlen(esc_url($guid)) == 0) or (esc_url($guid) != $guid)) :
649 - $guid = SyndicatedPost::alternative_guid_prefix().md5($guid);
650 - endif;
651 - $guid = trim($guid);
652 -
653 - return $guid;
654 - } /* SyndicatedPost::normalize_guid() */
655 -
656 - public function guid () {
789 +
790 + function guid () {
657 791 $guid = null;
658 792 if (isset($this->item['id'])): // Atom 0.3 / 1.0
659 793 $guid = $this->item['id'];
660 794 elseif (isset($this->item['atom']['id'])) : // Namespaced Atom
@@ -663,14 +797,14 @@
663 797 $guid = $this->item['guid'];
664 798 elseif (isset($this->item['dc']['identifier'])) : // yeah, right
665 799 $guid = $this->item['dc']['identifier'];
666 800 endif;
667 -
801 +
668 802 // Un-set or too long to use as-is. Generate a tag: URI.
669 803 if (is_null($guid) or strlen($guid) > 250) :
670 804 // In case we need to check this again
671 805 $original_guid = $guid;
672 -
806 +
673 807 // The feed does not seem to have provided us with a
674 808 // usable unique identifier, so we'll have to cobble
675 809 // together a tag: URI that might work for us. The base
676 810 // of the URI will be the host name of the feed source ...
@@ -684,19 +818,19 @@
684 818 // gets clipped by MySQL, uniqueness tests will fail
685 819 // forever after and the post will be endlessly
686 820 // reduplicated. So, instead, Guids Of A Certain Length
687 821 // are hashed down into a nice, manageable tag: URI.
688 - if ( !is_null($original_guid)) :
822 + if (!is_null($original_guid)) :
689 823 $guid .= ',2010-12-03:id.'.md5($original_guid);
690 -
824 +
691 825 // If we have a date of creation, then we can use that
692 826 // to uniquely identify the item. (On the other hand, if
693 827 // the feed producer was consicentious enough to
694 828 // generate dates of creation, she probably also was
695 829 // conscientious enough to generate unique identifiers.)
696 - elseif ( !is_null($this->created())) :
830 + elseif (!is_null($this->created())) :
697 831 $guid .= '://post.'.date('YmdHis', $this->created());
698 -
832 +
699 833 // Otherwise, use both the URI of the item, *and* the
700 834 // item's title. We have to use both because titles are
701 835 // often not unique, and sometimes links aren't unique
702 836 // either (e.g. Bitch (S)HITLIST, Mozilla Dot Org news,
@@ -705,86 +839,65 @@
705 839 // this is about the best we can do.
706 840 else :
707 841 $link = $this->permalink();
708 842 if (is_null($link)) : $link = $this->link->uri(); endif;
709 - $guid .= '://'.md5($link.'/'.$this->title());
843 + $guid .= '://'.md5($link.'/'.$this->item['title']);
710 844 endif;
711 845 endif;
712 846 return $guid;
713 847 } /* SyndicatedPost::guid() */
714 -
715 - public function author () {
848 +
849 + function author () {
716 850 $author = array ();
717 -
718 - $aa = $this->entry->get_authors();
719 - if (is_countable($aa) and count($aa) > 0) :
720 - $a = reset($aa);
721 -
722 - $author = array(
723 - 'name' => $a->get_name(),
724 - 'email' => $a->get_email(),
725 - 'uri' => $a->get_link(),
726 - );
727 - endif;
728 -
729 - if (FEEDWORDPRESS_COMPATIBILITY) :
730 - // Search through the MagpieRSS elements: Atom, Dublin Core, RSS
731 - if (isset($this->item['author_name'])):
732 - $author['name'] = $this->item['author_name'];
733 - elseif (isset($this->item['dc']['creator'])):
734 - $author['name'] = $this->item['dc']['creator'];
735 - elseif (isset($this->item['dc']['contributor'])):
736 - $author['name'] = $this->item['dc']['contributor'];
737 - elseif (isset($this->feed->channel['dc']['creator'])) :
738 - $author['name'] = $this->feed->channel['dc']['creator'];
739 - elseif (isset($this->feed->channel['dc']['contributor'])) :
740 - $author['name'] = $this->feed->channel['dc']['contributor'];
741 - elseif (isset($this->feed->channel['author_name'])) :
742 - $author['name'] = $this->feed->channel['author_name'];
743 - elseif ($this->feed->is_rss() and isset($this->item['author'])) :
744 - // The author element in RSS is allegedly an
745 - // e-mail address, but lots of people don't use
746 - // it that way. So let's make of it what we can.
747 - $author = parse_email_with_realname($this->item['author']);
748 -
749 - if ( !isset($author['name'])) :
750 - if (isset($author['email'])) :
751 - $author['name'] = $author['email'];
752 - else :
753 - $author['name'] = $this->feed->channel['title'];
754 - endif;
851 +
852 + if (isset($this->item['author_name'])):
853 + $author['name'] = $this->item['author_name'];
854 + elseif (isset($this->item['dc']['creator'])):
855 + $author['name'] = $this->item['dc']['creator'];
856 + elseif (isset($this->item['dc']['contributor'])):
857 + $author['name'] = $this->item['dc']['contributor'];
858 + elseif (isset($this->feed->channel['dc']['creator'])) :
859 + $author['name'] = $this->feed->channel['dc']['creator'];
860 + elseif (isset($this->feed->channel['dc']['contributor'])) :
861 + $author['name'] = $this->feed->channel['dc']['contributor'];
862 + elseif (isset($this->feed->channel['author_name'])) :
863 + $author['name'] = $this->feed->channel['author_name'];
864 + elseif ($this->feed->is_rss() and isset($this->item['author'])) :
865 + // The author element in RSS is allegedly an
866 + // e-mail address, but lots of people don't use
867 + // it that way. So let's make of it what we can.
868 + $author = parse_email_with_realname($this->item['author']);
869 +
870 + if (!isset($author['name'])) :
871 + if (isset($author['email'])) :
872 + $author['name'] = $author['email'];
873 + else :
874 + $author['name'] = $this->feed->channel['title'];
755 875 endif;
756 876 endif;
877 + elseif ($this->link->name()) :
878 + $author['name'] = $this->link->name();
879 + else :
880 + $url = parse_url($this->link->uri());
881 + $author['name'] = $url['host'];
757 882 endif;
758 -
759 - if ( !isset($author['name']) or is_null($author['name'])) :
760 - // Nothing found. Try some crappy defaults.
761 - if ($this->link->name()) :
762 - $author['name'] = $this->link->name();
763 - else :
764 - $url = parse_url($this->link->uri());
765 - $author['name'] = $url['host'];
766 - endif;
883 +
884 + if (isset($this->item['author_email'])):
885 + $author['email'] = $this->item['author_email'];
886 + elseif (isset($this->feed->channel['author_email'])) :
887 + $author['email'] = $this->feed->channel['author_email'];
767 888 endif;
768 -
769 - if (FEEDWORDPRESS_COMPATIBILITY) :
770 - if (isset($this->item['author_email'])):
771 - $author['email'] = $this->item['author_email'];
772 - elseif (isset($this->feed->channel['author_email'])) :
773 - $author['email'] = $this->feed->channel['author_email'];
774 - endif;
775 -
776 - if (isset($this->item['author_uri'])):
777 - $author['uri'] = $this->item['author_uri'];
778 - elseif (isset($this->item['author_url'])):
779 - $author['uri'] = $this->item['author_url'];
780 - elseif (isset($this->feed->channel['author_uri'])) :
781 - $author['uri'] = $this->item['author_uri'];
782 - elseif (isset($this->feed->channel['author_url'])) :
783 - $author['uri'] = $this->item['author_url'];
784 - elseif (isset($this->feed->channel['link'])) :
785 - $author['uri'] = $this->feed->channel['link'];
786 - endif;
889 +
890 + if (isset($this->item['author_uri'])):
891 + $author['uri'] = $this->item['author_uri'];
892 + elseif (isset($this->item['author_url'])):
893 + $author['uri'] = $this->item['author_url'];
894 + elseif (isset($this->feed->channel['author_uri'])) :
895 + $author['uri'] = $this->item['author_uri'];
896 + elseif (isset($this->feed->channel['author_url'])) :
897 + $author['uri'] = $this->item['author_url'];
898 + elseif (isset($this->feed->channel['link'])) :
899 + $author['uri'] = $this->feed->channel['link'];
787 900 endif;
788 901
789 902 return $author;
790 903 } /* SyndicatedPost::author() */
@@ -789,121 +902,8 @@
789 902 return $author;
790 903 } /* SyndicatedPost::author() */
791 904
792 905 /**
793 - * SyndicatedPost::get_terms_from_settings(): Return an array of terms to associate with the incoming
794 - * post based on the Categories, Tags, and other terms associated with each new post by the user's
795 - * settings (global and feed-specific).
796 - *
797 - * @since 2016.0331
798 - * @return array of lists, each element has the taxonomy for a key ('category', 'post_tag', etc.),
799 - * and a list of term codes (either alphanumeric names, or ID numbers encoded in a format that
800 - * SyndicatedLink::category_ids() can understand) within that taxonomy
801 - *
802 - */
803 - public function get_terms_from_settings () {
804 - // Categories: start with default categories, if any.
805 - $cats = array();
806 - if ('no' != $this->link->setting('add/category', NULL, 'yes')) :
807 - $fc = get_option("feedwordpress_syndication_cats");
808 - if ($fc) :
809 - $cats = array_merge($cats, explode("\n", $fc));
810 - endif;
811 - endif;
812 -
813 - $fc = $this->link->setting('cats',NULL, array());
814 - if (is_array($fc)) :
815 - $cats = array_merge($cats, $fc);
816 - endif;
817 - $preset_terms['category'] = $cats;
818 -
819 - // Tags: start with default tags, if any
820 - $tags = array();
821 - if ('no' != $this->link->setting('add/post_tag', NULL, 'yes')) :
822 - $ft = get_option("feedwordpress_syndication_tags", NULL);
823 - $tags = (is_null($ft) ? array() : explode(FEEDWORDPRESS_CAT_SEPARATOR, $ft));
824 - endif;
825 -
826 - $ft = $this->link->setting('tags', NULL, array());
827 - if (is_array($ft)) :
828 - $tags = array_merge($tags, $ft);
829 - endif;
830 - $preset_terms['post_tag'] = $tags;
831 -
832 - $taxonomies = $this->link->taxonomies();
833 - $feedTerms = $this->link->setting('terms', NULL, array());
834 - $globalTerms = get_option('feedwordpress_syndication_terms', array());
835 - $specials = array('category' => 'cats', 'post_tag' => 'tags');
836 -
837 - foreach ($taxonomies as $tax) :
838 - // category and tag settings have already previously been handled
839 - // but if this is from another taxonomy, then...
840 - if ( !isset($specials[$tax])) :
841 - $terms = array();
842 -
843 - // See if we should get the globals
844 - if ('no' != $this->link->setting("add/$tax", NULL, 'yes')) :
845 - if (isset($globalTerms[$tax])) :
846 - $terms = $globalTerms[$tax];
847 - endif;
848 - endif;
849 -
850 - // Now merge in the locals
851 - if (isset($feedTerms[$tax])) :
852 - $terms = array_merge($terms, $feedTerms[$tax]);
853 - endif;
854 -
855 - // That's all, folks.
856 - $preset_terms[$tax] = $terms;
857 - endif;
858 - endforeach;
859 -
860 - return $preset_terms;
861 - } /* SyndicatedPost::get_terms_from_settings () */
862 -
863 - /**
864 - * SyndicatedPost::get_terms_from_feeds(): Return an array of terms to associate with the incoming
865 - * post based on the contents of the subscribed feed (atom:category and rss:category elements, dc:subject
866 - * elements, tags embedded using microformats in the post content, etc.)
867 - *
868 - * @since 2016.0331
869 - * @return array of lists, each element has the taxonomy for a key ('category', 'post_tag', etc.),
870 - * and a list of alphanumeric term names
871 - */
872 - public function get_terms_from_feeds () {
873 - // Now add categories from the post, if we have 'em
874 - $cats = array();
875 - $post_cats = $this->entry->get_categories();
876 - if (is_array($post_cats)) : foreach ($post_cats as $cat) :
877 - $cat_name = $cat->get_term();
878 - if ( ! $cat_name) : $cat_name = $cat->get_label(); endif;
879 -
880 - if ($this->link->setting('cat_split', NULL, NULL)) :
881 - $pcre = "\007".$this->feedmeta['cat_split']."\007";
882 - $cats = array_merge(
883 - $cats,
884 - preg_split(
885 - $pcre,
886 - $cat_name,
887 - -1 /*=no limit*/,
888 - PREG_SPLIT_NO_EMPTY
889 - )
890 - );
891 - else :
892 - $cats[] = $cat_name;
893 - endif;
894 - endforeach; endif;
895 -
896 - $feed_terms['category'] = apply_filters('syndicated_item_categories', $cats, $this);
897 -
898 - // Scan post for /a[@rel='tag'] and use as tags if present
899 - $tags = $this->inline_tags();
900 - $feed_terms['post_tag'] = apply_filters('syndicated_item_tags', $tags, $this);
901 -
902 - return $feed_terms;
903 - } /* SyndicatedPost::get_terms_from_feeds () */
904 -
905 - /**
906 906 * SyndicatedPost::inline_tags: Return a list of all the tags embedded
907 907 * in post content using the a[@rel="tag"] microformat.
908 908 *
909 909 * @since 2010.0630
@@ -913,9 +913,9 @@
913 913 $tags = array();
914 914 $content = $this->content();
915 915 $pattern = FeedWordPressHTML::tagWithAttributeRegex('a', 'rel', 'tag');
916 916 preg_match_all($pattern, $content, $refs, PREG_SET_ORDER);
917 - if (is_countable($refs) and count($refs) > 0) :
917 + if (count($refs) > 0) :
918 918 foreach ($refs as $ref) :
919 919 $tag = FeedWordPressHTML::tagWithAttributeMatch($ref);
920 920 $tags[] = $tag['content'];
921 921 endforeach;
@@ -921,9 +921,9 @@
921 921 endforeach;
922 922 endif;
923 923 return $tags;
924 924 }
925 -
925 +
926 926 /**
927 927 * SyndicatedPost::isTaggedAs: Test whether a feed item is
928 928 * tagged / categorized with a given string. Case and leading and
929 929 * trailing whitespace are ignored.
@@ -929,9 +929,9 @@
929 929 * trailing whitespace are ignored.
930 930 *
931 931 * @param string $tag Tag to check for
932 932 *
933 - * @return bool Whether or not at least one of the categories / tags on
933 + * @return bool Whether or not at least one of the categories / tags on
934 934 * $this->item is set to $tag (modulo case and leading and trailing
935 935 * whitespace)
936 936 */
937 937 function isTaggedAs ($tag) {
@@ -944,9 +944,9 @@
944 944 // If we have the new MagpieRSS, the number of category elements
945 945 // on this item is stored under index "category#".
946 946 if (isset($this->item['category#'])) :
947 947 $numberOfCategories = (int) $this->item['category#'];
948 -
948 +
949 949 // We REALLY shouldn't have the old and busted MagpieRSS, but in
950 950 // case we do, it doesn't support multiple categories, but there
951 951 // might still be a single value under the "category" index.
952 952 elseif (isset($this->item['category'])) :
@@ -985,27 +985,27 @@
985 985 * that will be returned to only those with a MIME type which
986 986 * matches this regular expression.
987 987 * @return array
988 988 */
989 - function enclosures( $type = '/.*/' ) {
989 + function enclosures ($type = '/.*/') {
990 990 $enclosures = array();
991 991
992 - if ( isset( $this->item['enclosure#'] ) ) :
992 + if (isset($this->item['enclosure#'])) :
993 993 // Loop through enclosure, enclosure#2, enclosure#3, ....
994 - for ( $i = 1; $i <= $this->item['enclosure#']; $i++ ) :
995 - $eid = ( ( $i > 1 ) ? "#{$i}" : "" ); // this was set as #{$id} — was that a typo? (gwyneth 20230919)
994 + for ($i = 1; $i <= $this->item['enclosure#']; $i++) :
995 + $eid = (($i > 1) ? "#{$id}" : "");
996 996
997 997 // Does it match the type we want?
998 - if ( preg_match($type, $this->item["enclosure{$eid}@type"] ) ) :
998 + if (preg_match($type, $this->item["enclosure{$eid}@type"])) :
999 999 $enclosures[] = array(
1000 - "url" => $this->item["enclosure{$eid}@url"],
1001 - "type" => $this->item["enclosure{$eid}@type"],
1000 + "url" => $this->item["enclosure{$eid}@url"],
1001 + "type" => $this->item["enclosure{$eid}@type"],
1002 1002 "length" => $this->item["enclosure{$eid}@length"],
1003 1003 );
1004 1004 endif;
1005 1005 endfor;
1006 1006 endif;
1007 - return $enclosures;
1007 + return $enclosures;
1008 1008 } /* SyndicatedPost::enclosures() */
1009 1009
1010 1010 function source ($what = NULL) {
1011 1011 $ret = NULL;
@@ -1014,9 +1014,9 @@
1014 1014 $ret = array();
1015 1015 $ret['title'] = $source->get_title();
1016 1016 $ret['uri'] = $source->get_link();
1017 1017 $ret['feed'] = $source->get_link(0, 'self');
1018 -
1018 +
1019 1019 if ($id_tags = $source->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'id')) :
1020 1020 $ret['id'] = $id_tags[0]['data'];
1021 1021 elseif ($id_tags = $source->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'id')) :
1022 1022 $ret['id'] = $id_tags[0]['data'];
@@ -1027,18 +1027,18 @@
1027 1027 elseif ($id_tags = $source->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'guid')) :
1028 1028 $ret['id'] = $id_tags[0]['data'];
1029 1029 endif;
1030 1030 endif;
1031 -
1032 - if ( !is_null($what) and is_scalar($what)) :
1031 +
1032 + if (!is_null($what) and is_scalar($what)) :
1033 1033 $ret = $ret[$what];
1034 1034 endif;
1035 1035 return $ret;
1036 1036 }
1037 -
1037 +
1038 1038 function comment_link () {
1039 1039 $url = null;
1040 -
1040 +
1041 1041 // RSS 2.0 has a standard <comments> element:
1042 1042 // "<comments> is an optional sub-element of <item>. If present,
1043 1043 // it is the url of the comments page for the item."
1044 1044 // <http://cyber.law.harvard.edu/rss/rss.html#ltcommentsgtSubelementOfLtitemgt>
@@ -1049,15 +1049,15 @@
1049 1049 // The convention in Atom feeds is to use a standard <link>
1050 1050 // element with @rel="replies" and @type="text/html".
1051 1051 // Unfortunately, SimplePie_Item::get_links() allows us to filter
1052 1052 // by the value of @rel, but not by the value of @type. *sigh*
1053 -
1053 +
1054 1054 // Try Atom 1.0 first
1055 1055 $linkElements = $this->entry->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'link');
1056 -
1056 +
1057 1057 // Fall back and try Atom 0.3
1058 1058 if (is_null($linkElements)) : $linkElements = $this->entry->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'link'); endif;
1059 -
1059 +
1060 1060 // Now loop through the elements, screening by @rel and @type
1061 1061 if (is_array($linkElements)) : foreach ($linkElements as $link) :
1062 1062 $rel = (isset($link['attribs']['']['rel']) ? $link['attribs']['']['rel'] : 'alternate');
1063 1063 $type = (isset($link['attribs']['']['type']) ? $link['attribs']['']['type'] : NULL);
@@ -1143,15 +1143,14 @@
1143 1143
1144 1144 function resolve_single_relative_uri ($refs) {
1145 1145 $tag = FeedWordPressHTML::attributeMatch($refs);
1146 1146 $url = SimplePie_Misc::absolutize_url($tag['value'], $this->_base);
1147 -
1148 1147 return $tag['prefix'] . $url . $tag['suffix'];
1149 1148 } /* function SyndicatedPost::resolve_single_relative_uri() */
1150 1149
1151 - static function resolve_relative_uris ($content, $obj) {
1150 + function resolve_relative_uris ($content, $obj) {
1152 1151 $set = $obj->link->setting('resolve relative', 'resolve_relative', 'yes');
1153 - if ($set and $set != 'no') :
1152 + if ($set and $set != 'no') :
1154 1153 // Fallback: if we don't have anything better, use the
1155 1154 // item link from the feed
1156 1155 $obj->_base = $obj->permalink(); // Reset the base for resolving relative URIs
1157 1156
@@ -1164,22 +1163,16 @@
1164 1163
1165 1164 foreach ($obj->uri_attrs as $pair) :
1166 1165 list($tag, $attr) = $pair;
1167 1166 $pattern = FeedWordPressHTML::attributeRegex($tag, $attr);
1168 -
1169 - // FIXME: Encountered issue while testing an extremely long (= 88827 characters) item
1170 - // Relying on preg_replace_callback() here can cause a PHP seg fault on my development
1171 - // server. preg_match_all() causes a similar problem. Apparently this is a PCRE issue
1172 - // Cf. discussion of similar issue <https://bugs.php.net/bug.php?id=65009>
1173 1167 $content = preg_replace_callback (
1174 1168 $pattern,
1175 - array($obj, 'resolve_single_relative_uri'),
1169 + array(&$obj, 'resolve_single_relative_uri'),
1176 1170 $content
1177 1171 );
1178 -
1179 1172 endforeach;
1180 1173 endif;
1181 -
1174 +
1182 1175 return $content;
1183 1176 } /* function SyndicatedPost::resolve_relative_uris () */
1184 1177
1185 1178 var $strip_attrs = array (
@@ -1192,9 +1185,9 @@
1192 1185 $tag = FeedWordPressHTML::attributeMatch($refs);
1193 1186 return $tag['before_attribute'].$tag['after_attribute'];
1194 1187 }
1195 1188
1196 - static function sanitize_content ($content, $obj) {
1189 + function sanitize_content ($content, $obj) {
1197 1190 # This kind of sucks. I intend to replace it with
1198 1191 # lib_filter sometime soon.
1199 1192 foreach ($obj->strip_attrs as $pair):
1200 1193 list($tag,$attr) = $pair;
@@ -1201,9 +1194,9 @@
1201 1194 $pattern = FeedWordPressHTML::attributeRegex($tag, $attr);
1202 1195
1203 1196 $content = preg_replace_callback (
1204 1197 $pattern,
1205 - array($obj, 'strip_attribute_from_tag'),
1198 + array(&$obj, 'strip_attribute_from_tag'),
1206 1199 $content
1207 1200 );
1208 1201 endforeach;
1209 1202 return $content;
@@ -1229,140 +1222,77 @@
1229 1222 * match the latest revision, or a previously syndicated post that is
1230 1223 * still up-to-date.
1231 1224 *
1232 1225 * @return int A status code representing the freshness of the post
1233 - * -1 = post already syndicated; has a revision that needs to be stored, but not updated to
1234 1226 * 0 = post already syndicated; no update needed
1235 1227 * 1 = post already syndicated, but needs to be updated to latest
1236 1228 * 2 = post has not yet been syndicated; needs to be created
1237 1229 */
1238 - function freshness ($format = 'number') {
1230 + function freshness () {
1231 + global $wpdb;
1239 1232
1240 1233 if ($this->filtered()) : // This should never happen.
1241 - FeedWordPressDiagnostic::critical_bug('SyndicatedPost', $this, __LINE__, __FILE__);
1234 + FeedWordPress::critical_bug('SyndicatedPost', $this, __LINE__, __FILE__);
1242 1235 endif;
1243 -
1236 +
1244 1237 if (is_null($this->_freshness)) : // Not yet checked and cached.
1245 - $guid = $this->post['guid'];
1246 - $eguid = esc_sql($this->post['guid']);
1238 + $guid = $wpdb->escape($this->guid());
1247 1239
1248 1240 $q = new WP_Query(array(
1249 1241 'fields' => '_synfresh', // id, guid, post_modified_gmt
1250 - 'ignore_sticky_posts' => true,
1251 - 'guid' => $eguid, // it's always better to use the escaped version, right? (gwyneth 20230915)
1242 + 'guid' => $this->guid(),
1252 1243 ));
1253 1244
1254 1245 $old_post = NULL;
1255 1246 if ($q->have_posts()) :
1256 1247 while ($q->have_posts()) : $q->the_post();
1257 - if (get_post_type($q->post->ID) == $this->post['post_type']):
1258 - $old_post = $q->post;
1259 - endif;
1248 + $old_post = $q->post;
1260 1249 endwhile;
1261 1250 endif;
1262 -
1251 +
1263 1252 if (is_null($old_post)) : // No post with this guid
1264 - FeedWordPress::diagnostic('feed_items:freshness', 'Item ['.$guid.'] "'.$this->entry->get_title().'" is a NEW POST.');
1253 + FeedWordPress::diagnostic('feed_items:freshness', 'Item ['.$this->guid().'] "'.$this->entry->get_title().'" is a NEW POST.');
1265 1254 $this->_wp_id = NULL;
1266 1255 $this->_freshness = 2; // New content
1267 1256 else :
1268 - // Presume there is nothing new until we find
1269 - // something new.
1270 - $updated = false;
1271 - $live = false;
1257 + preg_match('/([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+):([0-9]+)/', $old_post->post_modified_gmt, $backref);
1272 1258
1273 - // Pull the list of existing revisions to get
1274 - // timestamps.
1275 - $revisions = wp_get_post_revisions($old_post->ID);
1276 - foreach ($revisions as $rev) :
1277 - $revisions_ts[] = mysql2date('G', $rev->post_modified_gmt);
1278 - endforeach;
1279 -
1280 - $revisions_ts[] = mysql2date('G', $old_post->post_modified_gmt);
1281 - $last_rev_ts = end($revisions_ts);
1259 + $last_rev_ts = gmmktime($backref[4], $backref[5], $backref[6], $backref[2], $backref[3], $backref[1]);
1282 1260 $updated_ts = $this->updated(/*fallback=*/ true, /*default=*/ NULL);
1283 -
1284 - // If we have an explicit updated timestamp,
1285 - // check that against existing stamps.
1286 - if ( !is_null($updated_ts)) :
1287 - $updated = !in_array($updated_ts, $revisions_ts);
1288 -
1289 - // If this a newer revision, make it go
1290 - // live. If an older one, just record
1291 - // the contents.
1292 - $live = ($updated and ($updated_ts > $last_rev_ts));
1293 - endif;
1294 -
1295 - // This is a revision we haven't seen before, judging by the date.
1296 -
1297 - $updatedReason = NULL;
1298 - if ($updated) :
1299 - $updatedReason = preg_replace(
1300 - "/\s+/", " ",
1301 - 'has been marked with a new timestamp ('
1302 - .date('Y-m-d H:i:s', $updated_ts)
1303 - ." > "
1304 - .date('Y-m-d H:i:s', $last_rev_ts)
1305 - .')'
1306 - );
1307 -
1308 - // The date does not indicate a new revision, so
1309 - // let's check the hash.
1310 - else :
1261 +
1262 + // Check timestamps...
1263 + $updated = (
1264 + !is_null($updated_ts)
1265 + and ($updated_ts > $last_rev_ts)
1266 + );
1267 +
1268 +
1269 + if (!$updated) :
1311 1270 // Or the hash...
1312 1271 $hash = $this->update_hash();
1313 1272 $seen = $this->stored_hashes($old_post->ID);
1314 - if (is_countable($seen) and count($seen) > 0) :
1273 + if (count($seen) > 0) :
1315 1274 $updated = !in_array($hash, $seen); // Not seen yet?
1316 1275 else :
1317 1276 $updated = true; // Can't find syndication meta-data
1318 1277 endif;
1319 -
1320 - if ($updated and FeedWordPressDiagnostic::is_on('feed_items:freshness:reasons')) :
1321 - // In the absence of definitive
1322 - // timestamp information, we
1323 - // just have to assume that a
1324 - // hash we haven't seen before
1325 - // is a newer version.
1326 - $live = true;
1327 -
1328 - $updatedReason = ' has a not-yet-seen update hash: '
1329 - .MyPHP::val($hash)
1330 - .' not in {'
1331 - .implode(", ", array_map(array('FeedWordPress', 'val'), $seen))
1332 - .'}. Basis: '
1333 - .MyPHP::val(array_keys($this->update_hash(false)));
1334 - endif;
1335 1278 endif;
1336 -
1279 +
1337 1280 $frozen = false;
1338 1281 if ($updated) : // Ignore if the post is frozen
1339 1282 $frozen = ('yes' == $this->link->setting('freeze updates', 'freeze_updates', NULL));
1340 - if ( ! $frozen) :
1341 - $frozen_value = get_post_meta($old_post->ID, '_syndication_freeze_updates', /*single=*/ true);
1342 - $frozen = ( !is_null($frozen_value) and ('yes' == $frozen_value));
1343 -
1344 - if ($frozen) :
1345 - $updatedReason = ' IS BLOCKED FROM BEING UPDATED BY A UPDATE LOCK ON THIS POST, EVEN THOUGH IT '.$updatedReason;
1346 - endif;
1347 - else :
1348 - $updatedReason = ' IS BLOCKED FROM BEING UPDATED BY A FEEDWORDPRESS UPDATE LOCK, EVEN THOUGH IT '.$updatedReason;
1283 + if (!$frozen) :
1284 + $frozen_values = get_post_custom_values('_syndication_freeze_updates', $old_post->ID);
1285 + $frozen = (count($frozen_values) > 0 and 'yes' == $frozen_values[0]);
1349 1286 endif;
1350 1287 endif;
1351 - $live = ($live and ! $frozen);
1288 + $updated = ($updated and !$frozen);
1352 1289
1353 1290 if ($updated) :
1354 - FeedWordPress::diagnostic('feed_items:freshness', 'Item ['.$guid.'] "'.$this->entry->get_title().'" is an update of an existing post.');
1355 - if ( !is_null($updatedReason)) :
1356 - $updatedReason = preg_replace('/\s+/', ' ', $updatedReason);
1357 - FeedWordPress::diagnostic('feed_items:freshness:reasons', 'Item ['.$guid.'] "'.$this->entry->get_title().'" '.$updatedReason);
1358 - endif;
1359 -
1360 - $this->_freshness = apply_filters('syndicated_item_freshness', ($live ? 1 : -1), $updated, $frozen, $updated_ts, $last_rev_ts, $this);
1361 -
1362 - $this->_wp_id = $old_post->ID;
1363 - $this->_wp_post = $old_post;
1364 -
1291 + FeedWordPress::diagnostic('feed_items:freshness', 'Item ['.$this->guid().'] "'.$this->entry->get_title().'" is an update of an existing post.');
1292 + $this->_freshness = 1; // Updated content
1293 + $this->_wp_id = $old_post->id;
1294 +
1365 1295 // We want this to keep a running list of all the
1366 1296 // processed update hashes.
1367 1297 $this->post['meta']['syndication_item_hash'] = array_merge(
1368 1298 $this->stored_hashes(),
@@ -1367,97 +1297,19 @@
1367 1297 $this->post['meta']['syndication_item_hash'] = array_merge(
1368 1298 $this->stored_hashes(),
1369 1299 array($this->update_hash())
1370 1300 );
1301 +
1371 1302 else :
1372 - FeedWordPress::diagnostic('feed_items:freshness', 'Item ['.$guid.'] "'.$this->entry->get_title().'" is a duplicate of an existing post.');
1303 + FeedWordPress::diagnostic('feed_items:freshness', 'Item ['.$this->guid().'] "'.$this->entry->get_title().'" is a duplicate of an existing post.');
1373 1304 $this->_freshness = 0; // Same old, same old
1374 - $this->_wp_id = $old_post->ID;
1305 + $this->_wp_id = $old_post->id;
1375 1306 endif;
1376 1307 endif;
1377 1308 endif;
1378 -
1379 - switch ($format) :
1380 - case 'status' :
1381 - switch ($this->_freshness) :
1382 - case -1:
1383 - $ret = 'stored';
1384 - break;
1385 - case 0:
1386 - $ret = NULL;
1387 - break;
1388 - case 1:
1389 - $ret = 'updated';
1390 - break;
1391 - case 2:
1392 - default:
1393 - $ret = 'new';
1394 - break;
1395 - endswitch;
1396 - break;
1397 - case 'number' :
1398 - default :
1399 - $ret = $this->_freshness;
1400 - endswitch;
1401 -
1402 -
1403 - return $ret;
1404 - } /* SyndicatedPost::freshness () */
1405 -
1406 - function has_fresh_content () {
1407 - return ( ! $this->filtered() and $this->freshness() != 0 );
1408 - } /* SyndicatedPost::has_fresh_content () */
1409 -
1410 - function this_revision_needs_original_post ($freshness = NULL) {
1411 - if (is_null($freshness)) :
1412 - $freshness = $this->freshness();
1413 - endif;
1414 - return ( $freshness >= 2 );
1309 + return $this->_freshness;
1415 1310 }
1416 1311
1417 - function this_revision_is_current ($freshness = NULL) {
1418 - if (is_null($freshness)) :
1419 - $freshness = $this->freshness();
1420 - endif;
1421 - return ( $freshness >= 1 );
1422 - } /* SyndicatedPost::this_revision_is_current () */
1423 -
1424 - function fresh_content_is_update () {
1425 - return ($this->freshness() < 2);
1426 - } /* SyndicatedPost::fresh_content_is_update () */
1427 -
1428 - function fresh_storage_diagnostic () {
1429 - $ret = NULL;
1430 - switch ($this->freshness()) :
1431 - case -1 :
1432 - $ret = 'Storing alternate revision of existing post # '.$this->wp_id().', "'.$this->post['post_title'].'"';
1433 - break;
1434 - case 1 :
1435 - $ret = 'Updating existing post # '.$this->wp_id().', "'.$this->post['post_title'].'"';
1436 - break;
1437 - case 2 :
1438 - default :
1439 - $ret = 'Inserting new post "'.$this->post['post_title'].'"';
1440 - break;
1441 - endswitch;
1442 - return $ret;
1443 - } /* SyndicatedPost::fresh_storage_diagnostic() */
1444 -
1445 - function fresh_storage_hook () {
1446 - $ret = NULL;
1447 - switch ($this->freshness()) :
1448 - case -1 :
1449 - case 1 :
1450 - $ret = 'update_syndicated_item';
1451 - break;
1452 - case 2 :
1453 - default :
1454 - $ret = 'post_syndicated_item';
1455 - break;
1456 - endswitch;
1457 - return $ret;
1458 - } /* SyndicatedPost::fresh_storage_hook () */
1459 -
1460 1312 #################################################
1461 1313 #### INTERNAL STORAGE AND MANAGEMENT METHODS ####
1462 1314 #################################################
1463 1315
@@ -1462,11 +1314,11 @@
1462 1314 #################################################
1463 1315
1464 1316 function wp_id () {
1465 1317 if ($this->filtered()) : // This should never happen.
1466 - FeedWordPressDiagnostic::critical_bug('SyndicatedPost', $this, __LINE__, __FILE__);
1318 + FeedWordPress::critical_bug('SyndicatedPost', $this, __LINE__, __FILE__);
1467 1319 endif;
1468 -
1320 +
1469 1321 if (is_null($this->_wp_id) and is_null($this->_freshness)) :
1470 1322 $fresh = $this->freshness(); // sets WP DB id in the process
1471 1323 endif;
1472 1324 return $this->_wp_id;
@@ -1471,183 +1323,114 @@
1471 1323 endif;
1472 1324 return $this->_wp_id;
1473 1325 }
1474 1326
1475 - /**
1476 - * SyndicatedPost::secure_author_id(). Look up, or create, a numeric ID
1477 - * for the author of the incoming post.
1478 - *
1479 - * side effect: int|NULL stored in $this->post['post_author']
1480 - * side effect: IF no valid author is found, NULL stored in $this->post
1481 - * side effect: diagnostic output in case item is rejected with NULL author
1482 - *
1483 - * @used-by SyndicatedPost::store
1484 - *
1485 - * @uses SyndicatedPost::post
1486 - * @uses SyndicatedPost::author_id
1487 - * @uses SyndicatedLink::setting
1488 - * @uses FeedWordPress::diagnostic
1489 - */
1490 - protected function secure_author_id () {
1491 - # -- Look up, or create, numeric ID for author
1492 - $this->post['post_author'] = $this->author_id (
1493 - $this->link->setting('unfamiliar author', 'unfamiliar_author', 'create')
1494 - );
1327 + function store () {
1328 + global $wpdb;
1495 1329
1496 - if (is_null($this->post['post_author'])) :
1497 - FeedWordPress::diagnostic('feed_items:rejected', 'Filtered out item ['.$this->guid().'] without syndication: no author available');
1498 - $this->post = NULL;
1330 + if ($this->filtered()) : // This should never happen.
1331 + FeedWordPress::critical_bug('SyndicatedPost', $this, __LINE__, __FILE__);
1499 1332 endif;
1500 - } /* SyndicatedPost::secure_author_id() */
1333 +
1334 + $freshness = $this->freshness();
1335 + if ($freshness > 0) :
1336 + # -- Look up, or create, numeric ID for author
1337 + $this->post['post_author'] = $this->author_id (
1338 + $this->link->setting('unfamiliar author', 'unfamiliar_author', 'create')
1339 + );
1501 1340
1502 - /**
1503 - * SyndicatedPost::secure_term_ids(). Look up, or create, numeric IDs
1504 - * for the terms (categories, tags, etc.) assigned to the incoming post,
1505 - * whether by global settings, feed settings, or by the tags on the feed.
1506 - *
1507 - * side effect: array of term ids stored in $this->post['tax_input']
1508 - * side effect: IF settings or filters determine post should be filtered out,
1509 - * NULL stored in $this->post
1510 - *
1511 - * @used-by SyndicatedPost::store
1512 - *
1513 - * @uses apply_filters
1514 - * @uses SyndicatedLink::setting
1515 - * @uses SyndicatedPost::category_ids
1516 - * @uses SyndicatedPost::preset_terms
1517 - * @uses SyndicatedPost::post
1518 - */
1519 - protected function secure_term_ids () {
1520 - $mapping = apply_filters('syndicated_post_terms_mapping', array(
1521 - 'category' => array('abbr' => 'cats', 'unfamiliar' => 'category', 'domain' => array('category', 'post_tag')),
1522 - 'post_tag' => array('abbr' => 'tags', 'unfamiliar' => 'post_tag', 'domain' => array('post_tag')),
1523 - ), $this);
1524 -
1525 - $termSet = array(); $valid = null;
1526 - foreach ($this->feed_terms as $what => $anTerms) :
1527 - // Default to using the inclusive procedures (for cats) rather than exclusive (for inline tags)
1528 - $taxes = (isset($mapping[$what]) ? $mapping[$what] : $mapping['category']);
1529 - $unfamiliar = $taxes['unfamiliar'];
1530 -
1531 - if ( !is_null($this->post)) : // Not filtered out yet
1532 - # -- Look up, or create, numeric ID for categories
1533 - $taxonomies = $this->link->setting("match/".$taxes['abbr'], 'match_'.$taxes['abbr'], $taxes['domain']);
1534 -
1535 - // Eliminate dummy variables
1536 - $taxonomies = array_filter( $taxonomies, 'remove_dummy_zero' );
1537 -
1538 - // Allow FWP add-on filters to control the taxonomies we use to search for a term
1539 - $taxonomies = apply_filters("syndicated_post_terms_match", $taxonomies, $what, $this);
1540 - $taxonomies = apply_filters("syndicated_post_terms_match_{$what}", $taxonomies, $this);
1541 -
1542 - // Allow FWP add-on filters to control with greater precision what happens on unmatched
1543 - $unmatched = apply_filters("syndicated_post_terms_unfamiliar",
1544 - $this->link->setting(
1545 - "unfamiliar {$unfamiliar}",
1546 - "unfamiliar_{$unfamiliar}",
1547 - 'create:'.$unfamiliar
1548 - ),
1549 - $what,
1550 - $this
1551 - );
1552 -
1553 - $terms = $this->category_ids (
1554 - $anTerms,
1555 - $unmatched,
1556 - /*taxonomies=*/ $taxonomies,
1557 - array(
1558 - 'singleton' => false, // I don't like surprises
1559 - 'filters' => true,
1560 - )
1561 - );
1562 -
1563 - if (is_null($terms) or is_null($termSet)) :
1564 - // filtered out -- no matches
1565 - else :
1566 - $valid = true;
1567 -
1568 - // filter mode off, or at least one match
1569 - foreach ($terms as $tax => $term_ids) :
1570 - if ( !isset($termSet[$tax])) :
1571 - $termSet[$tax] = array();
1572 - endif;
1573 - $termSet[$tax] = array_merge($termSet[$tax], $term_ids);
1574 - endforeach;
1575 - endif;
1341 + if (is_null($this->post['post_author'])) :
1342 + FeedWordPress::diagnostic('feed_items:rejected', 'Filtered out item ['.$this->guid().'] without syndication: no author available');
1343 + $this->post = NULL;
1576 1344 endif;
1577 - endforeach;
1345 + endif;
1346 +
1347 + if (!$this->filtered() and $freshness > 0) :
1348 + $consider = array(
1349 + 'category' => array('abbr' => 'cats', 'domain' => array('category', 'post_tag')),
1350 + 'post_tag' => array('abbr' => 'tags', 'domain' => array('post_tag')),
1351 + );
1578 1352
1579 - if (is_null($valid)) : // Plonked
1580 - $this->post = NULL;
1581 - else : // We can proceed
1582 - $this->post['tax_input'] = array();
1583 - foreach ($termSet as $tax => $term_ids) :
1584 - if ( !isset($this->post['tax_input'][$tax])) :
1585 - $this->post['tax_input'][$tax] = array();
1586 - endif;
1587 - $this->post['tax_input'][$tax] = array_merge(
1588 - $this->post['tax_input'][$tax],
1589 - $term_ids
1590 - );
1591 - endforeach;
1353 + $termSet = array(); $valid = null;
1354 + foreach ($consider as $what => $taxes) :
1355 + if (!is_null($this->post)) : // Not filtered out yet
1356 + # -- Look up, or create, numeric ID for categories
1357 + $taxonomies = $this->link->setting("match/".$taxes['abbr'], 'match_'.$taxes['abbr'], $taxes['domain']);
1358 +
1359 + // Eliminate dummy variables
1360 + $taxonomies = array_filter($taxonomies, 'remove_dummy_zero');
1361 +
1362 + $terms = $this->category_ids (
1363 + $this->feed_terms[$what],
1364 + $this->link->setting("unfamiliar {$what}", "unfamiliar_{$what}", 'create:'.$what),
1365 + /*taxonomies=*/ $taxonomies,
1366 + array(
1367 + 'singleton' => false, // I don't like surprises
1368 + 'filters' => true,
1369 + )
1370 + );
1371 +
1372 + if (is_null($terms) or is_null($termSet)) :
1373 + // filtered out -- no matches
1374 + else :
1375 + $valid = true;
1592 1376
1593 - // Now let's add on the feed and global presets
1594 - foreach ($this->preset_terms as $tax => $term_ids) :
1595 - if ( !isset($this->post['tax_input'][$tax])) :
1596 - $this->post['tax_input'][$tax] = array();
1377 + // filter mode off, or at least one match
1378 + foreach ($terms as $tax => $term_ids) :
1379 + if (!isset($termSet[$tax])) :
1380 + $termSet[$tax] = array();
1381 + endif;
1382 + $termSet[$tax] = array_merge($termSet[$tax], $term_ids);
1383 + endforeach;
1384 + endif;
1597 1385 endif;
1598 -
1599 - $this->post['tax_input'][$tax] = array_merge (
1600 - $this->post['tax_input'][$tax],
1601 - $this->category_ids (
1602 - /*terms=*/ $term_ids,
1603 - /*unfamiliar=*/ 'create:'.$tax, // These are presets; for those added in a tagbox editor, the tag may not yet exist
1604 - /*taxonomies=*/ array($tax),
1605 - array(
1606 - 'singleton' => true,
1607 - ))
1608 - );
1609 1386 endforeach;
1610 - endif;
1611 - } /* SyndicatedPost::secure_term_ids() */
1612 1387
1613 - /**
1614 - * SyndicatedPost::store
1615 - *
1616 - * @uses SyndicatedPost::secure_author_id
1617 - */
1618 - public function store () {
1619 - if ($this->filtered()) : // This should never happen.
1620 - FeedWordPressDiagnostic::critical_bug('SyndicatedPost', $this, __LINE__, __FILE__);
1621 - endif;
1388 + if (is_null($valid)) : // Plonked
1389 + $this->post = NULL;
1390 + else : // We can proceed
1391 + $this->post['tax_input'] = array();
1392 + foreach ($termSet as $tax => $term_ids) :
1393 + if (!isset($this->post['tax_input'][$tax])) :
1394 + $this->post['tax_input'][$tax] = array();
1395 + endif;
1396 + $this->post['tax_input'][$tax] = array_merge(
1397 + $this->post['tax_input'][$tax],
1398 + $term_ids
1399 + );
1400 + endforeach;
1622 1401
1623 - $freshness = $this->freshness(); // see above: this sets WP DB id in the process (gwyneth 20230919)
1624 - if ($this->has_fresh_content()) :
1625 - $this->secure_author_id();
1402 + // Now let's add on the feed and global presets
1403 + foreach ($this->preset_terms as $tax => $term_ids) :
1404 + if (!isset($this->post['tax_input'][$tax])) :
1405 + $this->post['tax_input'][$tax] = array();
1406 + endif;
1407 +
1408 + $this->post['tax_input'][$tax] = array_merge (
1409 + $this->post['tax_input'][$tax],
1410 + $this->category_ids (
1411 + /*terms=*/ $term_ids,
1412 + /*unfamiliar=*/ 'create:'.$tax, // These are presets; for those added in a tagbox editor, the tag may not yet exist
1413 + /*taxonomies=*/ array($tax),
1414 + array(
1415 + 'singleton' => true,
1416 + ))
1417 + );
1418 + endforeach;
1419 + endif;
1626 1420 endif;
1627 -
1628 - if ($this->has_fresh_content()) : // Was this filtered during author_id lookup?
1629 - $this->secure_term_ids();
1630 - endif;
1631 -
1632 - // We have to check again in case the post has been filtered
1633 - // during the category/tags/taxonomy terms lookup
1634 - if ($this->has_fresh_content()) :
1421 +
1422 + if (!$this->filtered() and $freshness > 0) :
1635 1423 // Filter some individual fields
1636 -
1637 - // If there already is a post slug (from syndication or by manual
1638 - // editing) don't cause WP to overwrite it by sending in a NULL
1639 - // post_name. Props Chris Fritz 2012-11-28.
1640 - $post_name = (is_null($this->_wp_post) ? NULL : $this->_wp_post->post_name);
1641 -
1424 +
1642 1425 // Allow filters to set post slug. Props niska.
1643 - $post_name = apply_filters('syndicated_post_slug', $post_name, $this);
1644 - if ( !empty($post_name)) :
1426 + $post_name = apply_filters('syndicated_post_slug', NULL, $this);
1427 + if (!empty($post_name)) :
1645 1428 $this->post['post_name'] = $post_name;
1646 1429 endif;
1647 -
1430 +
1648 1431 $this->post = apply_filters('syndicated_post', $this->post, $this);
1649 -
1432 +
1650 1433 // Allow for feed-specific syndicated_post filters.
1651 1434 $this->post = apply_filters(
1652 1435 "syndicated_post_".$this->link->uri(),
1653 1436 $this->post,
@@ -1653,56 +1436,39 @@
1653 1436 $this->post,
1654 1437 $this
1655 1438 );
1656 1439 endif;
1657 -
1440 +
1658 1441 // Hook in early to make sure these get inserted if at all possible
1659 1442 add_action(
1660 1443 /*hook=*/ 'transition_post_status',
1661 - /*callback=*/ array($this, 'add_rss_meta'),
1444 + /*callback=*/ array(&$this, 'add_rss_meta'),
1662 1445 /*priority=*/ -10000, /* very early */
1663 1446 /*arguments=*/ 3
1664 1447 );
1665 1448
1449 + $retval = array(1 => 'updated', 2 => 'new');
1450 +
1666 1451 $ret = false;
1667 - if ($this->has_fresh_content()) :
1668 - $diag = $this->fresh_storage_diagnostic();
1669 - if ( !is_null($diag)) :
1670 - FeedWordPress::diagnostic('syndicated_posts', $diag);
1671 - endif;
1452 + if (!$this->filtered() and isset($retval[$freshness])) :
1453 + $diag = array(
1454 + 1 => 'Updating existing post # '.$this->wp_id().', "'.$this->post['post_title'].'"',
1455 + 2 => 'Inserting new post "'.$this->post['post_title'].'"',
1456 + );
1457 + FeedWordPress::diagnostic('syndicated_posts', $diag[$freshness]);
1672 1458
1673 - $this->insert_post(/*update=*/ $this->fresh_content_is_update(), $this->freshness());
1459 + $this->insert_post(/*update=*/ ($freshness == 1));
1460 +
1461 + $hook = array( 1 => 'update_syndicated_item', 2 => 'post_syndicated_item' );
1462 + do_action($hook[$freshness], $this->wp_id(), $this);
1674 1463
1675 - $hook = $this->fresh_storage_hook();
1676 - if ( !is_null($hook)) :
1677 - do_action($hook, $this->wp_id(), $this);
1678 - endif;
1679 -
1680 - $ret = $this->freshness('status');
1464 + $ret = $retval[$freshness];
1681 1465 endif;
1682 1466
1683 - // If this is a legit, non-filtered post, tag it as found on the
1684 - // feed regardless of fresh or stale status
1685 - if ( ! $this->filtered()) :
1686 - $key = '_feedwordpress_retire_me_' . $this->link->id;
1687 - delete_post_meta($this->wp_id(), $key);
1688 -
1689 - $status = get_post_field('post_status', $this->wp_id());
1690 - if ('fwpretired'==$status and $this->link->is_non_incremental()) :
1691 - FeedWordPress::diagnostic('syndicated_posts', "Un-retiring previously retired post # ".$this->wp_id()." due to re-appearance on non-incremental feed.");
1692 - set_post_field('post_status', $this->post['post_status'], $this->wp_id());
1693 - wp_transition_post_status($this->post['post_status'], $status, $this->post);
1694 - elseif ('fwpzapped'==$status) :
1695 - // Set this new revision up to be
1696 - // blanked on the next update.
1697 - add_post_meta($this->wp_id(), '_feedwordpress_zapped_blank_me', 2, /*single=*/ true);
1698 - endif;
1699 - endif;
1700 -
1701 1467 // Remove add_rss_meta hook
1702 1468 remove_action(
1703 1469 /*hook=*/ 'transition_post_status',
1704 - /*callback=*/ array($this, 'add_rss_meta'),
1470 + /*callback=*/ array(&$this, 'add_rss_meta'),
1705 1471 /*priority=*/ -10000, /* very early */
1706 1472 /*arguments=*/ 3
1707 1473 );
1708 1474
@@ -1707,20 +1473,19 @@
1707 1473 );
1708 1474
1709 1475 return $ret;
1710 1476 } /* function SyndicatedPost::store () */
1477 +
1478 + function insert_post ($update = false) {
1479 + global $wpdb;
1711 1480
1712 - function insert_post ($update = false, $freshness = 2) {
1713 1481 $dbpost = $this->normalize_post(/*new=*/ true);
1714 -
1715 - $ret = null;
1716 -
1717 - if ( !is_null($dbpost)) :
1482 + if (!is_null($dbpost)) :
1718 1483 $dbpost['post_pingback'] = false; // Tell WP 2.1 and 2.2 not to process for pingbacks
1719 -
1484 +
1720 1485 // This is a ridiculous fucking kludge necessitated by WordPress 2.6 munging authorship meta-data
1721 1486 add_action('_wp_put_post_revision', array($this, 'fix_revision_meta'));
1722 -
1487 +
1723 1488 // Kludge to prevent kses filters from stripping the
1724 1489 // content of posts when updating without a logged in
1725 1490 // user who has `unfiltered_html` capability.
1726 1491 $mungers = array('wp_filter_kses', 'wp_filter_post_kses');
@@ -1730,33 +1495,33 @@
1730 1495 remove_filter('content_save_pre', $munger);
1731 1496 $removed[] = $munger;
1732 1497 endif;
1733 1498 endforeach;
1734 -
1499 +
1735 1500 if ($update and function_exists('get_post_field')) :
1736 1501 // Don't munge status fields that the user may
1737 1502 // have reset manually
1738 1503 $doNotMunge = array('post_status', 'comment_status', 'ping_status');
1739 -
1504 +
1740 1505 foreach ($doNotMunge as $field) :
1741 1506 $dbpost[$field] = get_post_field($field, $this->wp_id());
1742 1507 endforeach;
1743 1508 endif;
1744 -
1509 +
1745 1510 // WP3's wp_insert_post scans current_user_can() for the
1746 1511 // tax_input, with no apparent way to override. Ugh.
1747 1512 add_action(
1748 1513 /*hook=*/ 'transition_post_status',
1749 - /*callback=*/ array($this, 'add_terms'),
1514 + /*callback=*/ array(&$this, 'add_terms'),
1750 1515 /*priority=*/ -10001, /* very early */
1751 1516 /*arguments=*/ 3
1752 1517 );
1753 -
1518 +
1754 1519 // WP3 appears to override whatever you give it for
1755 1520 // post_modified. Ugh.
1756 1521 add_action(
1757 1522 /*hook=*/ 'transition_post_status',
1758 - /*callback=*/ array($this, 'fix_post_modified_ts'),
1523 + /*callback=*/ array(&$this, 'fix_post_modified_ts'),
1759 1524 /*priority=*/ -10000, /* very early */
1760 1525 /*arguments=*/ 3
1761 1526 );
1762 1527
@@ -1763,57 +1528,13 @@
1763 1528 if ($update) :
1764 1529 $this->post['ID'] = $this->wp_id();
1765 1530 $dbpost['ID'] = $this->post['ID'];
1766 1531 endif;
1532 + $this->_wp_id = wp_insert_post($dbpost, /*return wp_error=*/ true);
1767 1533
1768 - // O.K., is this a new post? If so, we need to create
1769 - // the basic post record before we do anything else.
1770 - if ($this->this_revision_needs_original_post()) :
1771 - // *sigh*, for handling inconsistent slash expectations < 3.6
1772 - $sdbpost = $this->db_sanitize_post($dbpost);
1773 -
1774 - // Go ahead and insert the first post record to
1775 - // anchor the revision history.
1776 -
1777 - $this->_wp_id = wp_insert_post($sdbpost, /*return wp_error=*/ true);
1778 -
1779 - $dbpost['ID'] = $this->_wp_id;
1780 - endif;
1781 -
1782 - // Sanity check: if the attempt to insert post
1783 - // returned an error, then feeding that error
1784 - // object in to _wp_put_post_revision() would
1785 - // cause a fatal error. Better to break out.
1786 - if ( !is_wp_error($this->_wp_id)) :
1787 - // Now that we've made sure the original exists, insert
1788 - // this version here as a revision.
1789 - $revision_id = _wp_put_post_revision($dbpost, /*autosave=*/ false);
1790 -
1791 - if ( ! $this->this_revision_needs_original_post()) :
1792 -
1793 - if ($this->this_revision_is_current()) :
1794 -
1795 - wp_restore_post_revision($revision_id);
1796 -
1797 - else :
1798 -
1799 - // If we do not activate this revision, then the
1800 - // add_rss_meta will not be called, which is
1801 - // more or less as it should be, but that means
1802 - // we have to actively record this revision's
1803 - // update hash from here.
1804 - $postId = $this->post['ID'];
1805 - $key = 'syndication_item_hash';
1806 - $hash = $this->update_hash();
1807 - FeedWordPress::diagnostic('syndicated_posts:meta_data', "Adding post meta-datum to post [$postId]: [$key] = ".FeedWordPress::val($hash, /*no newlines=*/ true));
1808 - add_post_meta( $postId, $key, $hash, /*unique=*/ false );
1809 - endif;
1810 - endif;
1811 - endif;
1812 -
1813 1534 remove_action(
1814 1535 /*hook=*/ 'transition_post_status',
1815 - /*callback=*/ array($this, 'add_terms'),
1536 + /*callback=*/ array(&$this, 'add_terms'),
1816 1537 /*priority=*/ -10001, /* very early */
1817 1538 /*arguments=*/ 3
1818 1539 );
1819 1540
@@ -1818,9 +1539,9 @@
1818 1539 );
1819 1540
1820 1541 remove_action(
1821 1542 /*hook=*/ 'transition_post_status',
1822 - /*callback=*/ array($this, 'fix_post_modified_ts'),
1543 + /*callback=*/ array(&$this, 'fix_post_modified_ts'),
1823 1544 /*priority=*/ -10000, /* very early */
1824 1545 /*arguments=*/ 3
1825 1546 );
1826 1547
@@ -1826,47 +1547,43 @@
1826 1547
1827 1548 // Turn off ridiculous fucking kludges #1 and #2
1828 1549 remove_action('_wp_put_post_revision', array($this, 'fix_revision_meta'));
1829 1550 foreach ($removed as $filter) :
1830 - add_filter('content_save_pre', $filter);
1551 + add_filter('content_save_pre', $removed);
1831 1552 endforeach;
1832 -
1553 +
1833 1554 $this->validate_post_id($dbpost, $update, array(__CLASS__, __FUNCTION__));
1834 -
1835 - $ret = $this->_wp_id;
1836 1555 endif;
1837 - return $ret;
1838 1556 } /* function SyndicatedPost::insert_post () */
1839 -
1840 - /**
1841 - * SyndicatedPost::insert_new(). Uses the data collected in this post object to insert
1842 - * a new post into the wp_posts table.
1843 - *
1844 - * @uses SyndicatedPost::insert_post
1845 - */
1557 +
1846 1558 function insert_new () {
1847 - $this->insert_post(/*update=*/ false, 1);
1559 + $this->insert_post(/*update=*/ false);
1848 1560 } /* SyndicatedPost::insert_new() */
1849 1561
1850 - /**
1851 - * SyndicatedPost::insert_new(). Uses the data collected in this post object to update
1852 - * an existing post in the wp_posts table.
1853 - *
1854 - * @uses SyndicatedPost::insert_post
1855 - */
1856 1562 function update_existing () {
1857 - $this->insert_post(/*update=*/ true, 2);
1563 + $this->insert_post(/*update=*/ true);
1858 1564 } /* SyndicatedPost::update_existing() */
1859 1565
1860 1566 /**
1861 1567 * SyndicatedPost::normalize_post()
1862 1568 *
1863 - * @param bool $new If true, this post is to be inserted anew. If false, it is an update of an existing post. (Unused)
1569 + * @param bool $new If true, this post is to be inserted anew. If false, it is an update of an existing post.
1864 1570 * @return array A normalized representation of the post ready to be inserted into the database or sent to the WordPress API functions
1865 1571 */
1866 - function normalize_post( $new = true ) {
1867 - $out = $this->post;
1572 + function normalize_post ($new = true) {
1573 + global $wpdb;
1868 1574
1575 + $out = array();
1576 +
1577 + // Why the fuck doesn't wp_insert_post already do this?
1578 + foreach ($this->post as $key => $value) :
1579 + if (is_string($value)) :
1580 + $out[$key] = $wpdb->escape($value);
1581 + else :
1582 + $out[$key] = $value;
1583 + endif;
1584 + endforeach;
1585 +
1869 1586 $fullPost = $out['post_title'].$out['post_content'];
1870 1587 $fullPost .= (isset($out['post_excerpt']) ? $out['post_excerpt'] : '');
1871 1588 if (strlen($fullPost) < 1) :
1872 1589 // FIXME: Option for filtering out empty posts
@@ -1878,9 +1595,9 @@
1878 1595 else :
1879 1596 $feed_url = parse_url($this->post['meta']['syndication_feed']);
1880 1597 $source_title = $feed_url['host'];
1881 1598 endif;
1882 -
1599 +
1883 1600 $out['post_title'] = $source_title
1884 1601 .' '.gmdate('Y-m-d H:i:s', $this->published() + $offset);
1885 1602 // FIXME: Option for what to fill a blank title with...
1886 1603 endif;
@@ -1886,81 +1603,11 @@
1886 1603 endif;
1887 1604
1888 1605 // Normalize the guid if necessary.
1889 1606 $out['guid'] = SyndicatedPost::normalize_guid($out['guid']);
1890 -
1891 1607 return $out;
1892 1608 }
1893 1609
1894 - public function db_sanitize_post_check_encoding ($out) {
1895 - // Check encoding recursively: every string field needs to be checked
1896 - // for character encoding issues. This is a bit problematic because we
1897 - // *should* be using DB_CHARSET, but DB_CHARSET sometimes has values
1898 - // that work for MySQL but not for PHP mb_check_encoding. So instead
1899 - // we must rely on WordPress setting blog_charset and hope that the user
1900 - // has got their database encoding set up to roughly match
1901 - $charset = get_option('blog_charset', 'utf8');
1902 -
1903 - foreach ($out as $key => $value) :
1904 - if (is_string($value)) :
1905 -
1906 - if ( !function_exists('mb_check_encoding') or mb_check_encoding($value, $charset)) :
1907 - $out[$key] = $value;
1908 - else :
1909 - $fromCharset = mb_detect_encoding($value, mb_detect_order(), /*strict=*/ true);
1910 - $out[$key] = mb_convert_encoding($value, $charset, $fromCharset);
1911 - endif;
1912 -
1913 - elseif (is_array($value)) :
1914 - $out[$key] = $this->db_sanitize_post_check_encoding($value);
1915 -
1916 - else :
1917 - $out[$key] = $value;
1918 - endif;
1919 -
1920 - endforeach;
1921 -
1922 - return $out;
1923 - } /* SyndicatedPost::db_sanitize_post_check_encoding () */
1924 -
1925 - function db_sanitize_post ($out) {
1926 - global $wp_db_version;
1927 -
1928 - $out = $this->db_sanitize_post_check_encoding($out);
1929 -
1930 - // < 3.6. Core API, including `wp_insert_post()`, expects
1931 - // properly slashed data. If `wp_slash()` exists, then
1932 - // this is after the big change-over in how data slashing
1933 - // was handled.
1934 - if ( !function_exists('wp_slash')) :
1935 -
1936 - foreach ($out as $key => $value) :
1937 - if (is_string($value)) :
1938 - $out[$key] = esc_sql($value);
1939 - else :
1940 - $out[$key] = $value;
1941 - endif;
1942 - endforeach;
1943 -
1944 - // For revisions [@23416,@23554), core API expects
1945 - // unslashed data. Cf. <https://core.trac.wordpress.org/browser/trunk/wp-includes/post.php?rev=23416>
1946 - // NOOP for those revisions.
1947 -
1948 - // In revisions @23554 to present, `wp_insert_post()`
1949 - // expects slashed data once again.
1950 - // Cf. <https://core.trac.wordpress.org/changeset/23554/trunk/wp-includes/post.php?contextall=1>
1951 - // But at least now we can use the wp_slash API function to do that.
1952 - // Hooray.
1953 -
1954 - elseif ($wp_db_version >= 23524) :
1955 -
1956 - $out = wp_slash($out);
1957 -
1958 - endif;
1959 -
1960 - return $out;
1961 - }
1962 -
1963 1610 /**
1964 1611 * SyndicatedPost::validate_post_id()
1965 1612 *
1966 1613 * @param array $dbpost An array representing the post we attempted to insert or update
@@ -1970,9 +1617,9 @@
1970 1617 if (is_array($ns)) : $ns = implode('::', $ns);
1971 1618 else : $ns = (string) $ns; endif;
1972 1619
1973 1620 // This should never happen.
1974 - if ( !is_numeric($this->_wp_id) or ($this->_wp_id == 0)) :
1621 + if (!is_numeric($this->_wp_id) or ($this->_wp_id == 0)) :
1975 1622 $verb = ($is_update ? 'update existing' : 'insert new');
1976 1623 $guid = $this->guid();
1977 1624 $url = $this->permalink();
1978 1625 $feed = $this->link->uri(array('add_params' => true));
@@ -1980,11 +1627,10 @@
1980 1627 // wp_insert_post failed. Diagnostics, or barf up a critical bug
1981 1628 // notice if we are in debug mode.
1982 1629 $mesg = "Failed to $verb item [$guid]. WordPress API returned no valid post ID.\n"
1983 1630 ."\t\tID = ".serialize($this->_wp_id)."\n"
1984 - ."\t\tURL = ".MyPHP::val($url)
1985 - ."\t\tFeed = ".MyPHP::val($feed);
1986 -
1631 + ."\t\tURL = ".FeedWordPress::val($url)
1632 + ."\t\tFeed = ".FeedWordPress::val($feed);
1987 1633 FeedWordPress::diagnostic('updated_feeds:errors', "WordPress API error: $mesg");
1988 1634 FeedWordPress::diagnostic('feed_items:rejected', $mesg);
1989 1635
1990 1636 $mesg = <<<EOM
@@ -1990,13 +1636,13 @@
1990 1636 $mesg = <<<EOM
1991 1637 The WordPress API returned an invalid post ID
1992 1638 when FeedWordPress tried to $verb item $guid
1993 1639 [URL: $url]
1994 - from the feed at $feed
1640 + from the feed at $feed
1995 1641
1996 -$ns::_wp_id
1642 +$ns::_wp_id
1997 1643 EOM;
1998 - FeedWordPressDiagnostic::noncritical_bug(
1644 + FeedWordPress::noncritical_bug(
1999 1645 /*message=*/ $mesg,
2000 1646 /*var =*/ array(
2001 1647 "\$this->_wp_id" => $this->_wp_id,
2002 1648 "\$dbpost" => $dbpost,
@@ -2004,18 +1650,18 @@
2004 1650 /*line # =*/ __LINE__, /*filename=*/ __FILE__
2005 1651 );
2006 1652 endif;
2007 1653 } /* SyndicatedPost::validate_post_id() */
2008 -
1654 +
2009 1655 /**
2010 - * SyndicatedPost::fix_revision_meta() - Ensures that we get the meta
2011 - * data (authorship, guid, etc.) that we want when storing revisions of
2012 - * a syndicated post.
1656 + * SyndicatedPost::fix_revision_meta() - Fixes the way WP 2.6+ fucks up
1657 + * meta-data (authorship, etc.) when storing revisions of an updated
1658 + * syndicated post.
2013 1659 *
2014 - * In their infinite wisdom, the WordPress coders seem to have made it
2015 - * completely impossible for a plugin that uses wp_insert_post() to set
2016 - * certain meta-data (such as the author) when you store an old revision
2017 - * of an updated post. Instead, it uses the WordPress defaults (= cur.
1660 + * In their infinite wisdom, the WordPress coders have made it completely
1661 + * impossible for a plugin that uses wp_insert_post() to set certain
1662 + * meta-data (such as the author) when you store an old revision of an
1663 + * updated post. Instead, it uses the WordPress defaults (= currently
2018 1664 * active user ID if the process is running with a user logged in, or
2019 1665 * = #0 if there is no user logged in). This results in bogus authorship
2020 1666 * data for revisions that are syndicated from off the feed, unless we
2021 1667 * use a ridiculous kludge like this to end-run the munging of meta-data
@@ -2022,24 +1668,21 @@
2022 1668 * by _wp_put_post_revision.
2023 1669 *
2024 1670 * @param int $revision_id The revision ID to fix up meta-data
2025 1671 */
2026 - function fix_revision_meta( $revision_id ) {
2027 - $post_author = (int) $this->post['post_author']; // is this a global? And if it is, where is it defined? (gwyneth 20230919)
2028 -
1672 + function fix_revision_meta ($revision_id) {
1673 + global $wpdb;
1674 +
1675 + $post_author = (int) $this->post['post_author'];
1676 +
2029 1677 $revision_id = (int) $revision_id;
2030 -
2031 - // Let's fix the author.
2032 - set_post_field( 'post_author', $this->post['post_author'], $revision_id );
2033 -
2034 - // Let's fix the GUID to a dummy URL with the update hash.
2035 - set_post_field( 'guid', 'http://feedwordpress.radgeek.com/?rev=' . $this->update_hash(), $revision_id );
2036 -
2037 - // Let's fire an event for add-ons and filters
2038 - do_action( 'syndicated_post_fix_revision_meta', $revision_id, $this );
2039 -
1678 + $wpdb->query("
1679 + UPDATE $wpdb->posts
1680 + SET post_author={$this->post['post_author']}
1681 + WHERE post_type = 'revision' AND ID='$revision_id'
1682 + ");
2040 1683 } /* SyndicatedPost::fix_revision_meta () */
2041 -
1684 +
2042 1685 /**
2043 1686 * SyndicatedPost::add_terms() -- if FeedWordPress is processing an
2044 1687 * automatic update, that generally means that wp_insert_post() is being
2045 1688 * called under the user credentials of whoever is viewing the blog at
@@ -2056,9 +1699,8 @@
2056 1699 * @param string $old_status Unused action parameter.
2057 1700 * @param object $post The database record for the post just inserted.
2058 1701 */
2059 1702 function add_terms ($new_status, $old_status, $post) {
2060 -
2061 1703 if ($new_status!='inherit') : // Bail if we are creating a revision.
2062 1704 if ( is_array($this->post) and isset($this->post['tax_input']) and is_array($this->post['tax_input']) ) :
2063 1705 foreach ($this->post['tax_input'] as $taxonomy => $terms) :
2064 1706 if (is_array($terms)) :
@@ -2063,30 +1705,14 @@
2063 1705 foreach ($this->post['tax_input'] as $taxonomy => $terms) :
2064 1706 if (is_array($terms)) :
2065 1707 $terms = array_filter($terms); // strip out empties
2066 1708 endif;
2067 -
2068 - $res = wp_set_post_terms(
2069 - /*post_id=*/ $post->ID,
2070 - /*terms=*/ $terms,
2071 - /*taxonomy=*/ $taxonomy
2072 - );
2073 -
2074 - FeedWordPress::diagnostic(
2075 - 'syndicated_posts:categories',
2076 - 'Category: post('.json_encode($post->ID).') '.$taxonomy
2077 - .' := '
2078 - .json_encode($terms)
2079 - .' / result: '
2080 - .json_encode($res)
2081 - );
2082 -
1709 + wp_set_post_terms($post->ID, $terms, $taxonomy);
2083 1710 endforeach;
2084 1711 endif;
2085 1712 endif;
2086 -
2087 1713 } /* SyndicatedPost::add_terms () */
2088 -
1714 +
2089 1715 /**
2090 1716 * SyndicatedPost::fix_post_modified_ts() -- We would like to set
2091 1717 * post_modified and post_modified_gmt to reflect the value of
2092 1718 * <atom:updated> or equivalent elements on the feed. Unfortunately,
@@ -2109,9 +1735,9 @@
2109 1735 'post_modified_gmt' => $this->post['post_modified_gmt'],
2110 1736 ), /*where=*/ array('ID' => $post->ID) );
2111 1737 endif;
2112 1738 } /* SyndicatedPost::fix_post_modified_ts () */
2113 -
1739 +
2114 1740 /**
2115 1741 * SyndicatedPost::add_rss_meta: adds interesting meta-data to each entry
2116 1742 * using the space for custom keys. The set of keys and values to add is
2117 1743 * specified by the keys and values of $post['meta']. This is used to
@@ -2125,9 +1751,9 @@
2125 1751 * @param string $new_status Unused action parameter.
2126 1752 * @param string $old_status Unused action parameter.
2127 1753 * @param object $post The database record for the post just inserted.
2128 1754 */
2129 - function add_rss_meta($new_status, $old_status, $post) {
1755 + function add_rss_meta ($new_status, $old_status, $post) {
2130 1756 global $wpdb;
2131 1757 if ($new_status!='inherit') : // Bail if we are creating a revision.
2132 1758 FeedWordPress::diagnostic('syndicated_posts:meta_data', 'Adding post meta-data: {'.implode(", ", array_keys($this->post['meta'])).'}');
2133 1759
@@ -2132,9 +1758,9 @@
2132 1758 FeedWordPress::diagnostic('syndicated_posts:meta_data', 'Adding post meta-data: {'.implode(", ", array_keys($this->post['meta'])).'}');
2133 1759
2134 1760 if ( is_array($this->post) and isset($this->post['meta']) and is_array($this->post['meta']) ) :
2135 1761 $postId = $post->ID;
2136 -
1762 +
2137 1763 // Aggregated posts should NOT send out pingbacks.
2138 1764 // WordPress 2.1-2.2 claim you can tell them not to
2139 1765 // using $post_pingback, but they don't listen, so we
2140 1766 // make sure here.
@@ -2141,12 +1767,12 @@
2141 1767 $result = $wpdb->query("
2142 1768 DELETE FROM $wpdb->postmeta
2143 1769 WHERE post_id='$postId' AND meta_key='_pingme'
2144 1770 ");
2145 -
1771 +
2146 1772 foreach ( $this->post['meta'] as $key => $values ) :
2147 - $eKey = esc_sql($key);
2148 -
1773 + $eKey = $wpdb->escape($key);
1774 +
2149 1775 // If this is an update, clear out the old
2150 1776 // values to avoid duplication.
2151 1777 $result = $wpdb->query("
2152 1778 DELETE FROM $wpdb->postmeta
@@ -2151,21 +1777,16 @@
2151 1777 $result = $wpdb->query("
2152 1778 DELETE FROM $wpdb->postmeta
2153 1779 WHERE post_id='$postId' AND meta_key='$eKey'
2154 1780 ");
2155 -
1781 +
2156 1782 // Allow for either a single value or an array
2157 - if ( !is_array($values)) $values = array($values);
1783 + if (!is_array($values)) $values = array($values);
2158 1784 foreach ( $values as $value ) :
2159 - FeedWordPress::diagnostic('syndicated_posts:meta_data', "Adding post meta-datum to post [$postId]: [$key] = ".MyPHP::val($value, /*no newlines=*/ true));
1785 + FeedWordPress::diagnostic('syndicated_posts:meta_data', "Adding post meta-datum to post [$postId]: [$key] = ".FeedWordPress::val($value, /*no newlines=*/ true));
2160 1786 add_post_meta($postId, $key, $value, /*unique=*/ false);
2161 1787 endforeach;
2162 1788 endforeach;
2163 -
2164 - if ( $result === false)
2165 - {
2166 - error_log( "delete query failed: " . $wpdb->last_error );
2167 - }
2168 1789 endif;
2169 1790 endif;
2170 1791 } /* SyndicatedPost::add_rss_meta () */
2171 1792
@@ -2185,9 +1806,9 @@
2185 1806
2186 1807 $source = $this->source();
2187 1808 $forbidden = apply_filters('feedwordpress_forbidden_author_names',
2188 1809 array('admin', 'administrator', 'www', 'root'));
2189 -
1810 +
2190 1811 // Prepare the list of candidates to try for author name: name from
2191 1812 // feed, original source title (if any), immediate source title live
2192 1813 // from feed, subscription title, prettied version of feed homepage URL,
2193 1814 // prettied version of feed URL, or, failing all, use "unknown author"
@@ -2194,32 +1815,31 @@
2194 1815 // as last resort
2195 1816
2196 1817 $candidates = array();
2197 1818 $candidates[] = $a['name'];
2198 - if ( !is_null($source)) : $candidates[] = $source['title']; endif;
1819 + if (!is_null($source)) : $candidates[] = $source['title']; endif;
2199 1820 $candidates[] = $this->link->name(/*fromFeed=*/ true);
2200 1821 $candidates[] = $this->link->name(/*fromFeed=*/ false);
2201 1822 if (strlen($this->link->homepage()) > 0) : $candidates[] = feedwordpress_display_url($this->link->homepage()); endif;
2202 1823 $candidates[] = feedwordpress_display_url($this->link->uri());
2203 1824 $candidates[] = 'unknown author';
2204 -
1825 +
2205 1826 // Pick the first one that works from the list, screening against empty
2206 1827 // or forbidden names.
2207 -
1828 +
2208 1829 $author = NULL;
2209 - foreach ($candidates as $candidate) {
2210 - if ( !is_null($candidate)
2211 - and (strlen(trim($candidate)) > 0)
2212 - and !in_array(strtolower(trim($candidate)), $forbidden)) :
2213 - $author = $candidate;
2214 - break;
1830 + while (is_null($author) and ($candidate = each($candidates))) :
1831 + if (!is_null($candidate['value'])
1832 + and (strlen(trim($candidate['value'])) > 0)
1833 + and !in_array(strtolower(trim($candidate['value'])), $forbidden)) :
1834 + $author = $candidate['value'];
2215 1835 endif;
2216 - }
2217 -
1836 + endwhile;
1837 +
2218 1838 $email = (isset($a['email']) ? $a['email'] : NULL);
2219 1839 $authorUrl = (isset($a['uri']) ? $a['uri'] : NULL);
2220 1840
2221 -
1841 +
2222 1842 $hostUrl = $this->link->homepage();
2223 1843 if (is_null($hostUrl) or (strlen($hostUrl) < 0)) :
2224 1844 $hostUrl = $this->link->uri();
2225 1845 endif;
@@ -2244,9 +1864,9 @@
2244 1864 //
2245 1865 // Uniqueness will be guaranteed below if necessary.
2246 1866
2247 1867 $url = parse_url($hostUrl);
2248 -
1868 +
2249 1869 $login = sanitize_user($url['host'], /*strict=*/ true);
2250 1870 if (strlen($login) < 1) :
2251 1871 // This isn't working. Frak it.
2252 1872 $login = 'syndicated';
@@ -2257,13 +1877,13 @@
2257 1877
2258 1878 $nice_author = sanitize_title($author);
2259 1879 $nice_author = apply_filters('pre_user_nicename', $nice_author);
2260 1880
2261 - $reg_author = esc_sql(preg_quote($author ?: "(unknown)"));
2262 - $author = esc_sql($author);
2263 - $email = esc_sql($email);
2264 - $test_email = esc_sql($test_email);
2265 - $authorUrl = esc_sql($authorUrl);
1881 + $reg_author = $wpdb->escape(preg_quote($author));
1882 + $author = $wpdb->escape($author);
1883 + $email = $wpdb->escape($email);
1884 + $test_email = $wpdb->escape($test_email);
1885 + $authorUrl = $wpdb->escape($authorUrl);
2266 1886
2267 1887 // Check for an existing author rule....
2268 1888 if (isset($this->link->settings['map authors']['name']['*'])) :
2269 1889 $author_rule = $this->link->settings['map authors']['name']['*'];
@@ -2273,17 +1893,15 @@
2273 1893 $author_rule = NULL;
2274 1894 endif;
2275 1895
2276 1896 // User name is mapped to a particular author. If that author ID exists, use it.
2277 - // Note: get_userdata() is a pluggable function, so it might not be available yet;
2278 - // check if it exists before using it, or WP will throw a fatal error. (gwyneth 20220223)
2279 - if (is_numeric($author_rule) and function_exists('get_userdata') and get_userdata((int) $author_rule)) :
1897 + if (is_numeric($author_rule) and get_userdata((int) $author_rule)) :
2280 1898 $id = (int) $author_rule;
2281 1899
2282 1900 // User name is filtered out
2283 1901 elseif ('filter' == $author_rule) :
2284 1902 $id = NULL;
2285 -
1903 +
2286 1904 else :
2287 1905 // Check the database for an existing author record that might fit
2288 1906
2289 1907 // First try the user core data table.
@@ -2294,9 +1912,9 @@
2294 1912 OR (
2295 1913 LENGTH(TRIM(LCASE(user_email))) > 0
2296 1914 AND TRIM(LCASE(user_email)) = TRIM(LCASE('$test_email'))
2297 1915 )");
2298 -
1916 +
2299 1917 // If that fails, look for aliases in the user meta data table
2300 1918 if (is_null($id)) :
2301 1919 $id = $wpdb->get_var(
2302 1920 "SELECT user_id FROM $wpdb->usermeta
@@ -2318,11 +1936,11 @@
2318 1936 if (is_null($id)) :
2319 1937 if ($unfamiliar_author === 'create') :
2320 1938 $userdata = array();
2321 1939
2322 - #-- we need *something* for the email here or WordPress
2323 - #-- is liable to pitch a fit. So, make something up if
2324 - #-- necessary. (Ugh.)
1940 + // WordPress 3 is going to pitch a fit if we attempt to register
1941 + // more than one user account with an empty e-mail address, so we
1942 + // need *something* here. Ugh.
2325 1943 if (strlen($email) == 0 or FeedWordPress::is_null_email($email)) :
2326 1944 $url = parse_url($hostUrl);
2327 1945 $email = $nice_author.'@'.$url['host'];
2328 1946 endif;
@@ -2334,20 +1952,15 @@
2334 1952 $userdata['user_pass'] = substr(md5(uniqid(microtime())), 0, 6); // just something random to lock it up
2335 1953 $userdata['user_email'] = $email;
2336 1954 $userdata['user_url'] = $authorUrl;
2337 1955 $userdata['nickname'] = $author;
2338 -
2339 1956 $parts = preg_split('/\s+/', trim($author), 2);
2340 1957 if (isset($parts[0])) : $userdata['first_name'] = $parts[0]; endif;
2341 1958 if (isset($parts[1])) : $userdata['last_name'] = $parts[1]; endif;
2342 -
2343 1959 $userdata['display_name'] = $author;
2344 1960 $userdata['role'] = 'contributor';
2345 -
2346 - #-- loop. Keep trying to add the user until you get it
2347 - #-- right. Or until PHP crashes, I guess.
2348 - $insanity = 0;
2349 - do {
1961 +
1962 + do { // Keep trying until you get it right. Or until PHP crashes, I guess.
2350 1963 $id = wp_insert_user($userdata);
2351 1964 if (is_wp_error($id)) :
2352 1965 $codes = $id->get_error_code();
2353 1966 switch ($codes) :
@@ -2352,62 +1965,27 @@
2352 1965 $codes = $id->get_error_code();
2353 1966 switch ($codes) :
2354 1967 case 'empty_user_login' :
2355 1968 case 'existing_user_login' :
2356 - case 'invalid_username' :
2357 1969 // Add a random disambiguator
2358 1970 $userdata['user_login'] .= substr(md5(uniqid(microtime())), 0, 6);
2359 1971 break;
2360 - case 'user_login_too_long' :
2361 - // Limit length to 53 characters; if we end up needing a random disambiguator,
2362 - // we should still have space to add it.
2363 - $userdata['user_login'] = mb_substr( $userdata['user_login'], 0, 53 );
2364 - break;
2365 - case 'user_nicename_too_long' :
2366 - // Add a limited 50 characters user_nicename based on user_login
2367 - $userdata['user_nicename'] = mb_substr( $userdata['user_login'], 0, 50 );
2368 - break;
2369 1972 case 'existing_user_email' :
2370 - // Disassemble email for username, host
1973 + // No disassemble!
2371 1974 $parts = explode('@', $userdata['user_email'], 2);
2372 -
1975 +
2373 1976 // Add a random disambiguator as a gmail-style username extension
2374 1977 $parts[0] .= '+'.substr(md5(uniqid(microtime())), 0, 6);
2375 -
1978 +
2376 1979 // Reassemble
2377 1980 $userdata['user_email'] = $parts[0].'@'.$parts[1];
2378 1981 break;
2379 - default :
2380 - if ( $insanity > 10 ) :
2381 - // Try some settings that are unlikely to cause complaint...
2382 - $url = parse_url($hostUrl);
2383 -
2384 - $userdata['user_login'] = substr(md5(uniqid(microtime())), 0, 6);
2385 - $userdata['user_nicename'] = $userdata['user_login'];
2386 - $userdata['user_email'] = 'noreply@' . $url['host'];
2387 - elseif ( $insanity > 50 ) :
2388 - // Stop doing the same thing and expecting a different result
2389 - break;
2390 - endif;
2391 1982 endswitch;
2392 1983 endif;
2393 - $insanity = $insanity + 1;
2394 1984 } while (is_wp_error($id));
2395 -
2396 - // $id should now contain the numeric ID of a newly minted
2397 - // user account. Let's mark them as having been generated
2398 - // by FeedWordPress in the usermeta table, as per the
2399 - // suggestion of @boonebgorges, in case we need to process,
2400 - // winnow, filter, or merge syndicated author accounts, &c.
2401 - if ( !is_wp_error($id)) :
2402 - add_user_meta($id, 'feedwordpress_generated', 1);
2403 - else :
2404 - $id = null;
2405 - endif;
2406 - // also see comment above regarding get_userdata(). (gwyneth 20220223)
2407 - elseif ( is_numeric( $unfamiliar_author ) and function_exists( 'get_userdata ') and get_userdata((int) $unfamiliar_author ) ) :
1985 + elseif (is_numeric($unfamiliar_author) and get_userdata((int) $unfamiliar_author)) :
2408 1986 $id = (int) $unfamiliar_author;
2409 - elseif ( $unfamiliar_author === 'default' ) :
1987 + elseif ($unfamiliar_author === 'default') :
2410 1988 $id = 1;
2411 1989 endif;
2412 1990 endif;
2413 1991 endif;
@@ -2413,9 +1991,9 @@
2413 1991 endif;
2414 1992
2415 1993 if ($id) :
2416 1994 $this->link->settings['map authors']['name'][strtolower(trim($author))] = $id;
2417 -
1995 +
2418 1996 // Multisite: Check whether the author has been recorded
2419 1997 // on *this* blog before. If not, put her down as a
2420 1998 // Contributor for *this* blog.
2421 1999 $user = new WP_User((int) $id);
@@ -2422,21 +2000,144 @@
2422 2000 if (empty($user->roles)) :
2423 2001 $user->add_role('contributor');
2424 2002 endif;
2425 2003 endif;
2426 - return $id;
2004 + return $id;
2427 2005 } /* function SyndicatedPost::author_id () */
2428 2006
2429 2007 /**
2430 - * category_ids: look up (and create) category ids from a list of
2431 - * categories
2008 + * category_ids: look up (and create) category ids from a list of categories
2432 2009 *
2433 2010 * @param array $cats
2434 2011 * @param string $unfamiliar_category
2435 2012 * @param array|null $taxonomies
2436 2013 * @return array
2437 - */
2014 + */
2438 2015 function category_ids ($cats, $unfamiliar_category = 'create', $taxonomies = NULL, $params = array()) {
2439 - return $this->link->category_ids($this, $cats, $unfamiliar_category, $taxonomies, $params);
2440 - } /* SyndicatedPost::category_ids () */
2016 + $singleton = (isset($params['singleton']) ? $params['singleton'] : true);
2017 + $allowFilters = (isset($params['filters']) ? $params['filters'] : false);
2018 +
2019 + $catTax = 'category';
2441 2020
2021 + if (is_null($taxonomies)) :
2022 + $taxonomies = array('category');
2023 + endif;
2024 +
2025 + // We need to normalize whitespace because (1) trailing
2026 + // whitespace can cause PHP and MySQL not to see eye to eye on
2027 + // VARCHAR comparisons for some versions of MySQL (cf.
2028 + // <http://dev.mysql.com/doc/mysql/en/char.html>), and (2)
2029 + // because I doubt most people want to make a semantic
2030 + // distinction between 'Computers' and 'Computers '
2031 + $cats = array_map('trim', $cats);
2032 +
2033 + $terms = array();
2034 + foreach ($taxonomies as $tax) :
2035 + $terms[$tax] = array();
2036 + endforeach;
2037 +
2038 + foreach ($cats as $cat_name) :
2039 + if (preg_match('/^{([^#}]*)#([0-9]+)}$/', $cat_name, $backref)) :
2040 + $cat_id = (int) $backref[2];
2041 + $tax = $backref[1];
2042 + if (strlen($tax) < 1) :
2043 + $tax = $catTax;
2044 + endif;
2045 +
2046 + $term = term_exists($cat_id, $tax);
2047 + if (!is_wp_error($term) and !!$term) :
2048 + if (!isset($terms[$tax])) :
2049 + $terms[$tax] = array();
2050 + endif;
2051 + $terms[$tax][] = $cat_id;
2052 + endif;
2053 + elseif (strlen($cat_name) > 0) :
2054 + $familiar = false;
2055 + foreach ($taxonomies as $tax) :
2056 + if ($tax!='category' or strtolower($cat_name)!='uncategorized') :
2057 + $term = term_exists($cat_name, $tax);
2058 + if (!is_wp_error($term) and !!$term) :
2059 + $familiar = true;
2060 +
2061 + if (is_array($term)) :
2062 + $term_id = (int) $term['term_id'];
2063 + else :
2064 + $term_id = (int) $term;
2065 + endif;
2066 +
2067 + if (!isset($terms[$tax])) :
2068 + $terms[$tax] = array();
2069 + endif;
2070 + $terms[$tax][] = $term_id;
2071 + break; // We're done here.
2072 + endif;
2073 + endif;
2074 + endforeach;
2075 +
2076 + if (!$familiar) :
2077 + if ('tag'==$unfamiliar_category) :
2078 + $unfamiliar_category = 'create:post_tag';
2079 + endif;
2080 +
2081 + if (preg_match('/^create(:(.*))?$/i', $unfamiliar_category, $ref)) :
2082 + $tax = $catTax; // Default
2083 + if (isset($ref[2]) and strlen($ref[2]) > 2) :
2084 + $tax = $ref[2];
2085 + endif;
2086 + $term = wp_insert_term($cat_name, $tax);
2087 + if (is_wp_error($term)) :
2088 + FeedWordPress::noncritical_bug('term insertion problem', array('cat_name' => $cat_name, 'term' => $term, 'this' => $this), __LINE__, __FILE__);
2089 + else :
2090 + if (!isset($terms[$tax])) :
2091 + $terms[$tax] = array();
2092 + endif;
2093 + $terms[$tax][] = (int) $term['term_id'];
2094 + endif;
2095 + endif;
2096 + endif;
2097 + endif;
2098 + endforeach;
2099 +
2100 + $filtersOn = $allowFilters;
2101 + if ($allowFilters) :
2102 + $filters = array_filter(
2103 + $this->link->setting('match/filter', 'match_filter', array()),
2104 + 'remove_dummy_zero'
2105 + );
2106 + $filtersOn = ($filtersOn and is_array($filters) and (count($filters) > 0));
2107 + endif;
2108 +
2109 + // Check for filter conditions
2110 + foreach ($terms as $tax => $term_ids) :
2111 + if ($filtersOn
2112 + and (count($term_ids)==0)
2113 + and in_array($tax, $filters)) :
2114 + $terms = NULL; // Drop the post
2115 + break;
2116 + else :
2117 + $terms[$tax] = array_unique($term_ids);
2118 + endif;
2119 + endforeach;
2120 +
2121 + if ($singleton and count($terms)==1) : // If we only searched one, just return the term IDs
2122 + $terms = end($terms);
2123 + endif;
2124 + return $terms;
2125 + } // function SyndicatedPost::category_ids ()
2126 +
2127 + function use_api ($tag) {
2128 + global $wp_db_version;
2129 + switch ($tag) :
2130 + case 'wp_insert_post':
2131 + // Before 2.2, wp_insert_post does too much of the wrong stuff to use it
2132 + // In 1.5 it was such a resource hog it would make PHP segfault on big updates
2133 + $ret = (isset($wp_db_version) and $wp_db_version > FWP_SCHEMA_21);
2134 + break;
2135 + case 'post_status_pending':
2136 + $ret = (isset($wp_db_version) and $wp_db_version > FWP_SCHEMA_23);
2137 + break;
2138 + endswitch;
2139 + return $ret;
2140 + } // function SyndicatedPost::use_api ()
2141 +
2442 2142 } /* class SyndicatedPost */
2143 +