PluginProbe
FeedWordPress / 2014.0805
FeedWordPress v2014.0805
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 | feedwordpress.php +1623 -575 2010.05282014.0805 View file →
@@ -2,9 +2,9 @@
2 2 /*
3 3 Plugin Name: FeedWordPress
4 4 Plugin URI: http://feedwordpress.radgeek.com/
5 5 Description: simple and flexible Atom/RSS syndication for WordPress
6 -Version: 2010.0528
6 +Version: 2014.0805
7 7 Author: Charles Johnson
8 8 Author URI: http://radgeek.com/
9 9 License: GPL
10 10 */
@@ -10,33 +10,37 @@
10 10 */
11 11
12 12 /**
13 13 * @package FeedWordPress
14 - * @version 2010.0528
14 + * @version 2014.0805
15 15 */
16 16
17 17 # This uses code derived from:
18 18 # - wp-rss-aggregate.php by Kellan Elliot-McCrea <kellan@protest.net>
19 -# - HTTP Navigator 2 by Keyvan Minoukadeh <keyvan@k1m.com>
19 +# - SimplePie feed parser by Ryan Parman, Geoffrey Sneddon, Ryan McCue, et al.
20 +# - MagpieRSS feed parser by Kellan Elliot-McCrea <kellan@protest.net>
20 21 # - Ultra-Liberal Feed Finder by Mark Pilgrim <mark@diveintomark.org>
22 +# - WordPress Blog Tool and Publishing Platform <http://wordpress.org/>
21 23 # according to the terms of the GNU General Public License.
22 24 #
23 -# INSTALLATION: see readme.txt or <http://projects.radgeek.com/install>
25 +# INSTALLATION: see readme.txt or <http://feedwordpress.radgeek.com/install>
24 26 #
25 27 # USAGE: once FeedWordPress is installed, you manage just about everything from
26 -# the WordPress Dashboard, under the Syndication menu. To ensure that fresh
27 -# content is added as it becomes available, you can convince your contributors
28 -# to put your XML-RPC URI (if WordPress is installed at
29 -# <http://www.zyx.com/blog>, XML-RPC requests should be sent to
30 -# <http://www.zyx.com/blog/xmlrpc.php>), or update manually under the
31 -# Syndication menu, or set up automatic updates under Syndication --> Settings,
32 -# or use a cron job.
28 +# the WordPress Dashboard, under the Syndication menu. To keep fresh content
29 +# coming in as it becomes available, you'll have to either check for updates
30 +# manually, or set up one of the automatically-scheduled update methods. See
31 +# <http://feedwordpress.radgeek.com/wiki/quick-start/> for some details.
33 32
34 33 # -- Don't change these unless you know what you're doing...
35 34
36 -define ('FEEDWORDPRESS_VERSION', '2010.0528');
35 +define ('FEEDWORDPRESS_VERSION', '2014.0805');
37 36 define ('FEEDWORDPRESS_AUTHOR_CONTACT', 'http://radgeek.com/contact');
38 37
38 +if (!defined('FEEDWORDPRESS_BLEG')) :
39 + define ('FEEDWORDPRESS_BLEG', true);
40 +endif;
41 +define('FEEDWORDPRESS_BLEG_BTC', '1FN3Q4VSR4jV7unRjaknVQVe5ky88ktPHS');
42 +
39 43 // Defaults
40 44 define ('DEFAULT_SYNDICATION_CATEGORY', 'Contributors');
41 45 define ('DEFAULT_UPDATE_PERIOD', 60); // value in minutes
42 46
@@ -48,8 +52,10 @@
48 52 $feedwordpress_debug = ($feedwordpress_debug == 'yes');
49 53 endif;
50 54 endif;
51 55 define ('FEEDWORDPRESS_DEBUG', $feedwordpress_debug);
56 +$feedwordpress_compatibility = true;
57 +define ('FEEDWORDPRESS_COMPATIBILITY', $feedwordpress_compatibility);
52 58
53 59 define ('FEEDWORDPRESS_CAT_SEPARATOR_PATTERN', '/[:\n]/');
54 60 define ('FEEDWORDPRESS_CAT_SEPARATOR', "\n");
55 61
@@ -57,36 +63,30 @@
57 63
58 64 define ('FEEDWORDPRESS_FRESHNESS_INTERVAL', 10*60); // Every ten minutes
59 65
60 66 define ('FWP_SCHEMA_HAS_USERMETA', 2966);
61 -define ('FWP_SCHEMA_20', 3308); // Database schema # for WP 2.0
62 -define ('FWP_SCHEMA_21', 4772); // Database schema # for WP 2.1
63 -define ('FWP_SCHEMA_23', 5495); // Database schema # for WP 2.3
64 -define ('FWP_SCHEMA_25', 7558); // Database schema # for WP 2.5
65 -define ('FWP_SCHEMA_26', 8201); // Database schema # for WP 2.6
66 -define ('FWP_SCHEMA_27', 9872); // Database schema # for WP 2.7
67 -define ('FWP_SCHEMA_28', 11548); // Database schema # for WP 2.8
68 -define ('FWP_SCHEMA_29', 12329); // Database schema # for WP 2.9
67 +define ('FWP_SCHEMA_USES_ARGS_TAXONOMY', 12694); // Revision # for using $args['taxonomy'] to get link categories
68 +define ('FWP_SCHEMA_30', 12694); // Database schema # for WP 3.0
69 69
70 70 if (FEEDWORDPRESS_DEBUG) :
71 71 // Help us to pick out errors, if any.
72 72 ini_set('error_reporting', E_ALL & ~E_NOTICE);
73 73 ini_set('display_errors', true);
74 -
74 +
75 75 // When testing we don't want cache issues to interfere. But this is
76 - // a VERY BAD SETTING for a production server. Webmasters will eat your
76 + // a VERY BAD SETTING for a production server. Webmasters will eat your
77 77 // face for breakfast if you use it, and the baby Jesus will cry. So
78 78 // make sure FEEDWORDPRESS_DEBUG is FALSE for any site that will be
79 79 // used for more than testing purposes!
80 80 define('FEEDWORDPRESS_CACHE_AGE', 1);
81 81 define('FEEDWORDPRESS_CACHE_LIFETIME', 1);
82 - define('FEEDWORDPRESS_FETCH_TIME_OUT', 60);
82 + define('FEEDWORDPRESS_FETCH_TIMEOUT_DEFAULT', 60);
83 83 else :
84 84 // Hold onto data all day for conditional GET purposes,
85 85 // but consider it stale after 1 min (requiring a conditional GET)
86 86 define('FEEDWORDPRESS_CACHE_LIFETIME', 24*60*60);
87 87 define('FEEDWORDPRESS_CACHE_AGE', 1*60);
88 - define('FEEDWORDPRESS_FETCH_TIME_OUT', 10);
88 + define('FEEDWORDPRESS_FETCH_TIMEOUT_DEFAULT', 20);
89 89 endif;
90 90
91 91 // Use our the cache settings that we want.
92 92 add_filter('wp_feed_cache_transient_lifetime', array('FeedWordPress', 'cache_lifetime'));
@@ -92,33 +92,47 @@
92 92 add_filter('wp_feed_cache_transient_lifetime', array('FeedWordPress', 'cache_lifetime'));
93 93
94 94 // Ensure that we have SimplePie loaded up and ready to go.
95 95 // We no longer need a MagpieRSS upgrade module. Hallelujah!
96 -require_once(ABSPATH . WPINC . '/feed.php');
96 +if (!class_exists('SimplePie')) :
97 + require_once(ABSPATH . WPINC . '/class-simplepie.php');
98 +endif;
99 +require_once(ABSPATH . WPINC . '/class-feed.php');
97 100
98 -if (isset($wp_db_version)) :
99 - if ($wp_db_version >= FWP_SCHEMA_23) :
100 - require_once (ABSPATH . WPINC . '/registration.php'); // for wp_insert_user
101 - elseif ($wp_db_version >= FWP_SCHEMA_21) : // WordPress 2.1 and 2.2, but not 2.3
102 - require_once (ABSPATH . WPINC . '/registration.php'); // for wp_insert_user
103 - require_once (ABSPATH . 'wp-admin/admin-db.php'); // for wp_insert_category
104 - elseif ($wp_db_version >= FWP_SCHEMA_20) : // WordPress 2.0
105 - require_once (ABSPATH . WPINC . '/registration-functions.php'); // for wp_insert_user
106 - require_once (ABSPATH . 'wp-admin/admin-db.php'); // for wp_insert_category
107 - endif;
101 +if (!function_exists('wp_insert_user')) :
102 + require_once (ABSPATH . WPINC . '/registration.php'); // for wp_insert_user
108 103 endif;
109 104
110 -require_once(dirname(__FILE__) . '/compatability.php'); // LEGACY API: Replicate or mock up functions for legacy support purposes
111 -require_once(dirname(__FILE__) . '/feedwordpresshtml.class.php');
105 +$dir = dirname(__FILE__);
106 +require_once("${dir}/externals/myphp/myphp.class.php");
107 +require_once("${dir}/admin-ui.php");
108 +require_once("${dir}/feedwordpresssyndicationpage.class.php");
109 +require_once("${dir}/compatability.php"); // Legacy API
110 +require_once("${dir}/syndicatedpost.class.php");
111 +require_once("${dir}/syndicatedlink.class.php");
112 +require_once("${dir}/feedwordpresshtml.class.php");
113 +require_once("${dir}/feedwordpress-content-type-sniffer.class.php");
114 +require_once("${dir}/inspectpostmeta.class.php");
115 +require_once("${dir}/syndicationdataqueries.class.php");
116 +require_once("${dir}/feedwordpie.class.php");
117 +require_once("${dir}/feedwordpie_item.class.php");
118 +require_once("${dir}/feedwordpress_file.class.php");
119 +require_once("${dir}/feedwordpress_parser.class.php");
120 +require_once("${dir}/feedwordpressrpc.class.php");
121 +require_once("${dir}/feedwordpresshttpauthenticator.class.php");
122 +require_once("${dir}/feedwordpresslocalpost.class.php");
112 123
113 124 // Magic quotes are just about the stupidest thing ever.
114 125 if (is_array($_POST)) :
115 - $fwp_post = stripslashes_deep($_POST);
126 + $fwp_post = $_POST;
127 + if (get_magic_quotes_gpc()) :
128 + $fwp_post = stripslashes_deep($fwp_post);
129 + endif;
116 130 endif;
117 131
118 132 // Get the path relative to the plugins directory in which FWP is stored
119 133 preg_match (
120 - '|/wp-content/plugins/(.+)$|',
134 + '|'.preg_quote(WP_PLUGIN_DIR).'/(.+)$|',
121 135 dirname(__FILE__),
122 136 $ref
123 137 );
124 138
@@ -127,41 +141,11 @@
127 141 else : // Something went wrong. Let's just guess.
128 142 $fwp_path = 'feedwordpress';
129 143 endif;
130 144
131 -function feedwordpress_admin_scripts () {
132 - wp_enqueue_script('post'); // for magic tag and category boxes
133 - wp_enqueue_script('admin-forms'); // for checkbox selection
134 -}
145 +$feedwordpress = new FeedWordPress;
146 +if (!$feedwordpress->needs_upgrade()) : // only work if the conditions are safe!
135 147
136 -// If this is a FeedWordPress admin page, queue up scripts for AJAX functions that FWP uses
137 -// If it is a display page or a non-FeedWordPress admin page, don't.
138 -if (is_admin() and isset($_REQUEST['page']) and preg_match("|^{$fwp_path}/|", $_REQUEST['page'])) :
139 - if (function_exists('wp_enqueue_script')) :
140 - if (FeedWordPressCompatibility::test_version(FWP_SCHEMA_29)) :
141 - add_action('admin_print_scripts', 'feedwordpress_admin_scripts');
142 - elseif (FeedWordPressCompatibility::test_version(FWP_SCHEMA_25)) :
143 - wp_enqueue_script('post'); // for magic tag and category boxes
144 - wp_enqueue_script('thickbox'); // for fold-up boxes
145 - wp_enqueue_script('admin-forms'); // for checkbox selection
146 - else :
147 - wp_enqueue_script( 'ajaxcat' ); // Provides the handy-dandy new category text box
148 - endif;
149 - endif;
150 - if (function_exists('wp_enqueue_style')) :
151 - if (fwp_test_wp_version(FWP_SCHEMA_25)) :
152 - wp_enqueue_style('dashboard');
153 - endif;
154 - endif;
155 - if (function_exists('wp_admin_css')) :
156 - if (fwp_test_wp_version(FWP_SCHEMA_25)) :
157 - wp_admin_css('css/dashboard');
158 - endif;
159 - endif;
160 -endif;
161 -
162 -if (!FeedWordPress::needs_upgrade()) : // only work if the conditions are safe!
163 -
164 148 # Syndicated items are generally received in output-ready (X)HTML and
165 149 # should not be folded, crumpled, mutilated, or spindled by WordPress
166 150 # formatting filters. But we don't want to interfere with filters for
167 151 # any locally-authored posts, either.
@@ -175,19 +159,20 @@
175 159 # this is a syndicated post
176 160
177 161 add_filter('the_content', 'feedwordpress_preserve_syndicated_content', -10000);
178 162 add_filter('the_content', 'feedwordpress_restore_syndicated_content', 10000);
179 -
163 +
180 164 add_action('atom_entry', 'feedwordpress_item_feed_data');
181 -
165 +
182 166 # Filter in original permalinks if the user wants that
183 - add_filter('post_link', 'syndication_permalink', 1);
167 + add_filter('post_link', 'syndication_permalink', /*priority=*/ 1, /*arguments=*/ 3);
168 + add_filter('post_type_link', 'syndication_permalink', /*priority=*/ 1, /*arguments=*/ 4);
184 169
185 170 # When foreign URLs are used for permalinks in feeds or display
186 171 # contexts, they need to be escaped properly.
187 172 add_filter('the_permalink', 'syndication_permalink_escaped');
188 173 add_filter('the_permalink_rss', 'syndication_permalink_escaped');
189 -
174 +
190 175 add_filter('post_comments_feed_link', 'syndication_comments_feed_link');
191 176
192 177 # WTF? By default, wp_insert_link runs incoming link_url and link_rss
193 178 # URIs through default filters that include `wp_kses()`. But `wp_kses()`
@@ -194,10 +179,11 @@
194 179 # just happens to escape any occurrence of & to &amp; -- which just
195 180 # happens to fuck up any URI with a & to separate GET parameters.
196 181 remove_filter('pre_link_rss', 'wp_filter_kses');
197 182 remove_filter('pre_link_url', 'wp_filter_kses');
198 -
183 +
199 184 # Admin menu
185 + add_action('admin_init', array($feedwordpress, 'admin_init'));
200 186 add_action('admin_menu', 'fwp_add_pages');
201 187 add_action('admin_notices', 'fwp_check_debug');
202 188
203 189 add_action('admin_menu', 'feedwordpress_add_post_edit_controls');
@@ -202,11 +188,13 @@
202 188
203 189 add_action('admin_menu', 'feedwordpress_add_post_edit_controls');
204 190 add_action('save_post', 'feedwordpress_save_post_edit_controls');
205 191
192 + add_action('admin_footer', array($feedwordpress, 'admin_footer'));
193 +
206 194 # Inbound XML-RPC update methods
207 - add_filter('xmlrpc_methods', 'feedwordpress_xmlrpc_hook');
208 -
195 + $feedwordpressRPC = new FeedWordPressRPC;
196 +
209 197 # Outbound XML-RPC ping reform
210 198 remove_action('publish_post', 'generic_ping'); // WP 1.5.x
211 199 remove_action('do_pings', 'do_all_pings', 10, 1); // WP 2.1, 2.2
212 200 remove_action('publish_post', '_publish_post_hook', 5, 1); // WP 2.3
@@ -215,167 +203,110 @@
215 203 add_action('do_pings', 'fwp_do_pings', 10, 1);
216 204 add_action('feedwordpress_update', 'fwp_hold_pings');
217 205 add_action('feedwordpress_update_complete', 'fwp_release_pings');
218 206
219 - # Hook in logging functions only if the logging option is ON
220 - $update_logging = get_option('feedwordpress_update_logging');
221 - if ($update_logging == 'yes') :
222 - add_action('post_syndicated_item', 'log_feedwordpress_post', 100);
223 - add_action('update_syndicated_item', 'log_feedwordpress_update_post', 100);
224 - add_action('feedwordpress_update', 'log_feedwordpress_update_feeds', 100);
225 - add_action('feedwordpress_check_feed', 'log_feedwordpress_check_feed', 100);
226 - add_action('feedwordpress_update_complete', 'log_feedwordpress_update_complete', 100);
227 - endif;
228 -
229 - if (FeedWordPress::update_requested()) :
230 - if (FEEDWORDPRESS_DEBUG) :
231 - add_action('post_syndicated_item', 'debug_out_feedwordpress_post', 100);
232 - add_action('update_syndicated_item', 'debug_out_feedwordpress_update_post', 100);
233 - add_action('feedwordpress_update', 'debug_out_feedwordpress_update_feeds', 100);
234 - add_action('feedwordpress_check_feed', 'debug_out_feedwordpress_check_feed', 100);
235 - add_action('feedwordpress_update_complete', 'debug_out_feedwordpress_update_complete', 100);
236 - endif;
207 + add_action('syndicated_feed_error', array('FeedWordPressDiagnostic', 'feed_error'), 100, 3);
237 208
238 - add_action('feedwordpress_check_feed_complete', 'debug_out_feedwordpress_feed_error', 100, 3);
239 - endif;
209 + add_action('wp_footer', 'debug_out_feedwordpress_footer', -100);
210 + add_action('admin_footer', 'debug_out_feedwordpress_footer', -100);
240 211
241 212 # Cron-less auto-update. Hooray!
242 - $autoUpdateHook = get_option('feedwordpress_automatic_updates');
243 - if ($autoUpdateHook != 'init') :
244 - $autoUpdateHook = 'shutdown';
213 + $autoUpdateHook = $feedwordpress->automatic_update_hook();
214 + if (!is_null($autoUpdateHook)) :
215 + add_action($autoUpdateHook, array($feedwordpress, 'auto_update'));
245 216 endif;
246 - add_action($autoUpdateHook, 'feedwordpress_auto_update');
247 217
248 - add_action('init', 'feedwordpress_update_magic_url');
218 + add_action('init', array($feedwordpress, 'init'));
219 + add_action('shutdown', array($feedwordpress, 'email_diagnostic_log'));
220 + add_action('shutdown', array($feedwordpress, 'feedwordpress_cleanup'));
221 + add_action('wp_dashboard_setup', array($feedwordpress, 'dashboard_setup'));
249 222
250 223 # Default sanitizers
251 224 add_filter('syndicated_item_content', array('SyndicatedPost', 'resolve_relative_uris'), 0, 2);
252 225 add_filter('syndicated_item_content', array('SyndicatedPost', 'sanitize_content'), 0, 2);
253 226
227 + add_action('plugins_loaded', array($feedwordpress, 'admin_api'));
228 + add_action('all_admin_notices', array($feedwordpress, 'all_admin_notices'));
229 +
254 230 else :
255 231 # Hook in the menus, which will just point to the upgrade interface
256 232 add_action('admin_menu', 'fwp_add_pages');
257 233 endif; // if (!FeedWordPress::needs_upgrade())
258 234
259 -function feedwordpress_auto_update () {
260 - if (FeedWordPress::stale()) :
261 - $feedwordpress = new FeedWordPress;
262 - $feedwordpress->update();
263 - endif;
264 -} /* feedwordpress_auto_update () */
265 -
266 -function feedwordpress_update_magic_url () {
267 - global $wpdb;
268 -
269 - // Explicit update request in the HTTP request (e.g. from a cron job)
270 - if (FeedWordPress::update_requested()) :
271 - $feedwordpress = new FeedWordPress;
272 - $feedwordpress->update(FeedWordPress::update_requested_url());
273 -
274 - if (FEEDWORDPRESS_DEBUG and count($wpdb->queries) > 0) :
275 - $mysqlTime = 0.0;
276 - $byTime = array();
277 - foreach ($wpdb->queries as $query) :
278 - $time = $query[1] * 1000000.0;
279 - $mysqlTime += $query[1];
280 - if (!isset($byTime[$time])) : $byTime[$time] = array(); endif;
281 - $byTime[$time][] = $query[0]. ' // STACK: ' . $query[2];
282 - endforeach;
283 - krsort($byTime);
284 -
285 - foreach ($byTime as $time => $querySet) :
286 - foreach ($querySet as $query) :
287 - print "[".(sprintf('%4.4f', $time/1000.0)) . "ms] $query\n";
288 - endforeach;
289 - endforeach;
290 - echo "[feedwordpress] $wpdb->num_queries queries. $mysqlTime seconds in MySQL. Total of "; timer_stop(1); print " seconds.";
291 - endif;
292 -
293 -
294 - // Magic URL should return nothing but a 200 OK header packet
295 - // when successful.
296 - exit;
297 - endif;
298 -} /* feedwordpress_magic_update_url () */
299 -
300 235 ################################################################################
301 236 ## LOGGING FUNCTIONS: log status updates to error_log if you want it ###########
302 237 ################################################################################
303 238
304 -function log_feedwordpress_post ($id) {
305 - $post = wp_get_single_post($id);
306 - error_log("[".date('Y-m-d H:i:s')."][feedwordpress] posted "
307 - ."'{$post->post_title}' ({$post->post_date})");
308 -}
239 +class FeedWordPressDiagnostic {
240 + function feed_error ($error, $old, $link) {
241 + $wpError = $error['object'];
242 + $url = $link->uri();
243 +
244 + // check for effects of an effective-url filter
245 + $effectiveUrl = $link->uri(array('fetch' => true));
246 + if ($url != $effectiveUrl) : $url .= ' | ' . $effectiveUrl; endif;
309 247
310 -function log_feedwordpress_update_post ($id) {
311 - $post = wp_get_single_post($id);
312 - error_log("[".date('Y-m-d H:i:s')."][feedwordpress] updated "
313 - ."'{$post->post_title}' ({$post->post_date})"
314 - ." (as of {$post->post_modified})");
315 -}
248 + $mesgs = $wpError->get_error_messages();
249 + foreach ($mesgs as $mesg) :
250 + $mesg = esc_html($mesg);
251 + FeedWordPress::diagnostic(
252 + 'updated_feeds:errors',
253 + "Feed Error: [${url}] update returned error: $mesg"
254 + );
316 255
317 -function log_feedwordpress_update_feeds ($uri) {
318 - error_log("[".date('Y-m-d H:i:s')."][feedwordpress] update('$uri')");
319 -}
256 + $hours = get_option('feedwordpress_diagnostics_persistent_errors_hours', 2);
257 + $span = ($error['ts'] - $error['since']);
320 258
321 -function log_feedwordpress_check_feed ($feed) {
322 - $uri = $feed['link/uri']; $name = $feed['link/name'];
323 - error_log("[".date('Y-m-d H:i:s')."][feedwordpress] Examining $name <$uri>");
324 -}
259 + if ($span >= ($hours * 60 * 60)) :
260 + $since = date('r', $error['since']);
261 + $mostRecent = date('r', $error['ts']);
262 + FeedWordPress::diagnostic(
263 + 'updated_feeds:errors:persistent',
264 + "Feed Update Error: [${url}] returning errors"
265 + ." since ${since}:<br/><code>$mesg</code>",
266 + $url, $error['since'], $error['ts']
267 + );
268 + endif;
269 + endforeach;
270 + }
325 271
326 -function log_feedwordpress_update_complete ($delta) {
327 - $mesg = array();
328 - if (isset($delta['new'])) $mesg[] = 'added '.$delta['new'].' new posts';
329 - if (isset($delta['updated'])) $mesg[] = 'updated '.$delta['updated'].' existing posts';
330 - if (empty($mesg)) $mesg[] = 'nothing changed';
272 + function admin_emails ($id = '') {
273 + $users = get_users_of_blog($id);
274 + $recipients = array();
275 + foreach ($users as $user) :
276 + $user_id = (isset($user->user_id) ? $user->user_id : $user->ID);
277 + $dude = new WP_User($user_id);
278 + if ($dude->has_cap('administrator')) :
279 + if ($dude->user_email) :
280 + $recipients[] = $dude->user_email;
281 + endif;
282 + endif;
283 + endforeach;
284 + return $recipients;
285 + }
286 +} /* class FeedWordPressDiagnostic */
331 287
332 - error_log("[".date('Y-m-d H:i:s')."][feedwordpress] "
333 - .(is_null($delta) ? "Error: I don't syndicate that URI"
334 - : implode(' and ', $mesg)));
288 +function debug_out_human_readable_bytes ($quantity) {
289 + $quantity = (int) $quantity;
290 + $magnitude = 'B';
291 + $orders = array('KB', 'MB', 'GB', 'TB');
292 + while (($quantity > (1024*100)) and (count($orders) > 0)) :
293 + $quantity = floor($quantity / 1024);
294 + $magnitude = array_shift($orders);
295 + endwhile;
296 + return "${quantity} ${magnitude}";
335 297 }
336 298
337 -function debug_out_feedwordpress_post ($id) {
338 - $post = wp_get_single_post($id);
339 - print ("[".date('Y-m-d H:i:s')."][feedwordpress] posted "
340 - ."'{$post->post_title}' ({$post->post_date})\n");
341 -}
342 -
343 -function debug_out_feedwordpress_update_post ($id) {
344 - $post = wp_get_single_post($id);
345 - print ("[".date('Y-m-d H:i:s')."][feedwordpress] updated "
346 - ."'{$post->post_title}' ({$post->post_date})"
347 - ." (as of {$post->post_modified})\n");
348 -}
349 -
350 -function debug_out_feedwordpress_update_feeds ($uri) {
351 - print ("[".date('Y-m-d H:i:s')."][feedwordpress] update('$uri')\n");
352 -}
353 -
354 -function debug_out_feedwordpress_check_feed ($feed) {
355 - $uri = $feed['link/uri']; $name = $feed['link/name'];
356 - print ("[".date('Y-m-d H:i:s')."][feedwordpress] Examining $name <$uri>\n");
357 -}
358 -
359 -function debug_out_feedwordpress_update_complete ($delta) {
360 - $mesg = array();
361 - if (isset($delta['new'])) $mesg[] = 'added '.$delta['new'].' new posts';
362 - if (isset($delta['updated'])) $mesg[] = 'updated '.$delta['updated'].' existing posts';
363 - if (empty($mesg)) $mesg[] = 'nothing changed';
364 -
365 - print ("[".date('Y-m-d H:i:s')."][feedwordpress] "
366 - .(is_null($delta) ? "Error: I don't syndicate that URI"
367 - : implode(' and ', $mesg))."\n");
368 -}
369 -
370 -function debug_out_feedwordpress_feed_error ($feed, $added, $dt) {
371 - if (is_wp_error($added)) :
372 - $mesgs = $added->get_error_messages();
373 - foreach ($mesgs as $mesg) :
374 - echo "[feedwordpress] Error updating [{$feed['link/uri']}]: $mesg\n";
375 - endforeach;
299 +function debug_out_feedwordpress_footer () {
300 + if (FeedWordPress::diagnostic_on('memory_usage')) :
301 + if (function_exists('memory_get_usage')) :
302 + FeedWordPress::diagnostic ('memory_usage', "Memory: Current usage: ".debug_out_human_readable_bytes(memory_get_usage()));
303 + endif;
304 + if (function_exists('memory_get_peak_usage')) :
305 + FeedWordPress::diagnostic ('memory_usage', "Memory: Peak usage: ".debug_out_human_readable_bytes(memory_get_peak_usage()));
306 + endif;
376 307 endif;
377 -}
308 +} /* debug_out_feedwordpress_footer() */
378 309
379 310 ################################################################################
380 311 ## TEMPLATE API: functions to make your templates syndication-aware ############
381 312 ################################################################################
@@ -386,39 +317,22 @@
386 317 * to determine whether or not to retrieve syndication-related meta-data in
387 318 * displaying a post.
388 319 *
389 320 * @param int $id The post to check for syndicated status. Defaults to the current post in a Loop context.
390 - * @return bool TRUE if the post's meta-data indicates it was syndicated; FALSE otherwise
391 - */
321 + * @return bool TRUE if the post's meta-data indicates it was syndicated; FALSE otherwise
322 + */
392 323 function is_syndicated ($id = NULL) {
393 - return (strlen(get_syndication_feed_id($id)) > 0);
324 + $p = new FeedWordPressLocalPost($id);
325 + return $p->is_syndicated();
394 326 } /* function is_syndicated() */
395 327
396 -function get_syndication_source_link ($original = NULL, $id = NULL) {
397 - if (is_null($original)) : $original = FeedWordPress::use_aggregator_source_data();
398 - endif;
399 -
400 - if ($original) : $vals = get_post_custom_values('syndication_source_uri_original', $id);
401 - else : $vals = array();
402 - endif;
403 -
404 - if (count($vals) == 0) : $vals = get_post_custom_values('syndication_source_uri', $id);
405 - endif;
406 -
407 - if (count($vals) > 0) : $ret = $vals[0]; else : $ret = NULL; endif;
408 -
409 - return $ret;
410 -} /* function get_syndication_source_link() */
411 -
412 -function the_syndication_source_link ($original = NULL, $id = NULL) {
413 - echo get_syndication_source_link($original, $id);
414 -}
415 -
416 328 function feedwordpress_display_url ($url, $before = 60, $after = 0) {
417 329 $bits = parse_url($url);
418 -
330 +
419 331 // Strip out crufty subdomains
420 - $bits['host'] = preg_replace('/^www[0-9]*\./i', '', $bits['host']);
332 + if (isset($bits['host'])) :
333 + $bits['host'] = preg_replace('/^www[0-9]*\./i', '', $bits['host']);
334 + endif;
421 335
422 336 // Reassemble bit-by-bit with minimum of crufty elements
423 337 $url = (isset($bits['user'])?$bits['user'].'@':'')
424 338 .(isset($bits['host'])?$bits['host']:'')
@@ -426,102 +340,69 @@
426 340 .(isset($uri_bits['port'])?':'.$uri_bits['port']:'')
427 341 .(isset($bits['query'])?'?'.$bits['query']:'');
428 342
429 343 if (strlen($url) > ($before+$after)) :
430 - $url = substr($url, 0, $before).'…'.substr($url, 0 - $after, $after);
344 + $url = substr($url, 0, $before).'.'.substr($url, 0 - $after, $after);
431 345 endif;
432 346
433 347 return $url;
434 -}
348 +} /* feedwordpress_display_url () */
435 349
436 -function get_syndication_source ($original = NULL, $id = NULL) {
437 - if (is_null($original)) :
438 - $original = FeedWordPress::use_aggregator_source_data();
439 - endif;
350 +function get_syndication_source_property ($original, $id, $local, $remote = NULL) {
351 + $p = new FeedWordPressLocalPost($id);
352 + return $p->meta($local, array("unproxy" => $original, "unproxied setting" => $remote));
353 +} /* function get_syndication_source_property () */
440 354
441 - if ($original) :
442 - $vals = get_post_custom_values('syndication_source_original', $id);
443 - else :
444 - $vals = array();
445 - endif;
446 -
447 - if (count($vals) == 0) :
448 - $vals = get_post_custom_values('syndication_source', $id);
449 - endif;
450 -
451 - if (count($vals) > 0) :
452 - $ret = $vals[0];
453 - else :
454 - $ret = NULL;
455 - endif;
355 +function get_syndication_source_link ($original = NULL, $id = NULL) {
356 + $p = new FeedWordPressLocalPost($id);
357 + return $p->syndication_source_link($original);
358 +} /* function get_syndication_source_link() */
456 359
457 - if (is_null($ret) or strlen(trim($ret)) == 0) :
458 - // Fall back to URL of blog
459 - $ret = feedwordpress_display_url(get_syndication_source_link());
460 - endif;
360 +function the_syndication_source_link ($original = NULL, $id = NULL) {
361 + echo get_syndication_source_link($original, $id);
362 +} /* function the_syndication_source_link() */
461 363
462 - return $ret;
364 +function get_syndication_source ($original = NULL, $id = NULL) {
365 + $p = new FeedWordPressLocalPost($id);
366 + return $p->syndication_source($original);
463 367 } /* function get_syndication_source() */
464 368
465 -function the_syndication_source ($original = NULL, $id = NULL) { echo get_syndication_source($original, $id); }
369 +function the_syndication_source ($original = NULL, $id = NULL) {
370 + echo get_syndication_source($original, $id);
371 +} /* function the_syndication_source () */
466 372
467 373 function get_syndication_feed ($original = NULL, $id = NULL) {
468 - if (is_null($original)) : $original = FeedWordPress::use_aggregator_source_data();
469 - endif;
470 -
471 - if ($original) : $vals = get_post_custom_values('syndication_feed_original', $id);
472 - else : $vals = array();
473 - endif;
474 -
475 - if (count($vals) == 0) : $vals = get_post_custom_values('syndication_feed', $id);
476 - endif;
477 -
478 - if (count($vals) > 0) : $ret = $vals[0]; else : $ret = NULL; endif;
479 -
480 - return $ret;
374 + $p = new FeedWordPressLocalPost($id);
375 + return $p->syndication_feed($original);
481 376 } /* function get_syndication_feed() */
482 377
483 -function the_syndication_feed ($original = NULL, $id = NULL) { echo get_syndication_feed($original, $id); }
378 +function the_syndication_feed ($original = NULL, $id = NULL) {
379 + echo get_syndication_feed($original, $id);
380 +} /* function the_syndication_feed() */
484 381
485 382 function get_syndication_feed_guid ($original = NULL, $id = NULL) {
486 - if (is_null($original)) : $original = FeedWordPress::use_aggregator_source_data();
487 - endif;
383 + $p = new FeedWordPressLocalPost($id);
384 + return $p->syndication_feed_guid($original);
385 +} /* function get_syndication_feed_guid () */
488 386
489 - if ($original) : $vals = get_post_custom_values('syndication_source_id_original', $id);
490 - else : $vals = array();
491 - endif;
492 -
493 - if (count($vals) == 0) : $vals = array(get_feed_meta('feed/id', $id));
494 - endif;
495 -
496 - if (count($vals) > 0) : $ret = $vals[0]; else : $ret = NULL; endif;
387 +function the_syndication_feed_guid ($original = NULL, $id = NULL) {
388 + echo get_syndication_feed_guid($original, $id);
389 +} /* function the_syndication_feed_guid () */
497 390
498 - return $ret;
499 -} /* function get_syndication_feed_guid () */
391 +function get_syndication_feed_id ($id = NULL) {
392 + $p = new FeedWordPressLocalPost($id);
393 + return $p->feed_id();
394 +} /* function get_syndication_feed_id () */
500 395
501 -function the_syndication_feed_guid ($original = NULL, $id = NULL) { echo get_syndication_feed_guid($original, $id); }
396 +function the_syndication_feed_id ($id = NULL) {
397 + echo get_syndication_feed_id($id);
398 +} /* function the_syndication_feed_id () */
502 399
503 -function get_syndication_feed_id ($id = NULL) { list($u) = get_post_custom_values('syndication_feed_id', $id); return $u; }
504 -function the_syndication_feed_id ($id = NULL) { echo get_syndication_feed_id($id); }
505 -
506 -$feedwordpress_linkcache = array (); // only load links from database once
507 400 function get_syndication_feed_object ($id = NULL) {
508 - global $feedwordpress_linkcache;
401 + $p = new FeedWordPressLocalPost($id);
402 + return $p->feed();
403 +} /* function get_syndication_feed_object() */
509 404
510 - $link = NULL;
511 -
512 - $feed_id = get_syndication_feed_id($id);
513 - if (strlen($feed_id) > 0):
514 - if (isset($feedwordpress_linkcache[$feed_id])) :
515 - $link = $feedwordpress_linkcache[$feed_id];
516 - else :
517 - $link = new SyndicatedLink($feed_id);
518 - $feedwordpress_linkcache[$feed_id] = $link;
519 - endif;
520 - endif;
521 - return $link;
522 -}
523 -
524 405 function get_feed_meta ($key, $id = NULL) {
525 406 $ret = NULL;
526 407
527 408 $link = get_syndication_feed_object($id);
@@ -528,16 +409,18 @@
528 409 if (is_object($link) and isset($link->settings[$key])) :
529 410 $ret = $link->settings[$key];
530 411 endif;
531 412 return $ret;
532 -} /* get_feed_meta() */
413 +} /* function get_feed_meta() */
533 414
534 415 function get_syndication_permalink ($id = NULL) {
535 - list($u) = get_post_custom_values('syndication_permalink', $id); return $u;
536 -}
416 + $p = new FeedWordPressLocalPost($id);
417 + return $p->syndication_permalink();
418 +} /* function get_syndication_permalink () */
419 +
537 420 function the_syndication_permalink ($id = NULL) {
538 421 echo get_syndication_permalink($id);
539 -}
422 +} /* function the_syndication_permalink () */
540 423
541 424 /**
542 425 * get_local_permalink: returns a string containing the internal permalink
543 426 * for a post (whether syndicated or not) on your local WordPress installation.
@@ -556,9 +439,9 @@
556 439 * @since 2010.0217
557 440 */
558 441 function get_local_permalink ($id = NULL) {
559 442 global $feedwordpress_the_original_permalink;
560 -
443 +
561 444 // get permalink, and thus activate filter and force global to be filled
562 445 // with original URL.
563 446 $url = get_permalink($id);
564 447 return $feedwordpress_the_original_permalink;
@@ -588,13 +471,10 @@
588 471
589 472 function feedwordpress_preserve_syndicated_content ($text) {
590 473 global $feedwordpress_the_syndicated_content;
591 474
592 - $globalExpose = (get_option('feedwordpress_formatting_filters') == 'yes');
593 - $localExpose = get_post_custom_values('_feedwordpress_formatting_filters');
594 - $expose = ($globalExpose or ((count($localExpose) > 0) and $localExpose[0]));
595 -
596 - if ( is_syndicated() and !$expose ) :
475 + $p = new FeedWordPressLocalPost;
476 + if (!$p->is_exposed_to_formatting_filters()) :
597 477 $feedwordpress_the_syndicated_content = $text;
598 478 else :
599 479 $feedwordpress_the_syndicated_content = NULL;
600 480 endif;
@@ -602,9 +482,9 @@
602 482 }
603 483
604 484 function feedwordpress_restore_syndicated_content ($text) {
605 485 global $feedwordpress_the_syndicated_content;
606 -
486 +
607 487 if ( !is_null($feedwordpress_the_syndicated_content) ) :
608 488 $text = $feedwordpress_the_syndicated_content;
609 489 endif;
610 490
@@ -647,30 +527,43 @@
647 527 * @return string The new permalink. Same as the old if the post is not
648 528 * syndicated, or if FWP is set to use internal permalinks, or if the post
649 529 * was syndicated, but didn't have a proper permalink recorded.
650 530 *
651 - * @uses FeedWordPress::munge_permalinks()
531 + * @uses SyndicatedLink::setting()
652 532 * @uses get_syndication_permalink()
533 + * @uses get_syndication_feed_object()
534 + * @uses url_to_postid()
535 + * @global $id
653 536 * @global $feedwordpress_the_original_permalink
654 - */
655 -function syndication_permalink ($permalink = '') {
537 + */
538 +function syndication_permalink ($permalink = '', $post = null, $leavename = false, $sample = false) {
539 + global $id;
656 540 global $feedwordpress_the_original_permalink;
657 -
541 +
658 542 // Save the local permalink in case we need to retrieve it later.
659 543 $feedwordpress_the_original_permalink = $permalink;
660 544
661 - // Map this permalink to a post ID so we can get the correct permalink
662 - // even outside of the Post Loop. Props Björn.
663 - $id = url_to_postid($permalink);
545 + if (is_object($post) and isset($post->ID) and !empty($post->ID)) :
546 + // Use the post ID we've been provided with.
547 + $postId = $post->ID;
548 + elseif (is_string($permalink) and strlen($permalink) > 0) :
549 + // Map this permalink to a post ID so we can get the correct
550 + // permalink even outside of the Post Loop. Props Björn.
551 + $postId = url_to_postid($permalink);
552 + else :
553 + // If the permalink string is empty but Post Loop context
554 + // provides an id.
555 + $postId = $id;
556 + endif;
664 557
665 558 $munge = false;
666 - $link = get_syndication_feed_object($id);
559 + $link = get_syndication_feed_object($postId);
667 560 if (is_object($link)) :
668 561 $munge = ($link->setting('munge permalink', 'munge_permalink', 'yes') != 'no');
669 562 endif;
670 563
671 564 if ($munge):
672 - $uri = get_syndication_permalink($id);
565 + $uri = get_syndication_permalink($postId);
673 566 $permalink = ((strlen($uri) > 0) ? $uri : $permalink);
674 567 endif;
675 568 return $permalink;
676 569 } /* function syndication_permalink () */
@@ -686,8 +579,9 @@
686 579 * @uses FeedWordPress::munge_permalinks()
687 580 *
688 581 */
689 582 function syndication_permalink_escaped ($permalink) {
583 + /* FIXME: This should review link settings not just global settings */
690 584 if (is_syndicated() and FeedWordPress::munge_permalinks()) :
691 585 // This is a foreign link; WordPress can't vouch for its not
692 586 // having any entities that need to be &-escaped. So we'll do
693 587 // it here.
@@ -693,13 +587,13 @@
693 587 // it here.
694 588 $permalink = esc_html($permalink);
695 589 endif;
696 590 return $permalink;
697 -} /* function syndication_permalink_escaped() */
591 +} /* function syndication_permalink_escaped() */
698 592
699 593 /**
700 594 * syndication_comments_feed_link: Escape XML special characters in comments
701 - * feed links
595 + * feed links
702 596 *
703 597 * @param string $link
704 598 * @return string
705 599 *
@@ -714,8 +608,9 @@
714 608 // wfw:commentRss or atom:link/@rel="replies" we can make use of
715 609 // that value here.
716 610 $source = get_syndication_feed_object();
717 611 $replacement = NULL;
612 +
718 613 if ($source->setting('munge comments feed links', 'munge_comments_feed_links', 'yes') != 'no') :
719 614 $commentFeeds = get_post_custom_values('wfw:commentRSS');
720 615 if (
721 616 is_array($commentFeeds)
@@ -722,9 +617,9 @@
722 617 and (count($commentFeeds) > 0)
723 618 and (strlen($commentFeeds[0]) > 0)
724 619 ) :
725 620 $replacement = $commentFeeds[0];
726 -
621 +
727 622 // This is a foreign link; WordPress can't vouch for its not
728 623 // having any entities that need to be &-escaped. So we'll do it
729 624 // here.
730 625 $replacement = esc_html($replacement);
@@ -729,9 +624,9 @@
729 624 // here.
730 625 $replacement = esc_html($replacement);
731 626 endif;
732 627 endif;
733 -
628 +
734 629 if (is_null($replacement)) :
735 630 // Q: How can we get the proper feed format, since the
736 631 // format is, stupidly, not passed to the filter?
737 632 // A: Kludge kludge kludge kludge!
@@ -753,9 +648,9 @@
753 648 // generate the comment feed URL, so the
754 649 // comments feed link is never munged by FWP.
755 650 endif;
756 651 endif;
757 -
652 +
758 653 if (!is_null($replacement)) : $link = $replacement; endif;
759 654 endif;
760 655 return $link;
761 656 } /* function syndication_comments_feed_link() */
@@ -764,23 +659,66 @@
764 659 ## ADMIN MENU ADD-ONS: register Dashboard management pages #####################
765 660 ################################################################################
766 661
767 662 function fwp_add_pages () {
768 - global $fwp_capability;
769 - global $fwp_path;
663 + global $feedwordpress;
770 664
771 - $menu = array('Syndicated Sites', 'Syndication', $fwp_capability['manage_links'], $fwp_path.'/syndication.php', NULL);
772 - if (fwp_test_wp_version(FWP_SCHEMA_27)) :
773 - // add icon parameter
774 - $menu[] = WP_PLUGIN_URL.'/'.$fwp_path.'/feedwordpress-tiny.png';
775 - endif;
665 + $menu_cap = FeedWordPress::menu_cap();
666 + $settings_cap = FeedWordPress::menu_cap(/*sub=*/ true);
667 + $syndicationMenu = FeedWordPress::path('syndication.php');
776 668
777 - call_user_func_array('add_menu_page', $menu);
778 - add_submenu_page($fwp_path.'/syndication.php', 'Syndicated Feeds & Updates', 'Feeds & Updates', $fwp_capability['manage_options'], $fwp_path.'/feeds-page.php');
779 - add_submenu_page($fwp_path.'/syndication.php', 'Syndicated Posts & Links', 'Posts & Links', $fwp_capability['manage_options'], $fwp_path.'/posts-page.php');
780 - add_submenu_page($fwp_path.'/syndication.php', 'Syndicated Authors', 'Authors', $fwp_capability['manage_options'], $fwp_path.'/authors-page.php');
781 - add_submenu_page($fwp_path.'/syndication.php', 'Categories'.FEEDWORDPRESS_AND_TAGS, 'Categories'.FEEDWORDPRESS_AND_TAGS, $fwp_capability['manage_options'], $fwp_path.'/categories-page.php');
782 - add_submenu_page($fwp_path.'/syndication.php', 'FeedWordPress Back End', 'Back End', $fwp_capability['manage_options'], $fwp_path.'/backend-page.php');
669 + add_menu_page(
670 + 'Syndicated Sites', 'Syndication',
671 + $menu_cap,
672 + $syndicationMenu,
673 + NULL,
674 + WP_PLUGIN_URL.'/'.FeedWordPress::path('feedwordpress-tiny.png')
675 + );
676 +
677 + do_action('feedwordpress_admin_menu_pre_feeds', $menu_cap, $settings_cap);
678 + add_submenu_page(
679 + $syndicationMenu, 'Syndicated Sites', 'Syndicated Sites',
680 + $settings_cap, $syndicationMenu
681 + );
682 +
683 + do_action('feedwordpress_admin_menu_pre_feeds', $menu_cap, $settings_cap);
684 + add_submenu_page(
685 + $syndicationMenu, 'Syndicated Feeds & Updates', 'Feeds & Updates',
686 + $settings_cap, FeedWordPress::path('feeds-page.php')
687 + );
688 +
689 + do_action('feedwordpress_admin_menu_pre_posts', $menu_cap, $settings_cap);
690 + add_submenu_page(
691 + $syndicationMenu, 'Syndicated Posts & Links', 'Posts & Links',
692 + $settings_cap, FeedWordPress::path('posts-page.php')
693 + );
694 +
695 + do_action('feedwordpress_admin_menu_pre_authors', $menu_cap, $settings_cap);
696 + add_submenu_page(
697 + $syndicationMenu, 'Syndicated Authors', 'Authors',
698 + $settings_cap, FeedWordPress::path('authors-page.php')
699 + );
700 +
701 + do_action('feedwordpress_admin_menu_pre_categories', $menu_cap, $settings_cap);
702 + add_submenu_page(
703 + $syndicationMenu, 'Categories & Tags', 'Categories & Tags',
704 + $settings_cap, FeedWordPress::path('categories-page.php')
705 + );
706 +
707 + do_action('feedwordpress_admin_menu_pre_performance', $menu_cap, $settings_cap);
708 + add_submenu_page(
709 + $syndicationMenu, 'FeedWordPress Performance', 'Performance',
710 + $settings_cap, FeedWordPress::path('performance-page.php')
711 + );
712 +
713 + do_action('feedwordpress_admin_menu_pre_diagnostics', $menu_cap, $settings_cap);
714 + add_submenu_page(
715 + $syndicationMenu, 'FeedWordPress Diagnostics', 'Diagnostics',
716 + $settings_cap, FeedWordPress::path('diagnostics-page.php')
717 + );
718 +
719 + add_filter('page_row_actions', array($feedwordpress, 'row_actions'), 10, 2);
720 + add_filter('post_row_actions', array($feedwordpress, 'row_actions'), 10, 2);
783 721 } /* function fwp_add_pages () */
784 722
785 723 function fwp_check_debug () {
786 724 // This is a horrible fucking kludge that I have to do because the
@@ -847,9 +785,9 @@
847 785 if ( defined('XMLRPC_REQUEST') )
848 786 do_action('xmlrpc_publish_post', $post_id);
849 787 if ( defined('APP_REQUEST') )
850 788 do_action('app_publish_post', $post_id);
851 -
789 +
852 790 if ( defined('WP_IMPORTING') )
853 791 return;
854 792
855 793 // Defer sending out pings until we finish updating
@@ -861,14 +799,35 @@
861 799 endif;
862 800 }
863 801
864 802 function feedwordpress_add_post_edit_controls () {
865 - add_meta_box('feedwordpress-post-controls', __('Syndication'), 'feedwordpress_post_edit_controls', 'post', 'side', 'high');
866 - } // function FeedWordPress::postEditControls
867 -
803 + global $feedwordpress;
804 + global $inspectPostMeta;
805 +
806 + // Put in Manual Editing checkbox
807 + add_action('add_meta_boxes', 'feedwordpress_post_add_meta_boxes', 10, 2);
808 +
809 + add_filter('user_can_richedit', array($feedwordpress, 'user_can_richedit'), 1000, 1);
810 +
811 + if (FeedWordPress::diagnostic_on('syndicated_posts:static_meta_data')) :
812 + $inspectPostMeta = new InspectPostMeta;
813 + endif;
814 + } // function feedwordpress_add_post_edit_controls ()
815 +
816 + function feedwordpress_post_add_meta_boxes ($post_type, $post) {
817 + add_meta_box(
818 + 'feedwordpress-post-controls',
819 + __('Syndication'),
820 + 'feedwordpress_post_edit_controls',
821 + $post_type,
822 + 'side',
823 + 'high'
824 + );
825 + }
826 +
868 827 function feedwordpress_post_edit_controls () {
869 828 global $post;
870 -
829 +
871 830 $frozen_values = get_post_custom_values('_syndication_freeze_updates', $post->ID);
872 831 $frozen_post = (count($frozen_values) > 0 and 'yes' == $frozen_values[0]);
873 832
874 833 if (is_syndicated($post->ID)) :
@@ -875,8 +834,10 @@
875 834 ?>
876 835 <p>This is a syndicated post, which originally appeared at
877 836 <cite><?php print esc_html(get_syndication_source(NULL, $post->ID)); ?></cite>.
878 837 <a href="<?php print esc_html(get_syndication_permalink($post->ID)); ?>">View original post</a>.</p>
838 +
839 + <?php do_action('feedwordpress_post_edit_controls_pre', $post); ?>
879 840
880 841 <p><input type="hidden" name="feedwordpress_noncename" id="feedwordpress_noncename" value="<?php print wp_create_nonce(plugin_basename(__FILE__)); ?>" />
881 842 <label><input type="checkbox" name="freeze_updates" value="yes" <?php if ($frozen_post) : ?>checked="checked"<?php endif; ?> /> <strong>Manual editing.</strong>
882 843 If set, FeedWordPress will not overwrite the changes you make manually
@@ -881,8 +842,11 @@
881 842 <label><input type="checkbox" name="freeze_updates" value="yes" <?php if ($frozen_post) : ?>checked="checked"<?php endif; ?> /> <strong>Manual editing.</strong>
882 843 If set, FeedWordPress will not overwrite the changes you make manually
883 844 to this post, if the syndicated content is updated on the
884 845 feed.</label></p>
846 +
847 + <?php do_action('feedwordpress_post_edit_controls', $post); ?>
848 +
885 849 <?php
886 850 else :
887 851 ?>
888 852 <p>This post was created locally at this website.</p>
@@ -887,36 +851,57 @@
887 851 ?>
888 852 <p>This post was created locally at this website.</p>
889 853 <?php
890 854 endif;
891 - } // function feedwordpress_post_edit_controls () */
855 + } /* function feedwordpress_post_edit_controls () */
892 856
893 857 function feedwordpress_save_post_edit_controls ( $post_id ) {
894 858 global $post;
895 -
896 859 if (!isset($_POST['feedwordpress_noncename']) or !wp_verify_nonce($_POST['feedwordpress_noncename'], plugin_basename(__FILE__))) :
897 860 return $post_id;
898 861 endif;
899 -
862 +
900 863 // Verify if this is an auto save routine. If it is our form has
901 864 // not been submitted, so we don't want to do anything.
902 865 if ( defined('DOING_AUTOSAVE') and DOING_AUTOSAVE ) :
903 866 return $post_id;
904 867 endif;
868 +
869 + // The data in $_POST is for applying only to the post actually
870 + // in the edit window, i.e. $post
871 + if ($post_id != $post->ID) :
872 + return $post_id;
873 + endif;
905 874
906 875 // Check permissions
907 - if ( !current_user_can( 'edit_'.$_POST['post_type'], $post_id) ) :
876 + $cap[0] = 'edit_post';
877 + $cap[1] = 'edit_' . $_POST['post_type'];
878 + if (
879 + !current_user_can( $cap[0], $post_id )
880 + and !current_user_can( $cap[1], $post_id )
881 + ) :
908 882 return $post_id;
909 883 endif;
910 884
911 885 // OK, we're golden. Now let's save some data.
912 886 if (isset($_POST['freeze_updates'])) :
913 - update_post_meta($post_id, '_syndication_freeze_updates', $_POST['freeze_updates']);
887 +
888 + update_post_meta($post_id, '_syndication_freeze_updates', $_POST['freeze_updates']);
889 + $ret = $_POST['freeze_updates'];
890 +
891 + // If you make manual edits through the WordPress editing
892 + // UI then they should be run through normal WP formatting
893 + // filters.
894 + update_post_meta($post_id, '_feedwordpress_formatting_filters', 'yes');
895 +
914 896 else :
915 897 delete_post_meta($post_id, '_syndication_freeze_updates');
898 + $ret = NULL;
916 899 endif;
917 -
918 - return $_POST['freeze_updates'];
900 +
901 + do_action('feedwordpress_save_edit_controls', $post_id);
902 +
903 + return $ret;
919 904 } // function feedwordpress_save_edit_controls
920 905
921 906 ################################################################################
922 907 ## class FeedWordPress #########################################################
@@ -956,18 +941,82 @@
956 941 array('script', 'src')
957 942 );
958 943
959 944 var $feeds = NULL;
945 + var $feedurls = NULL;
946 + var $httpauth = NULL;
960 947
961 - # function FeedWordPress (): Contructor; retrieve a list of feeds
962 - function FeedWordPress () {
948 + /**
949 + * FeedWordPress::__construct (): Construct FeedWordPress singleton object
950 + * and retrieves a list of feeds for later reference.
951 + */
952 + public function __construct () {
963 953 $this->feeds = array ();
954 + $this->feedurls = array();
964 955 $links = FeedWordPress::syndicated_links();
965 956 if ($links): foreach ($links as $link):
966 - $this->feeds[] = new SyndicatedLink($link);
957 + $id = intval($link->link_id);
958 + $url = $link->link_rss;
959 +
960 + // Store for later reference.
961 + $this->feeds[$id] = $id;
962 + if (strlen($url) > 0) :
963 + $this->feedurls[$url] = $id;
964 + endif;
967 965 endforeach; endif;
968 - } // FeedWordPress::FeedWordPress ()
969 966
967 + add_filter('feedwordpress_update_complete', array($this, 'process_retirements'), 1000, 1);
968 +
969 + $this->httpauth = new FeedWordPressHTTPAuthenticator;
970 + } /* FeedWordPress::__construct () */
971 +
972 + /**
973 + * FeedWordPress::subscribed (): Check whether a feed is currently in the
974 + * subscription list for FeedWordPress.
975 + *
976 + * @param mixed $id Numeric ID of a WordPress link object or URL of a feed
977 + * @return bool TRUE if currently subscribed; FALSE otherwise.
978 + */
979 + public function subscribed ($id) {
980 + return (isset($this->feedurls[$id]) or isset($this->feeds[$id]));
981 + } /* FeedWordPress::subscribed () */
982 +
983 + /**
984 + * FeedWordPress::subscription (): Get the SyndicatedLink object for a
985 + * given URL or numeric ID, if we have either an active subscription to
986 + * it; or a de-activated subscription.
987 + *
988 + * @param mixed $which Numeric ID for a WordPress link object or string URL for a feed
989 + * @return mixed SyndicatedLink object if subscription is found; NULL if not
990 + */
991 + public function subscription ($which) {
992 + $sub = NULL;
993 +
994 + if (is_string($which) and isset($this->feedurls[$which])) :
995 + $which = $this->feedurls[$which];
996 + endif;
997 +
998 + if (isset($this->feeds[$which])) :
999 + $sub = $this->feeds[$which];
1000 + endif;
1001 +
1002 + // If it's not in the in-memory cache already, try to load it from DB.
1003 + // This is necessary to fill requests for subscriptions that we don't
1004 + // cache in memory, e.g. for deactivated feeds.
1005 + if (is_null($sub)) :
1006 + $sub = get_bookmark($which);
1007 + endif;
1008 +
1009 + // Load 'er up if you haven't already.
1010 + if (!is_null($sub) and !($sub InstanceOf SyndicatedLink)) :
1011 + $link = new SyndicatedLink($sub);
1012 + $this->feeds[$which] = $link;
1013 + $sub = $link;
1014 + endif;
1015 +
1016 + return $sub;
1017 + } /* FeedWordPress::subscription () */
1018 +
970 1019 # function update (): polls for updates on one or more Contributor feeds
971 1020 #
972 1021 # Arguments:
973 1022 # ----------
@@ -1011,22 +1060,29 @@
1011 1060 # module elements) or else from a randomly-generated time window
1012 1061 # (between 30 minutes and 2 hours).
1013 1062 #
1014 1063 # * New posts from the polled feed are added to the WordPress store.
1015 - #
1064 + #
1016 1065 # * Updates to existing posts since the last poll are mirrored in the
1017 1066 # WordPress store.
1018 1067 #
1019 - function update ($uri = null, $crash_ts = null) {
1068 + public function update ($uri = null, $crash_ts = null) {
1020 1069 global $wpdb;
1021 1070
1022 1071 if (FeedWordPress::needs_upgrade()) : // Will make duplicate posts if we don't hold off
1023 1072 return NULL;
1024 1073 endif;
1025 -
1026 - if (!is_null($uri)) :
1074 +
1075 + if (!is_null($uri) and $uri != '*') :
1027 1076 $uri = trim($uri);
1028 1077 else : // Update all
1078 + if ($this->update_hooked) :
1079 + $diag = $this->update_hooked;
1080 + else :
1081 + $diag = 'Initiating a MANUAL check-in on the update schedule at '.date('r', time());
1082 + endif;
1083 + $this->diagnostic('update_schedule:check', $diag);
1084 +
1029 1085 update_option('feedwordpress_last_update_all', time());
1030 1086 endif;
1031 1087
1032 1088 do_action('feedwordpress_update', $uri);
@@ -1031,24 +1087,43 @@
1031 1087
1032 1088 do_action('feedwordpress_update', $uri);
1033 1089
1034 1090 if (is_null($crash_ts)) :
1035 - $crash_dt = (int) get_option('feedwordpress_update_time_limit');
1036 - if ($crash_dt > 0) :
1037 - $crash_ts = time() + $crash_dt;
1038 - else :
1039 - $crash_ts = NULL;
1040 - endif;
1091 + $crash_ts = $this->crash_ts();
1041 1092 endif;
1042 -
1093 +
1043 1094 // Randomize order for load balancing purposes
1044 - $feed_set = $this->feeds;
1095 + $feed_set = array_keys($this->feeds);
1045 1096 shuffle($feed_set);
1046 1097
1098 + $updateWindow = (int) get_option('feedwordpress_update_window', DEFAULT_UPDATE_PERIOD) * 60 /* sec/min */;
1099 + $interval = (int) get_option('feedwordpress_freshness', FEEDWORDPRESS_FRESHNESS_INTERVAL);
1100 + $portion = max(
1101 + (int) ceil(count($feed_set) / ($updateWindow / $interval)),
1102 + 10
1103 + );
1104 +
1105 + $max_polls = apply_filters('feedwordpress_polls_per_update', get_option(
1106 + 'feedwordpress_polls_per_update', $portion
1107 + ), $uri);
1108 +
1109 + $feed_set = apply_filters('feedwordpress_update_feeds', $feed_set, $uri);
1110 +
1111 +
1047 1112 // Loop through and check for new posts
1048 - $delta = NULL;
1049 - foreach ($feed_set as $feed) :
1050 - if (!is_null($crash_ts) and (time() > $crash_ts)) : // Check whether we've exceeded the time limit
1113 + $delta = NULL; $remaining = $max_polls;
1114 + foreach ($feed_set as $feed_id) :
1115 +
1116 + $feed = $this->subscription($feed_id);
1117 +
1118 + // Has this process overstayed its welcome?
1119 + if (
1120 + // Over time limit?
1121 + (!is_null($crash_ts) and (time() > $crash_ts))
1122 +
1123 + // Over feed count?
1124 + or ($remaining == 0)
1125 + ) :
1051 1126 break;
1052 1127 endif;
1053 1128
1054 1129 $pinged_that = (is_null($uri) or ($uri=='*') or in_array($uri, array($feed->uri(), $feed->homepage())));
@@ -1058,13 +1133,17 @@
1058 1133 else :
1059 1134 $timely = $feed->stale();
1060 1135 endif;
1061 1136
1062 - if ($pinged_that and is_null($delta)) : // If at least one feed was hit for updating...
1063 - $delta = array('new' => 0, 'updated' => 0); // ... don't return error condition
1137 + // If at least one feed was hit for updating...
1138 + if ($pinged_that and is_null($delta)) :
1139 + // ... don't return error condition
1140 + $delta = array('new' => 0, 'updated' => 0, 'stored' => 0);
1064 1141 endif;
1065 1142
1066 1143 if ($pinged_that and $timely) :
1144 + $remaining = $remaining - 1;
1145 +
1067 1146 do_action('feedwordpress_check_feed', $feed->settings);
1068 1147 $start_ts = time();
1069 1148 $added = $feed->poll($crash_ts);
1070 1149 do_action('feedwordpress_check_feed_complete', $feed->settings, $added, time() - $start_ts);
@@ -1069,31 +1148,101 @@
1069 1148 $added = $feed->poll($crash_ts);
1070 1149 do_action('feedwordpress_check_feed_complete', $feed->settings, $added, time() - $start_ts);
1071 1150
1072 1151 if (is_array($added)) : // Success
1073 - if (isset($added['new'])) : $delta['new'] += $added['new']; endif;
1074 - if (isset($added['updated'])) : $delta['updated'] += $added['updated']; endif;
1152 + foreach ($added as $key => $count) :
1153 + $delta[$key] += $added[$key];
1154 + endforeach;
1075 1155 endif;
1076 1156 endif;
1077 1157 endforeach;
1078 1158
1079 1159 do_action('feedwordpress_update_complete', $delta);
1160 + return $delta;
1161 + } /* FeedWordPress::update () */
1080 1162
1081 - return $delta;
1082 - }
1163 + public function crash_ts ($default = NULL) {
1164 + $crash_dt = (int) get_option('feedwordpress_update_time_limit', 0);
1165 + if ($crash_dt > 0) :
1166 + $crash_ts = time() + $crash_dt;
1167 + else :
1168 + $crash_ts = $default;
1169 + endif;
1170 + return $crash_ts;
1171 + } /* FeedWordPress::crash_ts () */
1083 1172
1084 - function stale () {
1085 - if (get_option('feedwordpress_automatic_updates')) :
1173 + public function secret_key () {
1174 + $secret = get_option('feedwordpress_secret_key', false);
1175 + if (!$secret) : // Generate random key.
1176 + $secret = substr(md5(uniqid(microtime())), 0, 6);
1177 + update_option('feedwordpress_secret_key', $secret);
1178 + endif;
1179 + return $secret;
1180 + } /* FeedWordPress::secret_key () */
1181 +
1182 + public function has_secret () {
1183 + return (MyPHP::request('feedwordpress_key')==$this->secret_key());
1184 + } /* FeedWordPress::has_secret () */
1185 +
1186 + var $update_hooked = NULL;
1187 + public function automatic_update_hook ($params = array()) {
1188 + $params = wp_parse_args($params, array( // Defaults
1189 + 'setting only' => false,
1190 + ));
1191 + $hook = get_option('feedwordpress_automatic_updates', NULL);
1192 + $method = 'FeedWordPress option';
1193 +
1194 + // Allow for forced behavior in testing.
1195 + if (
1196 + !$params['setting only']
1197 + and $this->has_secret()
1198 + and MyPHP::request('automatic_update')
1199 + ) :
1200 + $hook = MyPHP::request('automatic_update');
1201 + $method = 'URL parameter';
1202 + endif;
1203 +
1204 + $exact = $hook; // Before munging
1205 +
1206 + if (!!$hook) :
1207 + if ($hook != 'init') : // Constrain values.
1208 + $hook = 'shutdown';
1209 + endif;
1210 + endif;
1211 +
1212 + if ($hook) :
1213 + $this->update_hooked = "Initiating an AUTOMATIC CHECK FOR UPDATES ON PAGE LOAD ".$hook." due to ".$method." = ".trim($this->val($exact));
1214 + endif;
1215 +
1216 + return $hook;
1217 + } /* FeedWordPress::automatic_update_hook () */
1218 +
1219 + public function last_update_all () {
1220 + $last = get_option('feedwordpress_last_update_all');
1221 + if ($this->has_secret() and MyPHP::request('automatic_update')) :
1222 + $last = 1; // A long, long time ago.
1223 + elseif ($this->has_secret() and MyPHP::request('last_update_all')) :
1224 + $last = MyPHP::request('last_update_all');
1225 + endif;
1226 + return $last;
1227 + } /* FeedWordPress::last_update_all () */
1228 +
1229 + public function force_update_all () {
1230 + return ($this->has_secret() and MyPHP::request('force_update_feeds'));
1231 + } /* FeedWordPress::force_update_all () */
1232 +
1233 + public function stale () {
1234 + if (!is_null($this->automatic_update_hook())) :
1086 1235 // Do our best to avoid possible simultaneous
1087 1236 // updates by getting up-to-the-minute settings.
1088 -
1089 - $last = get_option('feedwordpress_last_update_all');
1090 -
1237 +
1238 + $last = $this->last_update_all();
1239 +
1091 1240 // If we haven't updated all yet, give it a time window
1092 1241 if (false === $last) :
1093 1242 $ret = false;
1094 1243 update_option('feedwordpress_last_update_all', time());
1095 -
1244 +
1096 1245 // Otherwise, check against freshness interval
1097 1246 elseif (is_numeric($last)) : // Expect a timestamp
1098 1247 $freshness = get_option('feedwordpress_freshness');
1099 1248 if (false === $freshness) : // Use default
@@ -1098,13 +1247,13 @@
1098 1247 $freshness = get_option('feedwordpress_freshness');
1099 1248 if (false === $freshness) : // Use default
1100 1249 $freshness = FEEDWORDPRESS_FRESHNESS_INTERVAL;
1101 1250 endif;
1102 - $ret = ( (time() - $last) > $freshness);
1251 + $ret = ( (time() - $last) > $freshness );
1103 1252
1104 - // This should never happen.
1253 + // This should never happen.
1105 1254 else :
1106 - FeedWordPress::critical_bug('FeedWordPress::stale::last', $last, __LINE__);
1255 + FeedWordPress::critical_bug('FeedWordPress::stale::last', $last, __LINE__, __FILE__);
1107 1256 endif;
1108 1257
1109 1258 else :
1110 1259 $ret = false;
@@ -1109,72 +1258,653 @@
1109 1258 else :
1110 1259 $ret = false;
1111 1260 endif;
1112 1261 return $ret;
1113 - } // FeedWordPress::stale()
1262 + } /* FeedWordPress::stale() */
1263 +
1264 + static function admin_init () {
1265 + // WordPress 3.5+ compat: the WP devs are in the midst of removing Links from the WordPress core. Eventually we'll have to deal
1266 + // with the possible disappearance of the wp_links table as a whole; but in the meantime, we just need to turn on the interface
1267 + // element to avoid problems with user capabilities that presume the presence of the Links Manager in the admin UI.
1268 + if (!intval(get_option('link_manager_enabled', false))) :
1269 + update_option('link_manager_enabled', true);
1270 + endif;
1271 +
1272 + if (defined('FEEDWORDPRESS_PREPARE_TO_ZAP') and FEEDWORDPRESS_PREPARE_TO_ZAP) :
1273 + $post_id = FEEDWORDPRESS_PREPARE_TO_ZAP;
1274 + $sendback = wp_get_referer();
1275 + if (
1276 + ! $sendback
1277 + or strpos( $sendback, 'post.php' ) !== false
1278 + or strpos( $sendback, 'post-new.php' ) !== false
1279 + ) :
1280 + if ( 'attachment' == $post_type ) :
1281 + $sendback = admin_url( 'upload.php' );
1282 + else :
1283 + $sendback = admin_url( 'edit.php' );
1284 + $sendback .= ( ! empty( $post_type ) ) ? '?post_type=' . $post_type : '';
1285 + endif;
1286 + else :
1287 + $sendback = remove_query_arg( array('trashed', 'untrashed', 'deleted', 'zapped', 'unzapped', 'ids'), $sendback );
1288 + endif;
1289 +
1290 + // Make sure we have a post corresponding to this ID.
1291 + $post = $post_type = $post_type_object = null;
1292 + if ( $post_id ) :
1293 + $post = get_post( $post_id );
1294 + endif;
1295 +
1296 + if ( $post ) :
1297 + $post_type = $post->post_type;
1298 + endif;
1299 + $p = get_post($post_id);
1300 +
1301 + if ( ! $post ) :
1302 + wp_die( __( 'The item you are trying to zap no longer exists.' ) );
1303 + endif;
1304 +
1305 + if ( ! current_user_can( 'delete_post', $post_id ) ) :
1306 + wp_die( __( 'You are not allowed to zap this item.' ) );
1307 + endif;
1308 +
1309 + if ( $user_id = wp_check_post_lock( $post_id ) ) :
1310 + $user = get_userdata( $user_id );
1311 + wp_die( sprintf( __( 'You cannot retire this item. %s is currently editing.' ), $user->display_name ) );
1312 + endif;
1313 +
1314 + if (MyPHP::request('fwp_post_delete')=='zap') :
1315 + FeedWordPress::diagnostic('syndicated_posts', 'Zapping existing post # '.$p->ID.' "'.$p->post_title.'" due to user request.');
1316 +
1317 + $old_status = $post->post_status;
1318 +
1319 + set_post_field('post_status', 'fwpzapped', $post_id);
1320 + wp_transition_post_status('fwpzapped', $old_status, $post);
1321 +
1322 + # Set up the post to have its content blanked on
1323 + # next update if you do not undo the zapping.
1324 + add_post_meta($post_id, '_feedwordpress_zapped_blank_me', 1, /*unique=*/ true);
1325 + add_post_meta($post_id, '_feedwordpress_zapped_blank_old_status', $old_status, /*unique=*/ true);
1326 +
1327 + wp_redirect( add_query_arg( array('zapped' => 1, 'ids' => $post_id), $sendback ) );
1328 +
1329 + else :
1330 + $old_status = get_post_meta($post_id, '_feedwordpress_zapped_blank_old_status', /*single=*/ true);
1331 +
1332 + set_post_field('post_status', $old_status, $post_id);
1333 + wp_transition_post_status($old_status, 'fwpzapped', $post);
1334 +
1335 + # O.K., make sure this post does not get blanked
1336 + delete_post_meta($post_id, '_feedwordpress_zapped_blank_me');
1337 + delete_post_meta($post_id, '_feedwordpress_zapped_blank_old_status');
1338 +
1339 + wp_redirect( add_query_arg( array('unzapped' => 1, 'ids' => $post_id), $sendback ) );
1340 +
1341 + endif;
1342 +
1343 + // Intercept, don't pass on.
1344 + exit;
1345 + endif;
1346 + } /* FeedWordPress::admin_init() */
1347 +
1348 + public function admin_api () {
1349 + // This sucks, but WordPress doesn't give us any other way to
1350 + // easily invoke a permanent-delete from a plugged in post
1351 + // actions link. So we create a magic parameter, and when this
1352 + // magic parameter is activated, the WordPress trashcan is
1353 + // temporarily de-activated.
1354 +
1355 + if (MyPHP::request('fwp_post_delete')=='nuke') :
1356 + // Get post ID #
1357 + $post_id = MyPHP::request('post');
1358 + if (!$post_id) :
1359 + $post_id = MyPHP::request('post_ID');
1360 + endif;
1361 +
1362 + // Make sure we've got the right nonce and all that.
1363 + check_admin_referer('delete-post_' . $post_id);
1364 +
1365 + // If so, disable the trashcan.
1366 + define('EMPTY_TRASH_DAYS', 0);
1367 +
1368 + elseif (MyPHP::request('fwp_post_delete')=='zap' OR MyPHP::request('fwp_post_delete') == 'unzap') :
1369 + // Get post ID #
1370 + $post_id = MyPHP::request('post');
1371 + if (!$post_id) :
1372 + $post_id = MyPHP::request('post_ID');
1373 + endif;
1374 +
1375 + // Make sure we've got the right nonce and all that
1376 + check_admin_referer('delete-post_' . $post_id);
1377 +
1378 + // If so, get ready to intercept the call a little
1379 + // further down the line.
1380 +
1381 + define('FEEDWORDPRESS_PREPARE_TO_ZAP', $post_id);
1382 +
1383 + endif;
1384 +
1385 + } /* FeedWordPress::admin_api () */
1386 +
1387 + public function all_admin_notices () {
1388 + if (MyPHP::request('zapped')) :
1389 + $n = intval(MyPHP::request('zapped'));
1390 +?>
1391 +<div id="message" class="updated"><p><?php print $n; ?> syndicated item<?php print ($n!=1?'s':''); ?> zapped. <strong>These items will not be re-syndicated.</strong> If this was a mistake, you must <strong>immediately</strong> Un-Zap them in the Zapped items section to avoid losing the data.</p></div>
1392 +<?php
1393 + endif;
1394 +
1395 + if (MyPHP::request('unzapped')) :
1396 + $n = intval(MyPHP::request('unzapped'));
1397 +?>
1398 +<div id="message" class="updated"><p><?php print $n; ?> syndicated item<?php print ($n!=1?'s':'') ?> un-zapped and restored to normal.</p></div>
1399 +<?php
1400 + endif;
1401 + } /* FeedWordPress::all_admin_notices () */
1114 1402
1115 - function update_requested () {
1116 - return (
1117 - isset($_REQUEST['update_feedwordpress'])
1118 - and $_REQUEST['update_feedwordpress']
1403 + public function process_retirements ($delta) {
1404 + update_option('feedwordpress_process_zaps', 1);
1405 +
1406 + return $delta;
1407 + }
1408 +
1409 + public function feedwordpress_cleanup () {
1410 + if (get_option('feedwordpress_process_zaps', null)) :
1411 + $q = new WP_Query(array(
1412 + 'fields' => '_synfrom',
1413 + 'post_status' => 'fwpzapped',
1414 + 'ignore_sticky_posts' => true,
1415 + 'meta_key' => '_feedwordpress_zapped_blank_me',
1416 + 'meta_value' => 1,
1417 + ));
1418 +
1419 + if ($q->have_posts()) :
1420 + foreach ($q->posts as $p) :
1421 +
1422 + $post_id = $p->ID;
1423 + $revisions = wp_get_post_revisions($post_id, array("check_enabled" => false));
1424 +
1425 + # Now nuke the content of the post & its revisions
1426 + set_post_field('post_content', '', $post_id);
1427 + set_post_field('post_excerpt', '', $post_id);
1428 +
1429 + foreach ($revisions as $rev) :
1430 + set_post_field('post_content', '', $rev->ID);
1431 + set_post_field('post_excerpt', '', $rev->ID);
1432 + endforeach;
1433 +
1434 + # Un-tag it for blanking.
1435 + delete_post_meta($p->ID, '_feedwordpress_zapped_blank_me');
1436 +
1437 + # Don't remove old_status indicator. A later
1438 + # update from the feed may cause us to once
1439 + # again have some content so we can un-zap.
1440 +
1441 + endforeach;
1442 + endif;
1443 +
1444 + $q = new WP_Query(array(
1445 + 'fields' => '_synfrom',
1446 + 'post_status' => 'fwpzapped',
1447 + 'ignore_sticky_posts' => true,
1448 + 'meta_key' => '_feedwordpress_zapped_blank_me',
1449 + 'meta_value' => 2,
1450 + ));
1451 +
1452 + if ($q->have_posts()) :
1453 + foreach ($q->posts as $p) :
1454 + update_post_meta($p->ID, '_feedwordpress_zapped_blank_me', 1);
1455 + endforeach;
1456 + endif;
1457 +
1458 + update_option('feedwordpress_process_zaps', 0);
1459 + endif;
1460 + } /* FeedWordPress::feedwordpress_cleanup () */
1461 +
1462 + public function init () {
1463 + global $fwp_path;
1464 +
1465 + // If this is a FeedWordPress admin page, queue up scripts for AJAX
1466 + // functions that FWP uses. If it is a display page or a non-FWP admin
1467 + // page, don't.
1468 + wp_register_style('feedwordpress-elements', WP_PLUGIN_URL.'/'.$fwp_path.'/feedwordpress-elements.css');
1469 + if (FeedWordPressSettingsUI::is_admin()) :
1470 + // For JavaScript that needs to be generated dynamically
1471 + add_action('admin_print_scripts', array('FeedWordPressSettingsUI', 'admin_scripts'));
1472 +
1473 + // For CSS that needs to be generated dynamically.
1474 + add_action('admin_print_styles', array('FeedWordPressSettingsUI', 'admin_styles'));
1475 +
1476 + wp_enqueue_style('dashboard');
1477 + wp_enqueue_style('feedwordpress-elements');
1478 +
1479 + /*if (function_exists('wp_admin_css')) :
1480 + wp_admin_css('css/dashboard');
1481 + endif;*/
1482 + endif;
1483 +
1484 + // These are a special post statuses for hiding posts that have
1485 + // expired from the feed or been marked for permanent zapping by
1486 + // the FWP admin.
1487 + register_post_status('fwpretired', array(
1488 + 'label' => _x('Retired', 'post'),
1489 + 'label_count' => _n_noop('Retired <span class="count">(%s)</span>', 'Retired <span class="count">(%s)</span>'),
1490 + 'exclude_from_search' => true,
1491 + 'public' => false,
1492 + 'publicly_queryable' => false,
1493 + 'show_in_admin_all_list' => false,
1494 + 'show_in_admin_status_list' => true,
1495 + ));
1496 + register_post_status('fwpzapped', array(
1497 + 'label' => _x('Zapped', 'post'),
1498 + 'label_count' => _n_noop('Zapped <span class="count">(%s)</span>', 'Retired <span class="count">(%s)</span>'),
1499 + 'exclude_from_search' => true,
1500 + 'public' => false,
1501 + 'publicly_queryable' => false,
1502 + 'show_in_admin_all_list' => false,
1503 + 'show_in_admin_status_list' => true,
1504 + ));
1505 + add_action(
1506 + /*hook=*/ 'template_redirect',
1507 + /*function=*/ array($this, 'redirect_retired'),
1508 + /*priority=*/ -100
1119 1509 );
1120 - } // FeedWordPress::update_requested()
1121 1510
1122 - function update_requested_url () {
1123 - $ret = null;
1511 + add_action('wp_ajax_fwp_feeds', array($this, 'fwp_feeds'));
1512 + add_action('wp_ajax_fwp_feedcontents', array($this, 'fwp_feedcontents'));
1513 + add_action('wp_ajax_fwp_xpathtest', array($this, 'fwp_xpathtest'));
1514 +
1515 + $this->clear_cache_magic_url();
1516 + $this->update_magic_url();
1517 + } /* FeedWordPress::init() */
1518 +
1519 + public function fwp_feeds () {
1520 + $feeds = array();
1521 + $feed_ids = $this->feeds;
1522 +
1523 + foreach ($feed_ids as $id) :
1524 + $sub = $this->subscription($id);
1525 + $feeds[] = array(
1526 + "id" => $id,
1527 + "url" => $sub->uri(),
1528 + "name" => $sub->name(/*fromFeed=*/ false),
1529 + );
1530 + endforeach;
1531 +
1532 + header("Content-Type: application/json");
1533 + echo json_encode($feeds);
1534 + exit;
1535 + } /* FeedWordPress::fwp_feeds () */
1536 +
1537 + public function fwp_feedcontents () {
1538 + $feed_id = MyPHP::request('feed_id');
1539 +
1540 + // Let's load up some data from the feed . . .
1541 + $feed = $this->subscription($feed_id);
1542 + $posts = $feed->live_posts();
1543 +
1544 + if (is_wp_error($posts)) :
1545 + header("HTTP/1.1 502 Bad Gateway");
1546 + $result = $posts;
1547 + else :
1548 + $result = array();
1549 +
1550 + foreach ($posts as $post) :
1551 + $p = new SyndicatedPost($post, $feed);
1552 +
1553 + $result[] = array(
1554 + "post_title" => $p->entry->get_title(),
1555 + "post_link" => $p->permalink(),
1556 + "guid" => $p->guid(),
1557 + "post_date" => $p->published(),
1558 + );
1559 + endforeach;
1560 + endif;
1561 +
1562 + header("Content-Type: application/json");
1563 +
1564 + echo json_encode($result);
1565 +
1566 + // This is an AJAX request, so close it out thus.
1567 + die;
1568 + } /* FeedWordPress::fwp_feedcontents () */
1569 +
1570 + public function fwp_xpathtest () {
1571 + $xpath = MyPHP::request('xpath');
1572 + $feed_id = MyPHP::request('feed_id');
1573 + $post_id = MyPHP::request('post_id');
1574 +
1575 + $expr = new FeedWordPressParsedPostMeta($xpath);
1576 +
1577 + // Let's load up some data from the feed . . .
1578 + $feed = $this->subscription($feed_id);
1579 + $posts = $feed->live_posts();
1580 +
1581 + if (!is_wp_error($posts)) :
1582 + if (strlen($post_id) == 0) :
1583 + $post = $posts[0];
1584 + else :
1585 + $post = null;
1586 +
1587 + foreach ($posts as $p) :
1588 + if ($p->get_id() == $post_id) :
1589 + $post = $p;
1590 + endif;
1591 + endforeach;
1592 + endif;
1593 +
1594 + $post = new SyndicatedPost($post, $feed);
1595 + $meta = $expr->do_substitutions($post);
1596 +
1597 + $result = array(
1598 + "post_title" => $post->entry->get_title(),
1599 + "post_link" => $post->permalink(),
1600 + "guid" => $post->guid(),
1601 + "expression" => $xpath,
1602 + "results" => $meta
1603 + );
1604 + else :
1605 + $result = array(
1606 + "expression" => $xpath,
1607 + "feed_id" => $feed_id,
1608 + "post_id" => $post_id,
1609 + "results" => $posts
1610 + );
1611 +
1612 + header("HTTP/1.1 503 Bad Gateway");
1613 + endif;
1614 +
1615 + header("Content-Type: application/json");
1616 +
1617 + echo json_encode($result);
1618 +
1619 + // This is an AJAX request, so close it out thus.
1620 + die;
1621 + } /* FeedWordPress::fwp_xpathtest () */
1622 +
1623 + public function redirect_retired () {
1624 + global $wp_query;
1625 + if (is_singular()) :
1626 + if (
1627 + 'fwpretired'==$wp_query->post->post_status
1628 + or 'fwpzapped'==$wp_query->post->post_status
1629 + ) :
1630 + do_action('feedwordpress_redirect_retired', $wp_query->post);
1631 +
1632 + if (!($template = get_404_template())) :
1633 + $template = get_index_template();
1634 + endif;
1635 + if ($template = apply_filters('template_include', $template)) :
1636 + header("HTTP/1.1 410 Gone");
1637 + include($template);
1638 + endif;
1639 + exit;
1640 + endif;
1641 + endif;
1642 + } /* FeedWordPress::redirect_retired () */
1643 +
1644 + public function row_actions ($actions, $post) {
1645 + if (is_syndicated($post->ID)) :
1646 + $link = get_delete_post_link($post->ID, '', true);
1647 + $eraseLink = MyPHP::url($link, array("fwp_post_delete" => "nuke"));
1648 +
1649 + $caption = apply_filters('feedwordpress_ui_erase_link_caption', __('Erase the record of this post (will be re-syndicated if it still appears on the feed).'));
1650 + $linktext = apply_filters('feedwordpress_ui_erase_link_text', __('Erase/Resyndicate'));
1124 1651
1125 - if (($_REQUEST['update_feedwordpress']=='*')
1126 - or (preg_match('|^http://.*|i', $_REQUEST['update_feedwordpress']))) :
1127 - $ret = $_REQUEST['update_feedwordpress'];
1652 + $retireClass = NULL;
1653 + if ($post->post_status == 'fwpzapped') :
1654 + if (count(get_post_meta($post->ID, '_feedwordpress_zapped_blank_me')) > 0) :
1655 + $retireCap = 'Un-Zap this syndicated post (so it will appear on the site again)';
1656 + $retireText = 'Un-Zap &amp; Restore';
1657 + $retireLink = MyPHP::url($link, array("fwp_post_delete" => "unzap"));
1658 + else :
1659 + // No Un-Zap link for posts that have
1660 + // been blanked. You'll just have to
1661 + // Erase and hope you can resyndicate...
1662 + $retireLink = NULL;
1663 + endif;
1664 + else :
1665 + $retireCap = apply_filters('feedwordpress_ui_zap_link_caption', __('Zap this syndicated post (so it will not be re-syndicated if it still appears on the feed).'));
1666 + $retireText = apply_filters('feedwordpress_ui_zap_link_text', __('Zap/Don&#8217;t Resyndicate'));
1667 + $retireLink = MyPHP::url($link, array("fwp_post_delete" => "zap"));
1668 + $retireClass = 'submitdelete';
1128 1669 endif;
1670 +
1671 + $keys = array_keys($actions);
1672 + $links = array();
1673 + foreach ($keys as $key) :
1674 + $links[$key] = $actions[$key];
1129 1675
1130 - return $ret;
1131 - } // FeedWordPress::update_requested_url()
1676 + if ('trash'==$key) :
1677 + #$links[$key] = "<a class='submitdelete' title='" . esc_attr( __( 'Move this item to the Trash (will NOT be re-syndicated)' ) ) . "' href='" . get_delete_post_link( $post->ID ) . "'>" . __( 'Trash' ) . "</a>";
1132 1678
1133 - function syndicate_link ($name, $uri, $rss) {
1679 + // Placeholder.
1680 + if (!is_null($retireLink)) :
1681 + $links['zap trash'] = '';
1682 + endif;
1683 + $links['delete'] = '';
1684 + endif;
1685 + endforeach;
1686 +
1687 + if (!is_null($retireLink)) :
1688 + $links['zap trash'] = '<a class="'.esc_attr($retireClass).'" title="'.esc_attr(__($retireCap)).'" href="' . $retireLink . '">' . __($retireText) . '</a>';
1689 + endif;
1690 + $links['delete'] = '<a class="submitdelete" title="'.esc_attr(__($caption)).'" href="' . $eraseLink . '">' . __($linktext) . '</a>';
1691 +
1692 + $actions = $links;
1693 + endif;
1694 + return $actions;
1695 + } /* FeedWordPress::row_actions () */
1696 +
1697 + public function dashboard_setup () {
1698 + $see_it = FeedWordPress::menu_cap();
1699 +
1700 + if (current_user_can($see_it)) :
1701 + // Get the stylesheet
1702 + wp_enqueue_style('feedwordpress-elements');
1703 +
1704 + $widget_id = 'feedwordpress_dashboard';
1705 + $widget_name = __('Syndicated Sources');
1706 + $column = 'side';
1707 + $priority = 'core';
1708 +
1709 + // I would love to use wp_add_dashboard_widget() here and save
1710 + // myself some trouble. But WP 3 does not yet have any way to
1711 + // push a dashboard widget onto the side, or to give it a default
1712 + // location.
1713 + add_meta_box(
1714 + /*id=*/ $widget_id,
1715 + /*title=*/ $widget_name,
1716 + /*callback=*/ array($this, 'dashboard'),
1717 + /*page=*/ 'dashboard',
1718 + /*context=*/ $column,
1719 + /*priority=*/ $priority
1720 + );
1721 + /*control_callback= array($this, 'dashboard_control') */
1722 +
1723 + // This is kind of rude, I know, but the dashboard widget isn't
1724 + // worth much if users don't know that it exists, and I don't
1725 + // know of any better way to reorder the boxen.
1726 + //
1727 + // Gleefully ripped off of codex.wordpress.org/Dashboard_Widgets_API
1728 +
1729 + // Globalize the metaboxes array, this holds all the widgets for wp-admin
1730 + global $wp_meta_boxes;
1731 +
1732 + // Get the regular dashboard widgets array
1733 + // (which has our new widget already but at the end)
1734 +
1735 + $normal_dashboard = $wp_meta_boxes['dashboard'][$column][$priority];
1736 +
1737 + // Backup and delete our new dashbaord widget from the end of the array
1738 + if (isset($normal_dashboard[$widget_id])) :
1739 + $backup = array();
1740 + $backup[$widget_id] = $normal_dashboard[$widget_id];
1741 + unset($normal_dashboard[$widget_id]);
1742 +
1743 + // Merge the two arrays together so our widget is at the
1744 + // beginning
1745 + $sorted_dashboard = array_merge($backup, $normal_dashboard);
1746 +
1747 + // Save the sorted array back into the original metaboxes
1748 + $wp_meta_boxes['dashboard'][$column][$priority] = $sorted_dashboard;
1749 + endif;
1750 + endif;
1751 + } /* FeedWordPress::dashboard_setup () */
1752 +
1753 + public function dashboard () {
1754 + $syndicationPage = new FeedWordPressSyndicationPage(dirname(__FILE__).'/syndication.php');
1755 + $syndicationPage->dashboard_box($syndicationPage);
1756 + } /* FeedWordPress::dashboard () */
1757 +
1758 + public function user_can_richedit ($rich_edit) {
1759 +
1760 + $post = new FeedWordPressLocalPost;
1761 +
1762 + if (!$post->is_exposed_to_formatting_filters()) :
1763 + // Disable visual editor and only allow operations
1764 + // directly on HTML if post is bypassing fmt filters
1765 + # $rich_edit = false;
1766 + endif;
1767 +
1768 + return $rich_edit;
1769 +
1770 + } /* FeedWordPress::user_can_richedit () */
1771 +
1772 + public function update_magic_url () {
1134 1773 global $wpdb;
1135 1774
1775 + // Explicit update request in the HTTP request (e.g. from a cron job)
1776 + if ($this->update_requested()) :
1777 + $this->update_hooked = "Initiating a CRON JOB CHECK-IN ON UPDATE SCHEDULE due to URL parameter = ".trim($this->val($_REQUEST['update_feedwordpress']));
1778 +
1779 + $this->update($this->update_requested_url());
1780 +
1781 + if (FEEDWORDPRESS_DEBUG and count($wpdb->queries) > 0) :
1782 + $mysqlTime = 0.0;
1783 + $byTime = array();
1784 + foreach ($wpdb->queries as $query) :
1785 + $time = $query[1] * 1000000.0;
1786 + $mysqlTime += $query[1];
1787 + if (!isset($byTime[$time])) : $byTime[$time] = array(); endif;
1788 + $byTime[$time][] = $query[0]. ' // STACK: ' . $query[2];
1789 + endforeach;
1790 + krsort($byTime);
1791 +
1792 + foreach ($byTime as $time => $querySet) :
1793 + foreach ($querySet as $query) :
1794 + print "[".(sprintf('%4.4f', $time/1000.0)) . "ms] $query\n";
1795 + endforeach;
1796 + endforeach;
1797 + echo self::log_prefix()."$wpdb->num_queries queries. $mysqlTime seconds in MySQL. Total of "; timer_stop(1); print " seconds.";
1798 + endif;
1799 +
1800 + debug_out_feedwordpress_footer();
1801 +
1802 + // Magic URL should return nothing but a 200 OK header packet
1803 + // when successful.
1804 + exit;
1805 + endif;
1806 + } /* FeedWordPress::magic_update_url () */
1807 +
1808 + public function clear_cache_magic_url () {
1809 + if ($this->clear_cache_requested()) :
1810 + $this->clear_cache();
1811 + endif;
1812 + } /* FeedWordPress::clear_cache_magic_url() */
1813 +
1814 + public function clear_cache_requested () {
1815 + return MyPHP::request('clear_cache');
1816 + } /* FeedWordPress::clear_cache_requested() */
1817 +
1818 + public function update_requested () {
1819 + return MyPHP::request('update_feedwordpress');
1820 + } /* FeedWordPress::update_requested() */
1821 +
1822 + public function update_requested_url () {
1823 + $ret = null;
1824 +
1825 + if (($_REQUEST['update_feedwordpress']=='*')
1826 + or (preg_match('|^http://.*|i', $_REQUEST['update_feedwordpress']))) :
1827 + $ret = $_REQUEST['update_feedwordpress'];
1828 + endif;
1829 +
1830 + return $ret;
1831 + } /* FeedWordPress::update_requested_url() */
1832 +
1833 + public function auto_update () {
1834 + if ($this->stale()) :
1835 + $this->update();
1836 + endif;
1837 + } /* FeedWordPress::auto_update () */
1838 +
1839 + public static function find_link ($uri, $field = 'link_rss') {
1840 + global $wpdb;
1841 +
1842 + $unslashed = untrailingslashit($uri);
1843 + $slashed = trailingslashit($uri);
1844 + $link_id = $wpdb->get_var($wpdb->prepare("
1845 + SELECT link_id FROM $wpdb->links WHERE $field IN ('%s', '%s')
1846 + LIMIT 1", $unslashed, $slashed
1847 + ));
1848 +
1849 + return $link_id;
1850 + } /* FeedWordPress::find_link () */
1851 +
1852 + /**
1853 + * FeedWordPress:syndicate_link(): add or update a feed subscription
1854 + *
1855 + * Add a new subscription to, or update an existing subscription in,
1856 + * FWP's list of subscribed feeds.
1857 + *
1858 + * Postcondition: If $rss is the URL of a feed not yet on FWP's list of
1859 + * subscribed feeds, then a new subscription will be added, using $name
1860 + * as its initial title and $uri as its initial homepage URL (normally
1861 + * these will be updated with new values taken from the feed, the first
1862 + * time the new feed is checked for syndicated content, unless feed
1863 + * settings prevent this). If $rss is the URL of a feed that is already
1864 + * on FWP's list of subscribed feeds, then that feed will be updated to
1865 + * use the title provided in $name and the homepage URL in $uri
1866 + *
1867 + * @param string $name The human-readable title of the feed (for example, "Rad Geek People's Daily")
1868 + * @param string $uri The URI for the human-readable homepage associated with the feed (for example, <http://radgeek.com/>)
1869 + * @param string $rss The URI for the feed itself (for example, <http://radgeek.com/feed/>)
1870 + *
1871 + * @return mixed Returns an int with the numeric ID of the new
1872 + * subscription's wp_links record if successful or a WP_Error object
1873 + * if wp_insert_link() failed.
1874 + *
1875 + * @uses FeedWordPress::link_category_id()
1876 + * @uses FeedWordPress::find_link()
1877 + * @uses is_wp_error()
1878 + * @uses wp_insert_link()
1879 + *
1880 + */
1881 + public static function syndicate_link ($name, $uri, $rss) {
1136 1882 // Get the category ID#
1137 1883 $cat_id = FeedWordPress::link_category_id();
1138 -
1884 + if (!is_wp_error($cat_id)) :
1885 + $link_category = array($cat_id);
1886 + else :
1887 + $link_category = array();
1888 + endif;
1889 +
1139 1890 // WordPress gets cranky if there's no homepage URI
1140 - if (!isset($uri) or strlen($uri)<1) : $uri = $rss; endif;
1141 -
1142 - if (function_exists('wp_insert_link')) : // WordPress 2.x
1143 - if (FeedWordPressCompatibility::test_version(0, FWP_SCHEMA_21)) :
1144 - // Morons.
1145 - $name = $wpdb->escape($name);
1146 - $uri = $wpdb->escape($uri);
1147 - $rss = $wpdb->escape($rss);
1148 -
1149 - // Comes in as a single category
1150 - $linkCats = $cat_id;
1151 - else :
1152 - // Comes in as an array of categories
1153 - $linkCats = array($cat_id);
1154 - endif;
1891 + if (!is_string($uri) or strlen($uri)<1) : $uri = $rss; endif;
1155 1892
1156 - $link_id = wp_insert_link(array(
1157 - "link_name" => $name,
1158 - "link_url" => $uri,
1159 - "link_category" => $linkCats,
1160 - "link_rss" => $rss
1161 - ));
1162 - else : // WordPress 1.5.x
1163 - $result = $wpdb->query("
1164 - INSERT INTO $wpdb->links
1165 - SET
1166 - link_name = '".$wpdb->escape($name)."',
1167 - link_url = '".$wpdb->escape($uri)."',
1168 - link_category = '".$wpdb->escape($cat_id)."',
1169 - link_rss = '".$wpdb->escape($rss)."'
1170 - ");
1171 - $link_id = $wpdb->insert_id;
1172 - endif;
1893 + // Check if this feed URL is already being syndicated.
1894 + $link_id = wp_insert_link(/*linkdata=*/ array(
1895 + "link_id" => FeedWordPress::find_link($rss), // insert if nothing was found; else update
1896 + "link_rss" => $rss,
1897 + "link_name" => $name,
1898 + "link_url" => $uri,
1899 + "link_category" => $link_category,
1900 + "link_visible" => 'Y', // reactivate if inactivated
1901 + ), /*wp_error=*/ true);
1902 +
1173 1903 return $link_id;
1174 - } // function FeedWordPress::syndicate_link()
1904 + } /* function FeedWordPress::syndicate_link() */
1175 1905
1176 - /*static*/ function syndicated_status ($what, $default) {
1906 + static function syndicated_status ($what, $default) {
1177 1907 $ret = get_option("feedwordpress_syndicated_{$what}_status");
1178 1908 if (!$ret) :
1179 1909 $ret = $default;
1180 1910 endif;
@@ -1180,31 +1910,19 @@
1180 1910 endif;
1181 1911 return $ret;
1182 1912 } /* FeedWordPress::syndicated_status() */
1183 1913
1184 - function on_unfamiliar ($what = 'author', $override = NULL) {
1185 - $set = array(
1186 - 'author' => array('create', 'default', 'filter'),
1187 - 'category' => array('create', 'tag', 'default', 'filter'),
1188 - );
1189 -
1190 - if (is_string($override)) :
1191 - $ret = strtolower($override);
1192 - else :
1193 - $ret = NULL;
1194 - endif;
1914 + public static function on_unfamiliar ($what = 'author') {
1915 + switch ($what) :
1916 + case 'category' : $suffix = ':category'; break;
1917 + case 'post_tag' : $suffix = ':post_tag'; break;
1918 + default: $suffix = '';
1919 + endswitch;
1195 1920
1196 - if (!is_numeric($override) and !in_array($ret, $set[$what])) :
1197 - $ret = get_option('feedwordpress_unfamiliar_'.$what);
1198 - if (!is_numeric($ret) and !in_array($ret, $set[$what])) :
1199 - $ret = 'create';
1200 - endif;
1201 - endif;
1202 -
1203 - return $ret;
1921 + return get_option('feedwordpress_unfamiliar_'.$what, 'create'.$suffix);
1204 1922 } // function FeedWordPress::on_unfamiliar()
1205 1923
1206 - function null_email_set () {
1924 + public static function null_email_set () {
1207 1925 $base = get_option('feedwordpress_null_email_set');
1208 1926
1209 1927 if ($base===false) :
1210 1928 $ret = array('noreply@blogger.com'); // default
@@ -1216,18 +1934,18 @@
1216 1934 return $ret;
1217 1935
1218 1936 } /* FeedWordPress::null_email_set () */
1219 1937
1220 - function is_null_email ($email) {
1938 + public static function is_null_email ($email) {
1221 1939 $ret = in_array(strtolower(trim($email)), FeedWordPress::null_email_set());
1222 1940 $ret = apply_filters('syndicated_item_author_is_null_email', $ret, $email);
1223 1941 return $ret;
1224 1942 } /* FeedWordPress::is_null_email () */
1225 1943
1226 - function use_aggregator_source_data () {
1944 + public static function use_aggregator_source_data () {
1227 1945 $ret = get_option('feedwordpress_use_aggregator_source_data');
1228 1946 return apply_filters('syndicated_post_use_aggregator_source_data', ($ret=='yes'));
1229 - }
1947 + } /* FeedWordPress::use_aggregator_source_data () */
1230 1948
1231 1949 /**
1232 1950 * FeedWordPress::munge_permalinks: check whether or not FeedWordPress
1233 1951 * should rewrite permalinks for syndicated items to reflect their
@@ -1234,27 +1952,31 @@
1234 1952 * original location.
1235 1953 *
1236 1954 * @return bool TRUE if FeedWordPress SHOULD rewrite permalinks; FALSE otherwise
1237 1955 */
1238 - /*static*/ function munge_permalinks () {
1956 + static function munge_permalinks () {
1239 1957 return (get_option('feedwordpress_munge_permalink', /*default=*/ 'yes') != 'no');
1240 1958 } /* FeedWordPress::munge_permalinks() */
1241 1959
1242 - function syndicated_links () {
1960 + public static function syndicated_links ($args = array()) {
1243 1961 $contributors = FeedWordPress::link_category_id();
1244 - if (function_exists('get_bookmarks')) :
1245 - $links = get_bookmarks(array("category" => $contributors));
1246 - else:
1247 - $links = get_linkobjects($contributors); // deprecated as of WP 2.1
1962 + if (!is_wp_error($contributors)) :
1963 + $links = get_bookmarks(array_merge(
1964 + array("category" => $contributors),
1965 + $args
1966 + ));
1967 + else :
1968 + $links = array();
1248 1969 endif;
1970 +
1249 1971 return $links;
1250 - } // function FeedWordPress::syndicated_links()
1972 + } /* FeedWordPress::syndicated_links() */
1251 1973
1252 - function link_category_id () {
1974 + public static function link_category_id () {
1253 1975 global $wpdb, $wp_db_version;
1254 1976
1255 1977 $cat_id = get_option('feedwordpress_cat_id');
1256 -
1978 +
1257 1979 // If we don't yet have the category ID stored, search by name
1258 1980 if (!$cat_id) :
1259 1981 $cat_id = FeedWordPressCompatibility::link_category_id(DEFAULT_SYNDICATION_CATEGORY);
1260 1982
@@ -1266,60 +1988,87 @@
1266 1988 // If we *do* have the category ID stored, verify that it exists
1267 1989 else :
1268 1990 $cat_id = FeedWordPressCompatibility::link_category_id((int) $cat_id, 'cat_id');
1269 1991 endif;
1270 -
1992 +
1271 1993 // If we could not find an appropriate link category,
1272 1994 // make a new one for ourselves.
1273 1995 if (!$cat_id) :
1274 1996 $cat_id = FeedWordPressCompatibility::insert_link_category(DEFAULT_SYNDICATION_CATEGORY);
1275 -
1276 - // Stamp it
1277 - update_option('feedwordpress_cat_id', $cat_id);
1997 + if (!is_wp_error($cat_id)) :
1998 + // Stamp it
1999 + update_option('feedwordpress_cat_id', $cat_id);
2000 + endif;
1278 2001 endif;
1279 2002
1280 2003 return $cat_id;
1281 - } // function FeedWordPress::link_category_id()
2004 + } /* FeedWordPress::link_category_id() */
1282 2005
1283 2006 # Upgrades and maintenance...
1284 - function needs_upgrade () {
2007 + static function needs_upgrade () {
2008 +
1285 2009 global $wpdb;
1286 - $fwp_db_version = get_option('feedwordpress_version');
2010 + $fwp_db_version = get_option('feedwordpress_version', NULL);
1287 2011 $ret = false; // innocent until proven guilty
1288 - if (!$fwp_db_version or $fwp_db_version < FEEDWORDPRESS_VERSION) :
1289 - // This is an older version or a fresh install. Does it
1290 - // require a database upgrade or database initialization?
1291 - if ($fwp_db_version <= 0.96) :
1292 - // Yes. Check to see whether this is a fresh install or an upgrade.
1293 - $syn = $wpdb->get_col("
1294 - SELECT post_id
1295 - FROM $wpdb->postmeta
1296 - WHERE meta_key = 'syndication_feed'
1297 - ");
1298 - if (count($syn) > 0) : // contains at least one syndicated post
1299 - $ret = true;
1300 - else : // fresh install; brand it as ours
1301 - update_option('feedwordpress_version', FEEDWORDPRESS_VERSION);
2012 + if (is_null($fwp_db_version) or ($fwp_db_version < FEEDWORDPRESS_VERSION)) :
2013 +
2014 + // This is an older version or a fresh install. Does it require a database
2015 + // upgrade or database initialization?
2016 +
2017 + if (is_null($fwp_db_version)) :
2018 +
2019 + // Fresh install; brand it as ours. Or possibly a version of FWP
2020 + // from before 0.96. But I'm no longer supporting upgrade paths
2021 + // for versions from the previous decade. Sorry.
2022 + update_option('feedwordpress_version', FEEDWORDPRESS_VERSION);
2023 +
2024 + elseif ($fwp_db_version < 2010.0814) :
2025 +
2026 + // Change in terminology.
2027 + if (get_option('feedwordpress_unfamiliar_category', 'create')=='default') :
2028 + update_option('feedwordpress_unfamiliar_category', 'null');
1302 2029 endif;
1303 - elseif ($fwp_db_version < 2009.0707) :
1304 - // We need to clear out any busted AJAX crap
1305 - if (fwp_test_wp_version(FWP_SCHEMA_HAS_USERMETA)) :
1306 - $wpdb->query("
1307 - DELETE FROM $wpdb->usermeta
1308 - WHERE LOCATE('feedwordpress', meta_key)
1309 - AND LOCATE('box', meta_key);
1310 - ");
1311 - endif;
2030 + foreach (FeedWordPress::syndicated_links() as $link) :
2031 + $sub = new SyndicatedLink($link);
2032 +
2033 + $remap_uf = array(
2034 + 'default' => 'null',
2035 + 'filter' => 'null',
2036 + 'create' => 'create:category',
2037 + 'tag' => 'create:post_tag'
2038 + );
2039 + if (isset($sub->settings['unfamiliar category'])) :
2040 + if ($sub->settings['unfamiliar category']=='filter') :
2041 + $sub->settings['match/filter'] = array('category');
2042 + endif;
2043 + foreach ($remap_uf as $from => $to) :
2044 + if ($sub->settings['unfamiliar category']==$from) :
2045 + $sub->settings['unfamiliar category'] = $to;
2046 + endif;
2047 + endforeach;
2048 + endif;
2049 +
2050 + if (isset($sub->settings['add global categories'])) :
2051 + $sub->settings['add/category'] = $sub->settings['add global categories'];
2052 + unset($sub->settings['add global categories']);
2053 + endif;
2054 +
2055 + $sub->save_settings(/*reload=*/ true);
2056 + endforeach;
1312 2057 update_option('feedwordpress_version', FEEDWORDPRESS_VERSION);
2058 +
1313 2059 else :
1314 - // No. Just brand it with the new version.
2060 +
2061 + // No upgrade needed. Just brand it with the new version.
1315 2062 update_option('feedwordpress_version', FEEDWORDPRESS_VERSION);
2063 +
1316 2064 endif;
2065 +
1317 2066 endif;
1318 2067 return $ret;
1319 - }
2068 + } /* FeedWordPress::needs_upgrade () */
1320 2069
1321 - function upgrade_database ($from = NULL) {
2070 + static function upgrade_database ($from = NULL) {
1322 2071 global $wpdb;
1323 2072
1324 2073 if (is_null($from) or $from <= 0.96) : $from = 0.96; endif;
1325 2074
@@ -1324,12 +2073,12 @@
1324 2073 if (is_null($from) or $from <= 0.96) : $from = 0.96; endif;
1325 2074
1326 2075 switch ($from) :
1327 2076 case 0.96:
1328 - // Dropping legacy upgrade code. If anyone is still
1329 - // using 0.96 and just now decided to upgrade, well, I'm
1330 - // sorry about that. You'll just have to cope with a few
1331 - // duplicate posts.
2077 + // Dropping legacy upgrade code. If anyone is still
2078 + // using 0.96 and just now decided to upgrade, well, I'm
2079 + // sorry about that. You'll just have to cope with a few
2080 + // duplicate posts.
1332 2081
1333 2082 // Mark the upgrade as successful.
1334 2083 update_option('feedwordpress_version', FEEDWORDPRESS_VERSION);
1335 2084 endswitch;
@@ -1335,11 +2084,11 @@
1335 2084 endswitch;
1336 2085 echo "<p>Upgrade complete. FeedWordPress is now ready to use again.</p>";
1337 2086 } /* FeedWordPress::upgrade_database() */
1338 2087
1339 - function has_guid_index () {
2088 + public static function has_guid_index () {
1340 2089 global $wpdb;
1341 -
2090 +
1342 2091 $found = false; // Guilty until proven innocent.
1343 2092
1344 2093 $results = $wpdb->get_results("
1345 2094 SHOW INDEXES FROM {$wpdb->posts}
@@ -1353,35 +2102,77 @@
1353 2102 endforeach;
1354 2103 endif;
1355 2104 return $found;
1356 2105 } /* FeedWordPress::has_guid_index () */
1357 -
1358 - function create_guid_index () {
2106 +
2107 + public static function create_guid_index () {
1359 2108 global $wpdb;
1360 -
2109 +
1361 2110 $wpdb->query("
1362 2111 CREATE INDEX {$wpdb->posts}_guid_idx ON {$wpdb->posts}(guid)
1363 2112 ");
1364 2113 } /* FeedWordPress::create_guid_index () */
1365 -
1366 - function remove_guid_index () {
2114 +
2115 + public static function remove_guid_index () {
1367 2116 global $wpdb;
1368 -
2117 +
1369 2118 $wpdb->query("
1370 2119 DROP INDEX {$wpdb->posts}_guid_idx ON {$wpdb->posts}
1371 2120 ");
1372 2121 }
1373 2122
1374 - /*static*/ function fetch ($url) {
1375 - require_once (ABSPATH . WPINC . '/class-feed.php');
1376 - $feed = new SimplePie();
2123 + static function fetch_timeout () {
2124 + return apply_filters(
2125 + 'feedwordpress_fetch_timeout',
2126 + intval(get_option('feedwordpress_fetch_timeout', FEEDWORDPRESS_FETCH_TIMEOUT_DEFAULT))
2127 + );
2128 + }
2129 +
2130 + static function fetch ($url, $params = array()) {
2131 + if (is_wp_error($url)) :
2132 + // Let's bounce.
2133 + return $url;
2134 + endif;
2135 +
2136 + $force_feed = true; // Default
2137 +
2138 + // Allow user to change default feed-fetch timeout with a global setting.
2139 + // Props Erigami Scholey-Fuller <http://www.piepalace.ca/blog/2010/11/feedwordpress-broke-my-heart.html>
2140 + $timeout = FeedWordPress::fetch_timeout();
2141 +
2142 + if (!is_array($params)) :
2143 + $force_feed = $params;
2144 + else : // Parameter array
2145 + $args = wp_parse_args(array(
2146 + 'force_feed' => $force_feed,
2147 + 'timeout' => $timeout
2148 + ), $params);
2149 +
2150 + extract($args);
2151 + endif;
2152 + $timeout = intval($timeout);
2153 +
2154 + $pie_class = apply_filters('feedwordpress_simplepie_class', 'FeedWordPie');
2155 + $cache_class = apply_filters('feedwordpress_cache_class', 'WP_Feed_Cache');
2156 + $file_class = apply_filters('feedwordpress_file_class', 'FeedWordPress_File');
2157 + $parser_class = apply_filters('feedwordpress_parser_class', 'FeedWordPress_Parser');
2158 + $item_class = apply_filters('feedwordpress_item_class', 'FeedWordPie_Item');
2159 + $sniffer_class = apply_filters('feedwordpress_sniffer_class', 'FeedWordPress_Content_Type_Sniffer');
2160 +
2161 + $feed = new $pie_class;
1377 2162 $feed->set_feed_url($url);
1378 - $feed->set_cache_class('WP_Feed_Cache');
1379 - $feed->set_file_class('WP_SimplePie_File');
1380 - $feed->set_cache_duration(FeedWordPress::cache_duration());
2163 + $feed->set_cache_class($cache_class);
2164 + $feed->set_timeout($timeout);
2165 +
2166 + $feed->set_content_type_sniffer_class($sniffer_class);
2167 + $feed->set_file_class($file_class);
2168 + $feed->set_parser_class($parser_class);
2169 + $feed->set_item_class($item_class);
2170 + $feed->force_feed($force_feed);
2171 + $feed->set_cache_duration(FeedWordPress::cache_duration($params));
1381 2172 $feed->init();
1382 2173 $feed->handle_content_type();
1383 -
2174 +
1384 2175 if ($feed->error()) :
1385 2176 $ret = new WP_Error('simplepie-error', $feed->error());
1386 2177 else :
1387 2178 $ret = $feed;
@@ -1387,12 +2178,18 @@
1387 2178 $ret = $feed;
1388 2179 endif;
1389 2180 return $ret;
1390 2181 } /* FeedWordPress::fetch () */
1391 -
1392 - function clear_cache () {
2182 +
2183 + public function clear_cache () {
1393 2184 global $wpdb;
1394 -
2185 +
2186 + // Just in case, clear out any old MagpieRSS cache records.
2187 + $magpies = $wpdb->query("
2188 + DELETE FROM {$wpdb->options}
2189 + WHERE option_name LIKE 'rss_%' AND LENGTH(option_name) > 32
2190 + ");
2191 +
1395 2192 // The WordPress SimplePie module stores its cached feeds as
1396 2193 // transient records in the options table. The data itself is
1397 2194 // stored in `_transient_feed_{md5 of url}` and the last-modified
1398 2195 // timestamp in `_transient_feed_mod_{md5 of url}`. Timeouts for
@@ -1398,22 +2195,32 @@
1398 2195 // timestamp in `_transient_feed_mod_{md5 of url}`. Timeouts for
1399 2196 // these records are stored in `_transient_timeout_feed_{md5}`.
1400 2197 // Since the md5 is always 32 characters in length, the
1401 2198 // option_name is always over 32 characters.
1402 - $wpdb->query("
2199 + $simplepies = $wpdb->query("
1403 2200 DELETE FROM {$wpdb->options}
1404 2201 WHERE option_name LIKE '_transient%_feed_%' AND LENGTH(option_name) > 32
1405 2202 ");
2203 + $simplepies = (int) ($simplepies / 4); // Each transient has 4 rows: the data, the modified timestamp; and the timeouts for each
2204 +
2205 + return ($magpies + $simplepies);
1406 2206 } /* FeedWordPress::clear_cache () */
1407 2207
1408 - function cache_duration () {
2208 + static public function cache_duration ($params = array()) {
2209 + $params = wp_parse_args($params, array(
2210 + "cache" => true,
2211 + ));
2212 +
1409 2213 $duration = NULL;
1410 - if (defined('FEEDWORDPRESS_CACHE_AGE')) :
2214 + if (!$params['cache']) :
2215 + $duration = 0;
2216 + elseif (defined('FEEDWORDPRESS_CACHE_AGE')) :
1411 2217 $duration = FEEDWORDPRESS_CACHE_AGE;
1412 2218 endif;
1413 2219 return $duration;
1414 2220 }
1415 - function cache_lifetime ($duration) {
2221 +
2222 + static public function cache_lifetime ($duration) {
1416 2223 // Check for explicit setting of a lifetime duration
1417 2224 if (defined('FEEDWORDPRESS_CACHE_LIFETIME')) :
1418 2225 $duration = FEEDWORDPRESS_CACHE_LIFETIME;
1419 2226
@@ -1420,74 +2227,315 @@
1420 2227 // Fall back to the cache freshness duration
1421 2228 elseif (defined('FEEDWORDPRESS_CACHE_AGE')) :
1422 2229 $duration = FEEDWORDPRESS_CACHE_AGE;
1423 2230 endif;
1424 -
2231 +
1425 2232 // Fall back to WordPress default
1426 2233 return $duration;
1427 2234 } /* FeedWordPress::cache_lifetime () */
1428 2235
1429 2236 # Utility functions for handling text settings
1430 - function negative ($f, $setting) {
2237 + static function negative ($f, $setting) {
1431 2238 $nego = array ('n', 'no', 'f', 'false');
1432 2239 return (isset($f[$setting]) and in_array(strtolower($f[$setting]), $nego));
1433 - }
2240 + } /* FeedWordPress::negative () */
1434 2241
1435 - function affirmative ($f, $setting) {
2242 + static function affirmative ($f, $setting) {
1436 2243 $affirmo = array ('y', 'yes', 't', 'true', 1);
1437 2244 return (isset($f[$setting]) and in_array(strtolower($f[$setting]), $affirmo));
1438 - }
2245 + } /* FeedWordPress::affirmative () */
1439 2246
1440 -
1441 2247 # Internal debugging functions
1442 - function critical_bug ($varname, $var, $line) {
2248 + static function critical_bug ($varname, $var, $line, $file = NULL) {
1443 2249 global $wp_version;
1444 2250
1445 - echo '<p>There may be a bug in FeedWordPress. Please <a href="'.FEEDWORDPRESS_AUTHOR_CONTACT.'">contact the author</a> and paste the following information into your e-mail:</p>';
1446 - echo "\n<plaintext>";
1447 - echo "Triggered at line # ".$line."\n";
1448 - echo "FeedWordPress version: ".FEEDWORDPRESS_VERSION."\n";
1449 - echo "WordPress version: {$wp_version}\n";
1450 - echo "PHP version: ".phpversion()."\n";
1451 - echo "\n";
1452 - echo $varname.": "; var_dump($var); echo "\n";
2251 + if (!is_null($file)) :
2252 + $location = "line # ${line} of ".basename($file);
2253 + else :
2254 + $location = "line # ${line}";
2255 + endif;
2256 +
2257 + print '<p><strong>Critical error:</strong> There may be a bug in FeedWordPress. Please <a href="'.FEEDWORDPRESS_AUTHOR_CONTACT.'">contact the author</a> and paste the following information into your e-mail:</p>';
2258 + print "\n<plaintext>";
2259 + print "Triggered at ${location}\n";
2260 + print "FeedWordPress: ".FEEDWORDPRESS_VERSION."\n";
2261 + print "WordPress: {$wp_version}\n";
2262 + print "PHP: ".phpversion()."\n";
2263 + print "Error data: ";
2264 + print $varname.": "; var_dump($var); echo "\n";
1453 2265 die;
1454 - }
1455 -
1456 - function noncritical_bug ($varname, $var, $line) {
2266 + } /* FeedWordPress::critical_bug () */
2267 +
2268 + static function noncritical_bug ($varname, $var, $line, $file = NULL) {
1457 2269 if (FEEDWORDPRESS_DEBUG) : // halt only when we are doing debugging
1458 - FeedWordPress::critical_bug($varname, $var, $line);
2270 + FeedWordPress::critical_bug($varname, $var, $line, $file);
1459 2271 endif;
1460 - }
1461 -} // class FeedWordPress
2272 + } /* FeedWordPress::noncritical_bug () */
1462 2273
1463 -require_once(dirname(__FILE__) . '/syndicatedpost.class.php');
1464 -require_once(dirname(__FILE__) . '/syndicatedlink.class.php');
2274 + static function val ($v, $no_newlines = false) {
2275 + return MyPHP::val($v, $no_newlines);
2276 + } /* FeedWordPress::val () */
1465 2277
1466 -################################################################################
1467 -## XML-RPC HOOKS: accept XML-RPC update pings from Contributors ################
1468 -################################################################################
2278 + static function diagnostic_on ($level) {
2279 + $show = get_option('feedwordpress_diagnostics_show', array());
2280 + return (in_array($level, $show));
2281 + } /* FeedWordPress::diagnostic_on () */
1469 2282
1470 -function feedwordpress_xmlrpc_hook ($args = array ()) {
1471 - $args['weblogUpdates.ping'] = 'feedwordpress_pong';
1472 - return $args;
1473 -}
2283 + static function diagnostic ($level, $out, $persist = NULL, $since = NULL, $mostRecent = NULL) {
2284 + global $feedwordpress_admin_footer;
1474 2285
1475 -function feedwordpress_pong ($args) {
1476 - $feedwordpress = new FeedWordPress;
1477 - $delta = @$feedwordpress->update($args[1]);
1478 - if (is_null($delta)):
1479 - return array('flerror' => true, 'message' => "Sorry. I don't syndicate <$args[1]>.");
1480 - else:
1481 - $mesg = array();
1482 - if (isset($delta['new'])) { $mesg[] = ' '.$delta['new'].' new posts were syndicated'; }
1483 - if (isset($delta['updated'])) { $mesg[] = ' '.$delta['updated'].' existing posts were updated'; }
2286 + $output = get_option('feedwordpress_diagnostics_output', array());
2287 + $dlog = get_option('feedwordpress_diagnostics_log', array());
1484 2288
1485 - return array('flerror' => false, 'message' => "Thanks for the ping.".implode(' and', $mesg));
1486 - endif;
1487 -}
2289 + $diagnostic_nesting = count(explode(":", $level));
1488 2290
1489 -require_once(dirname(__FILE__) . '/relative_uri.class.php');
2291 + if (FeedWordPress::diagnostic_on($level)) :
2292 + foreach ($output as $method) :
2293 + switch ($method) :
2294 + case 'echo' :
2295 + if (!FeedWordPress::update_requested()) :
2296 + echo "<div><pre><strong>Diag".str_repeat('====', $diagnostic_nesting-1).'|</strong> '.$out."</pre></div>\n";
2297 + endif;
2298 + break;
2299 + case 'echo_in_cronjob' :
2300 + if (FeedWordPress::update_requested()) :
2301 + echo FeedWordPress::log_prefix()." ".$out."\n";
2302 + endif;
2303 + break;
2304 + case 'admin_footer' :
2305 + $feedwordpress_admin_footer[] = $out;
2306 + break;
2307 + case 'error_log' :
2308 + error_log(FeedWordPress::log_prefix().' '.$out);
2309 + break;
2310 + case 'email' :
2311 +
2312 + if (is_null($persist)) :
2313 + $sect = 'occurrent';
2314 + $hook = (isset($dlog['mesg'][$sect]) ? count($dlog['mesg'][$sect]) : 0);
2315 + $line = array("Time" => time(), "Message" => $out);
2316 + else :
2317 + $sect = 'persistent';
2318 + $hook = md5($level."\n".$persist);
2319 + $line = array("Since" => $since, "Message" => $out, "Most Recent" => $mostRecent);
2320 + endif;
2321 +
2322 + if (!isset($dlog['mesg'])) : $dlog['mesg'] = array(); endif;
2323 + if (!isset($dlog['mesg'][$sect])) : $dlog['mesg'][$sect] = array(); endif;
2324 +
2325 + $dlog['mesg'][$sect][$hook] = $line;
2326 + endswitch;
2327 + endforeach;
2328 + endif;
2329 +
2330 + update_option('feedwordpress_diagnostics_log', $dlog);
2331 + } /* FeedWordPress::diagnostic () */
2332 +
2333 + public function email_diagnostics_override () {
2334 + return ($this->has_secret() and isset($_REQUEST['feedwordpress_email_diagnostics']) and !!$_REQUEST['feedwordpress_email_diagnostics']);
2335 + } /* FeedWordPress::email_diagnostics_override () */
2336 +
2337 + public function has_emailed_diagnostics ($dlog) {
2338 + $ret = false;
2339 + if ($this->email_diagnostics_override()
2340 + or (isset($dlog['schedule']) and isset($dlog['schedule']['last']))) :
2341 + $ret = true;
2342 + endif;
2343 + return $ret;
2344 + } /* FeedWordPress::has_emailed_diagnostics () */
2345 +
2346 + public function ready_to_email_diagnostics ($dlog) {
2347 + $ret = false;
2348 + if ($this->email_diagnostics_override()
2349 + or (time() > ($dlog['schedule']['last'] + $dlog['schedule']['freq']))) :
2350 + $ret = true;
2351 + endif;
2352 + return $ret;
2353 + } /* FeedWordPress::ready_to_email_diagnostics () */
2354 +
2355 + public function email_diagnostic_log ($params = array()) {
2356 + $params = wp_parse_args($params, array(
2357 + "force" => false,
2358 + ));
2359 +
2360 + $dlog = get_option('feedwordpress_diagnostics_log', array());
2361 +
2362 + if ($this->has_emailed_diagnostics($dlog)) :
2363 + if ($this->ready_to_email_diagnostics($dlog)) :
2364 + // No news is good news; only send if
2365 + // there are some messages to send.
2366 + $body = NULL;
2367 + if (!isset($dlog['mesg'])) : $dlog['mesg'] = array(); endif;
2368 +
2369 + foreach ($dlog['mesg'] as $sect => $mesgs) :
2370 + if (count($mesgs) > 0) :
2371 + if (is_null($body)) : $body = ''; endif;
2372 +
2373 + $paradigm = reset($mesgs);
2374 + $body .= "<h2>".ucfirst($sect)." issues</h2>\n"
2375 + ."<table>\n"
2376 + ."<thead><tr>\n";
2377 + foreach ($paradigm as $col => $value) :
2378 + $body .= '<th scope="col">'.$col."</th>\n";
2379 + endforeach;
2380 + $body .= "</tr></thead>\n"
2381 + ."<tbody>\n";
2382 +
2383 + foreach ($mesgs as $line) :
2384 + $body .= "<tr>\n";
2385 + foreach ($line as $col => $cell) :
2386 + if (is_numeric($cell)) :
2387 + $cell = date('j-M-y, h:i a', $cell);
2388 + endif;
2389 + $class = strtolower(preg_replace('/\s+/', '-', $col));
2390 + $body .= "<td class=\"$class\">${cell}</td>";
2391 + endforeach;
2392 + $body .= "</tr>\n";
2393 + endforeach;
2394 +
2395 + $body .= "</tbody>\n</table>\n\n";
2396 + endif;
2397 + endforeach;
2398 +
2399 + $body = apply_filters('feedwordpress_diagnostic_email_body', $body, $dlog);
2400 + if (!is_null($body)) :
2401 + $home = feedwordpress_display_url(get_bloginfo('url'));
2402 + $subj = apply_filters('feedwordpress_diagnostic_email_subject', $home . " syndication issues", $dlog);
2403 + $agent = 'FeedWordPress '.FEEDWORDPRESS_VERSION;
2404 + $body = <<<EOMAIL
2405 +<html>
2406 +<head>
2407 +<title>$subj</title>
2408 +<style type="text/css">
2409 + body { background-color: white; color: black; }
2410 + table { width: 100%; border: 1px solid black; }
2411 + table thead tr th { background-color: #ff7700; color: white; border-bottom: 1px solid black; }
2412 + table thead tr { border-bottom: 1px solid black; }
2413 + table tr { vertical-align: top; }
2414 + table .since { width: 20%; }
2415 + table .time { width: 20%; }
2416 + table .most-recently { width: 20%; }
2417 + table .message { width: auto; }
2418 +</style>
2419 +</head>
2420 +<body>
2421 +<h1>Syndication Issues encountered by $agent on $home</h1>
2422 +$body
2423 +</body>
2424 +</html>
2425 +
2426 +EOMAIL;
2427 +
2428 + $ded = get_option('feedwordpress_diagnostics_email_destination', 'admins');
2429 +
2430 + // e-mail address
2431 + if (preg_match('/^mailto:(.*)$/', $ded, $ref)) :
2432 + $recipients = array($ref[1]);
2433 +
2434 + // userid
2435 + elseif (preg_match('/^user:(.*)$/', $ded, $ref)) :
2436 + $userdata = get_userdata((int) $ref[1]);
2437 + $recipients = array($userdata->user_email);
2438 +
2439 + // admins
2440 + else :
2441 + $recipients = FeedWordPressDiagnostic::admin_emails();
2442 + endif;
2443 +
2444 + $mesgId = 'feedwordpress+'.time().'@'.$home;
2445 + $parentId = get_option('feedwordpress_diagnostics_email_root_message_id', NULL);
2446 +
2447 + $head = array("Message-ID: <$mesgId>");
2448 + if (!is_null($parentId)) :
2449 + // We've already sent off a diagnostic message in the past. Let's do some
2450 + // magic to help with threading, in the hopes that all diagnostic messages
2451 + // get threaded together.
2452 + $head[] = "References: <$parentId>";
2453 + $head[] = "In-Reply-To: <$parentId>";
2454 + $subj = "Re: ".$subj;
2455 + else :
2456 + // This is the first of its kind. Let's mark it as such.
2457 + update_option('feedwordpress_diagnostics_email_root_message_id', $mesgId);
2458 + endif;
2459 + $head = apply_filters('feedwordpress_diagnostic_email_headers', $head);
2460 +
2461 + foreach ($recipients as $email) :
2462 + add_filter('wp_mail_content_type', array('FeedWordPress', 'allow_html_mail'));
2463 + wp_mail($email, $subj, $body, $head);
2464 + remove_filter('wp_mail_content_type', array('FeedWordPress', 'allow_html_mail'));
2465 + endforeach;
2466 + endif;
2467 +
2468 + // Clear the logs
2469 + $dlog['mesg']['persistent'] = array();
2470 + $dlog['mesg']['occurrent'] = array();
2471 +
2472 + // Set schedule for next update
2473 + $dlog['schedule']['last'] = time();
2474 + endif;
2475 + else :
2476 + $dlog['schedule'] = array(
2477 + 'freq' => 24 /*hr*/ * 60 /*min*/ * 60 /*s*/,
2478 + 'last' => time(),
2479 + );
2480 + endif;
2481 +
2482 + update_option('feedwordpress_diagnostics_log', $dlog);
2483 + } /* FeedWordPress::email_diagnostic_log () */
2484 +
2485 + static function allow_html_mail () {
2486 + return 'text/html';
2487 + } /* FeedWordPress::allow_html_mail () */
2488 +
2489 + static function admin_footer () {
2490 + global $feedwordpress_admin_footer;
2491 + foreach ($feedwordpress_admin_footer as $line) :
2492 + echo '<div><pre>'.$line.'</pre></div>';
2493 + endforeach;
2494 + } /* FeedWordPress::admin_footer () */
2495 +
2496 + static function log_prefix ($date = false) {
2497 + $home = get_bloginfo('url');
2498 + $prefix = '['.feedwordpress_display_url($home).'] [feedwordpress] ';
2499 + if ($date) :
2500 + $prefix = "[".date('Y-m-d H:i:s')."]".$prefix;
2501 + endif;
2502 + return $prefix;
2503 + } /* FeedWordPress::log_prefix () */
2504 +
2505 + static function menu_cap ($sub = false) {
2506 + if ($sub) :
2507 + $cap = apply_filters('feedwordpress_menu_settings_capacity', 'manage_options');
2508 + else :
2509 + $cap = apply_filters('feedwordpress_menu_main_capacity', 'manage_links');
2510 + endif;
2511 + return $cap;
2512 + } /* FeedWordPress::menu_cap () */
2513 +
2514 + static function path ($filename = '') {
2515 + global $fwp_path;
2516 +
2517 + $path = $fwp_path;
2518 + if (strlen($filename) > 0) :
2519 + $path .= '/'.$filename;
2520 + endif;
2521 + return $path;
2522 + } /* FeedWordPress::path () */
2523 +
2524 + // These are superceded by MyPHP::param/post/get/request, but kept
2525 + // here for backward compatibility.
2526 +
2527 + static function param ($key, $type = 'REQUEST', $default = NULL) {
2528 + return MyPHP::param($key, $default, $type);
2529 + } /* FeedWordPress::param () */
2530 +
2531 + static function post ($key, $default = NULL) {
2532 + return MyPHP::post($key, $default);
2533 + } /* FeedWordPress::post () */
2534 +
2535 +} /* class FeedWordPress */
2536 +
2537 +$feedwordpress_admin_footer = array();
1490 2538
1491 2539 // take your best guess at the realname and e-mail, given a string
1492 2540 define('FWP_REGEX_EMAIL_ADDY', '([^@"(<\s]+@[^"@(<\s]+\.[^"@(<\s]+)');
1493 2541 define('FWP_REGEX_EMAIL_NAME', '("([^"]*)"|([^"<(]+\S))');