function subscribe($args)
 {
     $ret = $this->validate($args);
     if (is_array($ret)) {
         // Success
         // The remaining params are feed URLs
         foreach ($args as $arg) {
             $finder = new FeedFinder($arg, false, 1);
             $feeds = array_values(array_unique($finder->find()));
             if (count($feeds) > 0) {
                 $link_id = FeedWordPress::syndicate_link(feedwordpress_display_url($feeds[0]), $feeds[0], $feeds[0]);
                 $ret[] = array('added', $feeds[0], $arg);
             } else {
                 $ret[] = array('error', $arg);
             }
         }
     }
     return $ret;
 }
 /**
  * SyndicatedPost::author_id (): get the ID for an author name from
  * the feed. Create the author if necessary.
  *
  * @param string $unfamiliar_author
  *
  * @return NULL|int The numeric ID of the author to attribute the post to
  *	NULL if the post should be filtered out.
  */
 function author_id($unfamiliar_author = 'create')
 {
     global $wpdb;
     $a = $this->named['author'];
     $source = $this->source();
     $forbidden = apply_filters('feedwordpress_forbidden_author_names', array('admin', 'administrator', 'www', 'root'));
     // Prepare the list of candidates to try for author name: name from
     // feed, original source title (if any), immediate source title live
     // from feed, subscription title, prettied version of feed homepage URL,
     // prettied version of feed URL, or, failing all, use "unknown author"
     // as last resort
     $candidates = array();
     $candidates[] = $a['name'];
     if (!is_null($source)) {
         $candidates[] = $source['title'];
     }
     $candidates[] = $this->link->name(true);
     $candidates[] = $this->link->name(false);
     if (strlen($this->link->homepage()) > 0) {
         $candidates[] = feedwordpress_display_url($this->link->homepage());
     }
     $candidates[] = feedwordpress_display_url($this->link->uri());
     $candidates[] = 'unknown author';
     // Pick the first one that works from the list, screening against empty
     // or forbidden names.
     $author = NULL;
     while (is_null($author) and $candidate = each($candidates)) {
         if (!is_null($candidate['value']) and strlen(trim($candidate['value'])) > 0 and !in_array(strtolower(trim($candidate['value'])), $forbidden)) {
             $author = $candidate['value'];
         }
     }
     $email = isset($a['email']) ? $a['email'] : NULL;
     $authorUrl = isset($a['uri']) ? $a['uri'] : NULL;
     $hostUrl = $this->link->homepage();
     if (is_null($hostUrl) or strlen($hostUrl) < 0) {
         $hostUrl = $this->link->uri();
     }
     $match_author_by_email = !('yes' == get_option("feedwordpress_do_not_match_author_by_email"));
     if ($match_author_by_email and !FeedWordPress::is_null_email($email)) {
         $test_email = $email;
     } else {
         $test_email = NULL;
     }
     // Never can be too careful...
     $login = sanitize_user($author, true);
     // Possible for, e.g., foreign script author names
     if (strlen($login) < 1) {
         // No usable characters in author name for a login.
         // (Sometimes results from, e.g., foreign scripts.)
         //
         // We just need *something* in Western alphanumerics,
         // so let's try the domain name.
         //
         // Uniqueness will be guaranteed below if necessary.
         $url = parse_url($hostUrl);
         $login = sanitize_user($url['host'], true);
         if (strlen($login) < 1) {
             // This isn't working. Frak it.
             $login = '******';
         }
     }
     $login = apply_filters('pre_user_login', $login);
     $nice_author = sanitize_title($author);
     $nice_author = apply_filters('pre_user_nicename', $nice_author);
     $reg_author = esc_sql(preg_quote($author));
     $author = esc_sql($author);
     $email = esc_sql($email);
     $test_email = esc_sql($test_email);
     $authorUrl = esc_sql($authorUrl);
     // Check for an existing author rule....
     if (isset($this->link->settings['map authors']['name']['*'])) {
         $author_rule = $this->link->settings['map authors']['name']['*'];
     } elseif (isset($this->link->settings['map authors']['name'][strtolower(trim($author))])) {
         $author_rule = $this->link->settings['map authors']['name'][strtolower(trim($author))];
     } else {
         $author_rule = NULL;
     }
     // User name is mapped to a particular author. If that author ID exists, use it.
     if (is_numeric($author_rule) and get_userdata((int) $author_rule)) {
         $id = (int) $author_rule;
         // User name is filtered out
     } elseif ('filter' == $author_rule) {
         $id = NULL;
     } else {
         // Check the database for an existing author record that might fit
         // First try the user core data table.
         $id = $wpdb->get_var("SELECT ID FROM {$wpdb->users}\n\t\t\tWHERE TRIM(LCASE(display_name)) = TRIM(LCASE('{$author}'))\n\t\t\tOR TRIM(LCASE(user_login)) = TRIM(LCASE('{$author}'))\n\t\t\tOR (\n\t\t\t\tLENGTH(TRIM(LCASE(user_email))) > 0\n\t\t\t\tAND TRIM(LCASE(user_email)) = TRIM(LCASE('{$test_email}'))\n\t\t\t)");
         // If that fails, look for aliases in the user meta data table
         if (is_null($id)) {
             $id = $wpdb->get_var("SELECT user_id FROM {$wpdb->usermeta}\n\t\t\t\tWHERE\n\t\t\t\t\t(meta_key = 'description' AND TRIM(LCASE(meta_value)) = TRIM(LCASE('{$author}')))\n\t\t\t\t\tOR (\n\t\t\t\t\t\tmeta_key = 'description'\n\t\t\t\t\t\tAND TRIM(LCASE(meta_value))\n\t\t\t\t\t\tRLIKE CONCAT(\n\t\t\t\t\t\t\t'(^|\\n)a\\.?k\\.?a\\.?( |\\t)*:?( |\\t)*',\n\t\t\t\t\t\t\tTRIM(LCASE('{$reg_author}')),\n\t\t\t\t\t\t\t'( |\\t|\\r)*(\\n|\$)'\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t");
         }
         // ... if you don't find one, then do what you need to do
         if (is_null($id)) {
             if ($unfamiliar_author === 'create') {
                 $userdata = array();
                 // WordPress 3 is going to pitch a fit if we attempt to register
                 // more than one user account with an empty e-mail address, so we
                 // need *something* here. Ugh.
                 if (strlen($email) == 0 or FeedWordPress::is_null_email($email)) {
                     $url = parse_url($hostUrl);
                     $email = $nice_author . '@' . $url['host'];
                 }
                 #-- user table data
                 $userdata['ID'] = NULL;
                 // new user
                 $userdata['user_login'] = $login;
                 $userdata['user_nicename'] = $nice_author;
                 $userdata['user_pass'] = substr(md5(uniqid(microtime())), 0, 6);
                 // just something random to lock it up
                 $userdata['user_email'] = $email;
                 $userdata['user_url'] = $authorUrl;
                 $userdata['nickname'] = $author;
                 $parts = preg_split('/\\s+/', trim($author), 2);
                 if (isset($parts[0])) {
                     $userdata['first_name'] = $parts[0];
                 }
                 if (isset($parts[1])) {
                     $userdata['last_name'] = $parts[1];
                 }
                 $userdata['display_name'] = $author;
                 $userdata['role'] = 'contributor';
                 do {
                     // Keep trying until you get it right. Or until PHP crashes, I guess.
                     $id = wp_insert_user($userdata);
                     if (is_wp_error($id)) {
                         $codes = $id->get_error_code();
                         switch ($codes) {
                             case 'empty_user_login':
                             case 'existing_user_login':
                                 // Add a random disambiguator
                                 $userdata['user_login'] .= substr(md5(uniqid(microtime())), 0, 6);
                                 break;
                             case 'existing_user_email':
                                 // No disassemble!
                                 $parts = explode('@', $userdata['user_email'], 2);
                                 // Add a random disambiguator as a gmail-style username extension
                                 $parts[0] .= '+' . substr(md5(uniqid(microtime())), 0, 6);
                                 // Reassemble
                                 $userdata['user_email'] = $parts[0] . '@' . $parts[1];
                                 break;
                         }
                     }
                 } while (is_wp_error($id));
             } elseif (is_numeric($unfamiliar_author) and get_userdata((int) $unfamiliar_author)) {
                 $id = (int) $unfamiliar_author;
             } elseif ($unfamiliar_author === 'default') {
                 $id = 1;
             }
         }
     }
     if ($id) {
         $this->link->settings['map authors']['name'][strtolower(trim($author))] = $id;
         // Multisite: Check whether the author has been recorded
         // on *this* blog before. If not, put her down as a
         // Contributor for *this* blog.
         $user = new WP_User((int) $id);
         if (empty($user->roles)) {
             $user->add_role('contributor');
         }
     }
     return $id;
 }
 public function syndication_source($original = NULL)
 {
     $ret = $this->meta('syndication_source', array("unproxy" => $original));
     // If this is blank, fall back to a prettified URL for the blog.
     if (is_null($ret) or strlen(trim($ret)) == 0) {
         $ret = feedwordpress_display_url($this->syndication_source_link());
     }
     return $ret;
 }
    function multiadd_box($page, $box = NULL)
    {
        global $fwp_post;
        $localData = NULL;
        if (isset($_FILES['opml_upload']['name']) and strlen($_FILES['opml_upload']['name']) > 0) {
            $in = 'tag:localhost';
            /*FIXME: check whether $_FILES['opml_upload']['error'] === UPLOAD_ERR_OK or not...*/
            $localData = file_get_contents($_FILES['opml_upload']['tmp_name']);
            $merge_all = true;
        } elseif (isset($fwp_post['multilookup'])) {
            $in = $fwp_post['multilookup'];
            $merge_all = false;
        } elseif (isset($fwp_post['opml_lookup'])) {
            $in = $fwp_post['opml_lookup'];
            $merge_all = true;
        } else {
            $in = '';
            $merge_all = false;
        }
        if (strlen($in) > 0) {
            $lines = preg_split("/\\s+/", $in, -1, PREG_SPLIT_NO_EMPTY);
            $i = 0;
            ?>
			<form id="multiadd-form" action="<?php 
            print $this->form_action();
            ?>
" method="post">
			<div><?php 
            FeedWordPressCompatibility::stamp_nonce('feedwordpress_feeds');
            ?>
			<input type="hidden" name="multiadd" value="<?php 
            print FWP_SYNDICATE_NEW;
            ?>
" />
			<input type="hidden" name="confirm" value="multiadd" />

			<input type="hidden" name="multiadd" value="<?php 
            print FWP_SYNDICATE_NEW;
            ?>
" />
			<input type="hidden" name="confirm" value="multiadd" /></div>

			<div id="multiadd-status">
			<p><img src="<?php 
            print esc_url(admin_url('images/wpspin_light.gif'));
            ?>
" alt="" />
			Looking up feed information...</p>
			</div>

			<div id="multiadd-buttons">
			<input type="submit" class="button" name="cancel" value="<?php 
            _e(FWP_CANCEL_BUTTON);
            ?>
" />
			<input type="submit" class="button-primary" value="<?php 
            print _e('Subscribe to selected sources →');
            ?>
" />
			</div>
			
			<p><?php 
            _e('Here are the feeds that FeedWordPress has discovered from the addresses that you provided. To opt out of a subscription, unmark the checkbox next to the feed.');
            ?>
</p>
			
			<?php 
            print "<ul id=\"multiadd-list\">\n";
            flush();
            foreach ($lines as $line) {
                $url = trim($line);
                if (strlen($url) > 0) {
                    // First, use FeedFinder to check the URL.
                    if (is_null($localData)) {
                        $finder = new FeedFinder($url, false, 1);
                    } else {
                        $finder = new FeedFinder('tag:localhost', false, 1);
                        $finder->upload_data($localData);
                    }
                    $feeds = array_values(array_unique($finder->find()));
                    $found = false;
                    if (count($feeds) > 0) {
                        foreach ($feeds as $feed) {
                            $pie = FeedWordPress::fetch($feed);
                            if (!is_wp_error($pie)) {
                                $found = true;
                                $short_feed = esc_html(feedwordpress_display_url($feed));
                                $feed = esc_html($feed);
                                $title = esc_html($pie->get_title());
                                $checked = ' checked="checked"';
                                $link = esc_html($pie->get_link());
                                $this->display_multiadd_line(array('feed' => $feed, 'title' => $pie->get_title(), 'link' => $pie->get_link(), 'checked' => ' checked="checked"', 'i' => $i));
                                $i++;
                                // Increment field counter
                                if (!$merge_all) {
                                    // Break out after first find
                                    break;
                                }
                            }
                        }
                    }
                    if (!$found) {
                        $this->display_multiadd_line(array('feed' => $url, 'title' => feedwordpress_display_url($url), 'extra' => " [FeedWordPress couldn't detect any feeds for this URL.]", 'link' => NULL, 'checked' => '', 'i' => $i));
                        $i++;
                        // Increment field counter
                    }
                }
            }
            print "</ul>\n";
            ?>
			</form>
			
			<script type="text/javascript">
				jQuery(document).ready( function () {
					// Hide it now that we're done.
					jQuery('#multiadd-status').fadeOut(500 /*ms*/);
				} );
			</script>
			<?php 
        }
        $this->_sources = NULL;
        // Force reload of sources list
        return true;
        // Continue
    }
	function __construct ($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false) {
		global $feedwordpress;
		global $wp_version;

		$source = NULL;
		if ($feedwordpress->subscribed($url)) :
			$source = $feedwordpress->subscription($url);
		endif;
		
		$this->url = $url;
		$this->timeout = $timeout;
		$this->redirects = $redirects;
		$this->headers = $headers;
		$this->useragent = $useragent;

		$this->method = SIMPLEPIE_FILE_SOURCE_REMOTE;
		
		global $wpdb;
		global $fwp_credentials;
		
		if ( preg_match('/^http(s)?:\/\//i', $url) ) {
			$args = array( 'timeout' => $this->timeout, 'redirection' => $this->redirects);
	
			if ( !empty($this->headers) )
				$args['headers'] = $this->headers;

			// Use default FWP user agent unless custom has been specified
			if ( SIMPLEPIE_USERAGENT != $this->useragent ) :
				$args['user-agent'] = $this->useragent;
			else :
				$args['user-agent'] = apply_filters('feedwordpress_user_agent',
					'FeedWordPress/'.FEEDWORDPRESS_VERSION
					.' (aggregator:feedwordpress; WordPress/'.$wp_version
					.' + '.SIMPLEPIE_NAME.'/'.SIMPLEPIE_VERSION
					.'; Allow like Gecko; +http://feedwordpress.radgeek.com/) at '
					. feedwordpress_display_url(get_bloginfo('url')),
					$this
				);
			endif;

			// This is ugly as hell, but communicating up and down the chain
			// in any other way is difficult.

			if (!is_null($fwp_credentials)) :

				$args['authentication'] = $fwp_credentials['authentication'];
				$args['username'] = $fwp_credentials['username'];
				$args['password'] = $fwp_credentials['password'];

			elseif ($source InstanceOf SyndicatedLink) :

				$args['authentication'] = $source->authentication_method();
				$args['username'] = $source->username();
				$args['password'] = $source->password();
			
			endif;

			FeedWordPress::diagnostic('updated_feeds:http', "HTTP [$url] &#8668; ".esc_html(FeedWordPress::val($args)));
			$res = wp_remote_request($url, $args);
			FeedWordPress::diagnostic('updated_feeds:http', "HTTP [$url] &#8669; ".esc_html(FeedWordPress::val($res)));

			if ( is_wp_error($res) ) {
				$this->error = 'WP HTTP Error: ' . $res->get_error_message();
				$this->success = false;
			} else {
				$this->headers = wp_remote_retrieve_headers( $res );
				$this->body = wp_remote_retrieve_body( $res );
				$this->status_code = wp_remote_retrieve_response_code( $res );
			}
			
			if ($source InstanceOf SyndicatedLink) :
				$source->update_setting('link/filesize', strlen($this->body));
				$source->update_setting('link/http status', $this->status_code);
				$source->save_settings(/*reload=*/ true);
			endif;
			
		} else {
			if ( ! $this->body = file_get_contents($url) ) {
				$this->error = 'file_get_contents could not read the file';
				$this->success = false;
			}
		}

		// SimplePie makes a strongly typed check against integers with
		// this, but WordPress puts a string in. Which causes caching
		// to break and fall on its ass when SimplePie is getting a 304,
		// but doesn't realize it because this member is "304" instead.
		$this->status_code = (int) $this->status_code;
	}
    function display_feedfinder()
    {
        global $wpdb;
        $lookup = isset($_REQUEST['lookup']) ? $_REQUEST['lookup'] : NULL;
        $auth = FeedWordPress::param('link_rss_auth_method');
        $username = FeedWordPress::param('link_rss_username');
        $password = FeedWordPress::param('link_rss_password');
        $credentials = array("authentication" => $auth, "username" => $username, "password" => $password);
        $feeds = array();
        $feedSwitch = false;
        $current = null;
        if ($this->for_feed_settings()) {
            // Existing feed?
            $feedSwitch = true;
            if (is_null($lookup)) {
                // Switch Feed without a specific feed yet suggested
                // Go to the human-readable homepage to look for
                // auto-detection links
                $lookup = $this->link->link->link_url;
                $auth = $this->link->setting('http auth method');
                $username = $this->link->setting('http username');
                $password = $this->link->setting('http password');
                // Guarantee that you at least have the option to
                // stick with what works.
                $current = $this->link->link->link_rss;
                $feeds[] = $current;
            }
            $name = esc_html($this->link->link->link_name);
        } else {
            // Or a new subscription to add?
            $name = "Subscribe to <code>" . esc_html(feedwordpress_display_url($lookup)) . "</code>";
        }
        ?>
		<div class="wrap" id="feed-finder">
		<h2>Feed Finder: <?php 
        echo $name;
        ?>
</h2>

		<?php 
        if ($feedSwitch) {
            $this->display_alt_feed_box($lookup);
        }
        $finder = array();
        if (!is_null($current)) {
            $finder[$current] = new FeedFinder($current);
        }
        $finder[$lookup] = new FeedFinder($lookup);
        foreach ($finder as $url => $ff) {
            $feeds = array_merge($feeds, $ff->find(NULL, $credentials));
        }
        $feeds = array_values($feeds);
        if (count($feeds) > 0) {
            if ($feedSwitch) {
                ?>
				<h3>Feeds Found</h3>
				<?php 
            }
            if (count($feeds) > 1) {
                $option_template = 'Option %d: ';
                $form_class = ' class="multi"';
                ?>
				<p><strong>This web page provides at least <?php 
                print count($feeds);
                ?>
 different feeds.</strong> These feeds may provide the same information
				in different formats, or may track different items. (You can check the Feed Information and the
				Sample Item for each feed to get an idea of what the feed provides.) Please select the feed that you'd like to subscribe to.</p>
				<?php 
            } else {
                $option_template = '';
                $form_class = '';
            }
            global $fwp_credentials;
            foreach ($feeds as $key => $f) {
                $ofc = $fwp_credentials;
                $fwp_credentials = $credentials;
                // Set
                $pie = FeedWordPress::fetch($f);
                $fwp_credentials = $ofc;
                // Re-Set
                $rss = is_wp_error($pie) ? $pie : new MagpieFromSimplePie($pie);
                if ($this->url_for_401($pie)) {
                    $this->display_alt_feed_box($lookup, array("err" => $pie, "auth" => $auth, "username" => $username, "password" => $password));
                    continue;
                }
                if ($rss and !is_wp_error($rss)) {
                    $feed_link = isset($rss->channel['link']) ? $rss->channel['link'] : '';
                    $feed_title = isset($rss->channel['title']) ? $rss->channel['title'] : $feed_link;
                    $feed_type = $rss->feed_type ? $rss->feed_type : 'Unknown';
                    $feed_version_template = '%.1f';
                    $feed_version = $rss->feed_version;
                } else {
                    // Give us some sucky defaults
                    $feed_title = feedwordpress_display_url($lookup);
                    $feed_link = $lookup;
                    $feed_type = 'Unknown';
                    $feed_version_template = '';
                    $feed_version = '';
                }
                ?>
					<form<?php 
                print $form_class;
                ?>
 action="admin.php?page=<?php 
                print $GLOBALS['fwp_path'];
                ?>
/syndication.php" method="post">
					<div class="inside"><?php 
                FeedWordPressCompatibility::stamp_nonce('feedwordpress_switchfeed');
                ?>

					<?php 
                $classes = array('feed-found');
                $currentFeed = '';
                if (!is_null($current) and $current == $f) {
                    $classes[] = 'current';
                    $currentFeed = ' (currently subscribed)';
                }
                if ($key % 2) {
                    $classes[] = 'alt';
                }
                ?>
					<fieldset class="<?php 
                print implode(" ", $classes);
                ?>
">
					<legend><?php 
                printf($option_template, $key + 1);
                print $feed_type . " ";
                printf($feed_version_template, $feed_version);
                ?>
 feed<?php 
                print $currentFeed;
                ?>
</legend>

					<?php 
                $this->stamp_link_id();
                // No feed specified = add new feed; we
                // need to pass along a starting title
                // and homepage URL for the new Link.
                if (!$this->for_feed_settings()) {
                    ?>
						<input type="hidden" name="feed_title" value="<?php 
                    echo esc_html($feed_title);
                    ?>
" />
						<input type="hidden" name="feed_link" value="<?php 
                    echo esc_html($feed_link);
                    ?>
" />
						<?php 
                }
                ?>

					<input type="hidden" name="feed" value="<?php 
                echo esc_html($f);
                ?>
" />
					<input type="hidden" name="action" value="switchfeed" />

					<div>
					<div class="feed-sample">
					<?php 
                $link = NULL;
                $post = NULL;
                if (!is_wp_error($rss) and count($rss->items) > 0) {
                    // Prepare to display Sample Item
                    $link = new MagpieMockLink(array('simplepie' => $pie, 'magpie' => $rss), $f);
                    $post = new SyndicatedPost(array('simplepie' => $rss->originals[0], 'magpie' => $rss->items[0]), $link);
                    ?>
						<h3>Sample Item</h3>
						<ul>
						<li><strong>Title:</strong> <a href="<?php 
                    echo $post->post['meta']['syndication_permalink'];
                    ?>
"><?php 
                    echo $post->post['post_title'];
                    ?>
</a></li>
						<li><strong>Date:</strong> <?php 
                    print date('d-M-y g:i:s a', $post->published());
                    ?>
</li>
						</ul>
						<div class="entry">
						<?php 
                    print $post->post['post_content'];
                    ?>
						</div>
						<?php 
                    do_action('feedwordpress_feed_finder_sample_item', $f, $post, $link);
                } else {
                    if (is_wp_error($rss)) {
                        print '<div class="feed-problem">';
                        print "<h3>Problem:</h3>\n";
                        print "<p>FeedWordPress encountered the following error\n\t\t\t\t\t\t\twhen trying to retrieve this feed:</p>";
                        print '<p style="margin: 1.0em 3.0em"><code>' . $rss->get_error_message() . '</code></p>';
                        print "<p>If you think this is a temporary problem, you can still force FeedWordPress to add the subscription. FeedWordPress will not be able to find any syndicated posts until this problem is resolved.</p>";
                        print "</div>";
                    }
                    ?>
						<h3>No Items</h3>
						<p>FeedWordPress found no posts on this feed.</p>
						<?php 
                }
                ?>
					</div>
	
					<div>
					<h3>Feed Information</h3>
					<ul>
					<li><strong>Homepage:</strong> <a href="<?php 
                echo $feed_link;
                ?>
"><?php 
                echo is_null($feed_title) ? '<em>Unknown</em>' : $feed_title;
                ?>
</a></li>
					<li><strong>Feed URL:</strong> <a title="<?php 
                echo esc_html($f);
                ?>
" href="<?php 
                echo esc_html($f);
                ?>
"><?php 
                echo esc_html(feedwordpress_display_url($f, 40, 10));
                ?>
</a> (<a title="Check feed &lt;<?php 
                echo esc_html($f);
                ?>
&gt; for validity" href="http://feedvalidator.org/check.cgi?url=<?php 
                echo urlencode($f);
                ?>
">validate</a>)</li>
					<li><strong>Encoding:</strong> <?php 
                echo isset($rss->encoding) ? esc_html($rss->encoding) : "<em>Unknown</em>";
                ?>
</li>
					<li><strong>Description:</strong> <?php 
                echo isset($rss->channel['description']) ? esc_html($rss->channel['description']) : "<em>Unknown</em>";
                ?>
</li>
					</ul>
					<?php 
                $this->display_authentication_credentials_box(array('username' => $username, 'password' => $password, 'method' => $auth));
                ?>
					<?php 
                do_action('feedwordpress_feedfinder_form', $f, $post, $link, $this->for_feed_settings());
                ?>
					<div class="submit"><input type="submit" class="button-primary" name="Use" value="&laquo; Use this feed" />
					<input type="submit" class="button" name="Cancel" value="× Cancel" /></div>
					</div>
					</div>
					</fieldset>
					</div> <!-- class="inside" -->
					</form>
					<?php 
                unset($link);
                unset($post);
            }
        } else {
            foreach ($finder as $url => $ff) {
                $url = esc_html($url);
                print "<h3>Searched for feeds at {$url}</h3>\n";
                print "<p><strong>" . __('Error') . ":</strong> " . __("FeedWordPress couldn't find any feeds at") . ' <code><a href="' . htmlspecialchars($lookup) . '">' . htmlspecialchars($lookup) . '</a></code>';
                print ". " . __('Try another URL') . ".</p>";
                // Diagnostics
                print "<div class=\"updated\" style=\"margin-left: 3.0em; margin-right: 3.0em;\">\n";
                print "<h3>" . __('Diagnostic information') . "</h3>\n";
                if (!is_null($ff->error()) and strlen($ff->error()) > 0) {
                    print "<h4>" . __('HTTP request failure') . "</h4>\n";
                    print "<p>" . $ff->error() . "</p>\n";
                } else {
                    print "<h4>" . __('HTTP request completed') . "</h4>\n";
                    print "<p><strong>Status " . $ff->status() . ":</strong> " . $this->HTTPStatusMessages[(int) $ff->status()] . "</p>\n";
                }
                // Do some more diagnostics if the API for it is available.
                if (function_exists('_wp_http_get_object')) {
                    $httpObject = _wp_http_get_object();
                    if (is_callable(array($httpObject, '_getTransport'))) {
                        $transports = $httpObject->_getTransport();
                        print "<h4>" . __('HTTP Transports available') . ":</h4>\n";
                        print "<ol>\n";
                        print "<li>" . implode("</li>\n<li>", array_map('get_class', $transports)) . "</li>\n";
                        print "</ol>\n";
                    } elseif (is_callable(array($httpObject, '_get_first_available_transport'))) {
                        $transport = $httpObject->_get_first_available_transport(array(), $url);
                        print "<h4>" . __("HTTP Transport") . ":</h4>\n";
                        print "<ol>\n";
                        print "<li>" . FeedWordPress::val($transport) . "</li>\n";
                        print "</ol>\n";
                    }
                    print "</div>\n";
                }
            }
        }
        if (!$feedSwitch) {
            $this->display_alt_feed_box($lookup, true);
        }
        ?>
	</div> <!-- class="wrap" -->
		<?php 
        return false;
        // Don't continue
    }
 function log_prefix($date = false)
 {
     $home = get_bloginfo('url');
     $prefix = '[' . feedwordpress_display_url($home) . '] [feedwordpress] ';
     if ($date) {
         $prefix = "[" . date('Y-m-d H:i:s') . "]" . $prefix;
     }
     return $prefix;
 }
function get_syndication_source($original = NULL, $id = NULL)
{
    if (is_null($original)) {
        $original = FeedWordPress::use_aggregator_source_data();
    }
    if ($original) {
        $vals = get_post_custom_values('syndication_source_original', $id);
    } else {
        $vals = array();
    }
    if (count($vals) == 0) {
        $vals = get_post_custom_values('syndication_source', $id);
    }
    if (count($vals) > 0) {
        $ret = $vals[0];
    } else {
        $ret = NULL;
    }
    if (is_null($ret) or strlen(trim($ret)) == 0) {
        // Fall back to URL of blog
        $ret = feedwordpress_display_url(get_syndication_source_link());
    }
    return $ret;
}
 public function __construct($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false)
 {
     global $feedwordpress;
     global $wp_version;
     $source = NULL;
     if ($feedwordpress->subscribed($url)) {
         $source = $feedwordpress->subscription($url);
     }
     $this->url = $url;
     $this->timeout = $timeout;
     $this->redirects = $redirects;
     $this->headers = $headers;
     $this->useragent = $useragent;
     $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE;
     global $wpdb;
     global $fwp_credentials;
     if (preg_match('/^http(s)?:\\/\\//i', $url)) {
         $args = array('timeout' => $this->timeout, 'redirection' => $this->redirects);
         if (!empty($this->headers)) {
             $args['headers'] = $this->headers;
         }
         // Use default FWP user agent unless custom has been specified
         if (SIMPLEPIE_USERAGENT != $this->useragent) {
             $args['user-agent'] = $this->useragent;
         } else {
             $args['user-agent'] = apply_filters('feedwordpress_user_agent', 'FeedWordPress/' . FEEDWORDPRESS_VERSION . ' (aggregator:feedwordpress; WordPress/' . $wp_version . ' + ' . SIMPLEPIE_NAME . '/' . SIMPLEPIE_VERSION . '; Allow like Gecko; +http://feedwordpress.radgeek.com/) at ' . feedwordpress_display_url(get_bloginfo('url')), $this);
         }
         // This is ugly as hell, but communicating up and down the chain
         // in any other way is difficult.
         if (!is_null($fwp_credentials)) {
             $args['authentication'] = $fwp_credentials['authentication'];
             $args['username'] = $fwp_credentials['username'];
             $args['password'] = $fwp_credentials['password'];
         } elseif ($source instanceof SyndicatedLink) {
             $args['authentication'] = $source->authentication_method();
             $args['username'] = $source->username();
             $args['password'] = $source->password();
         }
         FeedWordPress::diagnostic('updated_feeds:http', "HTTP [{$url}] &#8668; " . esc_html(MyPHP::val($args)));
         $res = wp_remote_request($url, $args);
         FeedWordPress::diagnostic('updated_feeds:http', "HTTP [{$url}] &#8669; " . esc_html(MyPHP::val($res)));
         if (is_wp_error($res)) {
             $this->error = 'WP HTTP Error: ' . $res->get_error_message();
             $this->success = false;
         } else {
             $this->headers = wp_remote_retrieve_headers($res);
             $this->body = wp_remote_retrieve_body($res);
             $this->status_code = wp_remote_retrieve_response_code($res);
         }
         if ($source instanceof SyndicatedLink) {
             $source->update_setting('link/filesize', strlen($this->body));
             $source->update_setting('link/http status', $this->status_code);
             $source->save_settings(true);
         }
         // Do not allow schemes other than http(s)? for the time being.
         // They are unlikely to be used; and unrestricted use of schemes
         // allows for user to use an unrestricted file:/// scheme, which
         // may result in exploits by WordPress users against the web
         // hosting environment.
     } else {
         $this->error = 'FeedWordPress only allows http or https URLs';
         $this->success = false;
     }
     // SimplePie makes a strongly typed check against integers with
     // this, but WordPress puts a string in. Which causes caching
     // to break and fall on its ass when SimplePie is getting a 304,
     // but doesn't realize it because this member is "304" instead.
     $this->status_code = (int) $this->status_code;
 }
Example #10
0
function fwp_syndication_manage_page_links_table_rows($links, $page, $visible = 'Y')
{
    $subscribed = 'Y' == strtoupper($visible);
    if ($subscribed or count($links) > 0) {
        ?>
	<table class="widefat<?php 
        if (!$subscribed) {
            ?>
 unsubscribed<?php 
        }
        ?>
">
	<thead>
	<tr>
	<th class="check-column" scope="col"><input type="checkbox" /></th>
	<th scope="col"><?php 
        _e('Name');
        ?>
</th>
	<th scope="col"><?php 
        _e('Feed');
        ?>
</th>
	<th scope="col"><?php 
        _e('Updated');
        ?>
</th>
	</tr>
	</thead>

	<tbody>
<?php 
        $alt_row = true;
        if (count($links) > 0) {
            foreach ($links as $link) {
                $trClass = array();
                // Prep: Get last updated timestamp
                $sLink = new SyndicatedLink($link->link_id);
                if (!is_null($sLink->setting('update/last'))) {
                    $lastUpdated = 'Last checked ' . fwp_time_elapsed($sLink->setting('update/last'));
                } else {
                    $lastUpdated = __('None yet');
                }
                // Prep: get last error timestamp, if any
                $fileSizeLines = array();
                if (is_null($sLink->setting('update/error'))) {
                    $errorsSince = '';
                    if (!is_null($sLink->setting('link/item count'))) {
                        $N = $sLink->setting('link/item count');
                        $fileSizeLines[] = sprintf($N == 1 ? __('%d item') : __('%d items'), $N);
                    }
                    if (!is_null($sLink->setting('link/filesize'))) {
                        $fileSizeLines[] = size_format($sLink->setting('link/filesize')) . ' total';
                    }
                } else {
                    $trClass[] = 'feed-error';
                    $theError = unserialize($sLink->setting('update/error'));
                    $errorsSince = "<div class=\"returning-errors\">" . "<p><strong>Returning errors</strong> since " . fwp_time_elapsed($theError['since']) . "</p>" . "<p>Most recent (" . fwp_time_elapsed($theError['ts']) . "):<br/><code>" . implode("</code><br/><code>", $theError['object']->get_error_messages()) . "</code></p>" . "</div>\n";
                }
                $nextUpdate = "<div style='max-width: 30.0em; font-size: 0.9em;'><div style='font-style:italic;'>";
                $ttl = $sLink->setting('update/ttl');
                if (is_numeric($ttl)) {
                    $next = $sLink->setting('update/last') + $sLink->setting('update/fudge') + (int) $ttl * 60;
                    if ('automatically' == $sLink->setting('update/timed')) {
                        if ($next < time()) {
                            $nextUpdate .= 'Ready and waiting to be updated since ';
                        } else {
                            $nextUpdate .= 'Scheduled for next update ';
                        }
                        $nextUpdate .= fwp_time_elapsed($next);
                        if (FEEDWORDPRESS_DEBUG) {
                            $nextUpdate .= " [" . ($next - time()) / 60 . " minutes]";
                        }
                    } else {
                        $lastUpdated .= " &middot; Next ";
                        if ($next < time()) {
                            $lastUpdated .= 'ASAP';
                        } elseif ($next - time() < 60) {
                            $lastUpdated .= fwp_time_elapsed($next);
                        } elseif ($next - time() < 60 * 60 * 24) {
                            $lastUpdated .= gmdate('g:ia', $next + get_option('gmt_offset') * 3600);
                        } else {
                            $lastUpdated .= gmdate('F j', $next + get_option('gmt_offset') * 3600);
                        }
                        $nextUpdate .= "Scheduled to be checked for updates every " . $ttl . " minute" . ($ttl != 1 ? "s" : "") . "</div><div style='size:0.9em; margin-top: 0.5em'>\tThis update schedule was requested by the feed provider";
                        if ($sLink->setting('update/xml')) {
                            $nextUpdate .= " using a standard <code style=\"font-size: inherit; padding: 0; background: transparent\">&lt;" . $sLink->setting('update/xml') . "&gt;</code> element";
                        }
                        $nextUpdate .= ".";
                    }
                } else {
                    $nextUpdate .= "Scheduled for update as soon as possible";
                }
                $nextUpdate .= "</div></div>";
                $fileSize = '';
                if (count($fileSizeLines) > 0) {
                    $fileSize = '<div>' . implode(" / ", $fileSizeLines) . "</div>";
                }
                unset($sLink);
                $alt_row = !$alt_row;
                if ($alt_row) {
                    $trClass[] = 'alternate';
                }
                ?>
	<tr<?php 
                echo count($trClass) > 0 ? ' class="' . implode(" ", $trClass) . '"' : '';
                ?>
>
	<th class="check-column" scope="row"><input type="checkbox" name="link_ids[]" value="<?php 
                echo $link->link_id;
                ?>
" /></th>
				<?php 
                $caption = strlen($link->link_rss) > 0 ? __('Switch Feed') : ($caption = __('Find Feed'));
                ?>
	<td>
	<strong><a href="<?php 
                print $page->admin_page_href('feeds-page.php', array(), $link);
                ?>
"><?php 
                print esc_html($link->link_name);
                ?>
</a></strong>
	<div class="row-actions"><?php 
                if ($subscribed) {
                    $page->display_feed_settings_page_links(array('before' => '<div><strong>Settings &gt;</strong> ', 'after' => '</div>', 'subscription' => $link));
                }
                ?>

	<div><strong>Actions &gt;</strong>
	<?php 
                if ($subscribed) {
                    ?>
	<a href="<?php 
                    print $page->admin_page_href('syndication.php', array('action' => 'feedfinder'), $link);
                    ?>
"><?php 
                    echo $caption;
                    ?>
</a>
	<?php 
                } else {
                    ?>
	<a href="<?php 
                    print $page->admin_page_href('syndication.php', array('action' => FWP_RESUB_CHECKED), $link);
                    ?>
"><?php 
                    _e('Re-subscribe');
                    ?>
</a>
	<?php 
                }
                ?>
	| <a href="<?php 
                print $page->admin_page_href('syndication.php', array('action' => 'Unsubscribe'), $link);
                ?>
"><?php 
                _e($subscribed ? 'Unsubscribe' : 'Delete permanently');
                ?>
</a>
	| <a href="<?php 
                print esc_html($link->link_url);
                ?>
"><?php 
                _e('View');
                ?>
</a></div>
	</div>
	</td>
				<?php 
                if (strlen($link->link_rss) > 0) {
                    ?>
	<td><a href="<?php 
                    echo esc_html($link->link_rss);
                    ?>
"><?php 
                    echo esc_html(feedwordpress_display_url($link->link_rss, 32));
                    ?>
</a></td>
				<?php 
                } else {
                    ?>
	<td class="feed-missing"><p><strong>no feed assigned</strong></p></td>
				<?php 
                }
                ?>

	<td><div style="float: right; padding-left: 10px">
	<input type="submit" class="button" name="update_uri[<?php 
                print esc_html($link->link_rss);
                ?>
]" value="<?php 
                _e('Update Now');
                ?>
" />
	</div>
	<?php 
                print $lastUpdated;
                ?>
	<?php 
                print $fileSize;
                ?>
	<?php 
                print $errorsSince;
                ?>
	<?php 
                print $nextUpdate;
                ?>
	</td>
	</tr>
			<?php 
            }
        } else {
            ?>
<tr><td colspan="4"><p>There are no websites currently listed for syndication.</p></td></tr>
<?php 
        }
        ?>
</tbody>
</table>
	<?php 
    }
}
function fwp_syndication_manage_page_links_table_rows($links, $visible = 'Y')
{
    $subscribed = 'Y' == strtoupper($visible);
    if ($subscribed or count($links) > 0) {
        ?>
	<table class="widefat<?php 
        if (!$subscribed) {
            ?>
 unsubscribed<?php 
        }
        ?>
">
	<thead>
	<tr>
	<th class="check-column" scope="col"><input type="checkbox" /></th>
	<th scope="col"><?php 
        _e('Name');
        ?>
</th>
	<th scope="col"><?php 
        _e('Feed');
        ?>
</th>
	<th scope="col"><?php 
        _e('Updated');
        ?>
</th>
	</tr>
	</thead>

	<tbody>
<?php 
        $alt_row = true;
        if (count($links) > 0) {
            foreach ($links as $link) {
                $trClass = array();
                // Prep: Get last updated timestamp
                $sLink = new SyndicatedLink($link->link_id);
                if (!is_null($sLink->setting('update/last'))) {
                    $lastUpdated = fwp_time_elapsed($sLink->setting('update/last'));
                } else {
                    $lastUpdated = __('None yet');
                }
                // Prep: get last error timestamp, if any
                if (is_null($sLink->setting('update/error'))) {
                    $errorsSince = '';
                } else {
                    $trClass[] = 'feed-error';
                    $theError = unserialize($sLink->setting('update/error'));
                    $errorsSince = "<div class=\"returning-errors\">" . "<p><strong>Returning errors</strong> since " . fwp_time_elapsed($theError['since']) . "</p>" . "<p>Most recent (" . fwp_time_elapsed($theError['ts']) . "):<br/><code>" . implode("</code><br/><code>", $theError['object']->get_error_messages()) . "</code></p>" . "</div>\n";
                }
                $nextUpdate = "<div style='font-style:italic;size:0.9em'>Ready for next update ";
                if (isset($sLink->settings['update/ttl']) and is_numeric($sLink->settings['update/ttl'])) {
                    if (isset($sLink->settings['update/timed']) and $sLink->settings['update/timed'] == 'automatically') {
                        $next = $sLink->settings['update/last'] + (int) $sLink->settings['update/ttl'] * 60;
                        $nextUpdate .= fwp_time_elapsed($next);
                    } else {
                        $nextUpdate .= "every " . $sLink->settings['update/ttl'] . " minute" . ($sLink->settings['update/ttl'] != 1 ? "s" : "");
                    }
                } else {
                    $nextUpdate .= "as soon as possible";
                }
                $nextUpdate .= "</div>";
                unset($sLink);
                $alt_row = !$alt_row;
                if ($alt_row) {
                    $trClass[] = 'alternate';
                }
                ?>
	<tr<?php 
                echo count($trClass) > 0 ? ' class="' . implode(" ", $trClass) . '"' : '';
                ?>
>
	<th class="check-column" scope="row"><input type="checkbox" name="link_ids[]" value="<?php 
                echo $link->link_id;
                ?>
" /></th>
				<?php 
                $hrefPrefix = "admin.php?link_id={$link->link_id}&amp;page=";
                $caption = strlen($link->link_rss) > 0 ? __('Switch Feed') : ($caption = __('Find Feed'));
                ?>
	<td>
	<strong><a href="<?php 
                echo $hrefPrefix . FWP_FEEDS_PAGE_SLUG;
                ?>
"><?php 
                print esc_html($link->link_name);
                ?>
</a></strong>
	<div class="row-actions"><?php 
                if ($subscribed) {
                    ?>
	<div><strong>Settings &gt;</strong>
	<a href="<?php 
                    echo $hrefPrefix . FWP_FEEDS_PAGE_SLUG;
                    ?>
"><?php 
                    _e('Feed');
                    ?>
</a>
	| <a href="<?php 
                    echo $hrefPrefix . FWP_POSTS_PAGE_SLUG;
                    ?>
"><?php 
                    _e('Posts');
                    ?>
</a>
	| <a href="<?php 
                    echo $hrefPrefix . FWP_AUTHORS_PAGE_SLUG;
                    ?>
"><?php 
                    _e('Authors');
                    ?>
</a>
	| <a href="<?php 
                    echo $hrefPrefix . FWP_CATEGORIES_PAGE_SLUG;
                    ?>
"><?php 
                    print htmlspecialchars(__('Categories' . FEEDWORDPRESS_AND_TAGS));
                    ?>
</a></div>
	<?php 
                }
                ?>

	<div><strong>Actions &gt;</strong>
	<?php 
                if ($subscribed) {
                    ?>
	<a href="<?php 
                    echo $hrefPrefix . FWP_SYNDICATION_PAGE_SLUG;
                    ?>
&amp;action=feedfinder"><?php 
                    echo $caption;
                    ?>
</a>
	<?php 
                } else {
                    ?>
	<a href="<?php 
                    echo $hrefPrefix . FWP_SYNDICATION_PAGE_SLUG;
                    ?>
&amp;action=<?php 
                    print FWP_RESUB_CHECKED;
                    ?>
"><?php 
                    _e('Re-subscribe');
                    ?>
</a>
	<?php 
                }
                ?>
	| <a href="<?php 
                echo $hrefPrefix . FWP_SYNDICATION_PAGE_SLUG;
                ?>
&amp;action=Unsubscribe"><?php 
                _e($subscribed ? 'Unsubscribe' : 'Delete permanently');
                ?>
</a>
	| <a href="<?php 
                print esc_html($link->link_url);
                ?>
"><?php 
                _e('View');
                ?>
</a></div>
	</div>
	</td>
				<?php 
                if (strlen($link->link_rss) > 0) {
                    ?>
	<td><a href="<?php 
                    echo esc_html($link->link_rss);
                    ?>
"><?php 
                    echo esc_html(feedwordpress_display_url($link->link_rss, 32));
                    ?>
</a></td>
				<?php 
                } else {
                    ?>
	<td class="feed-missing"><p><strong>no feed assigned</strong></p></td>
				<?php 
                }
                ?>

	<td><?php 
                print $lastUpdated;
                ?>
	<?php 
                print $errorsSince;
                ?>
	<?php 
                print $nextUpdate;
                ?>
	</td>
	</tr>
			<?php 
            }
        } else {
            ?>
<tr><td colspan="4"><p>There are no websites currently listed for syndication.</p></td></tr>
<?php 
        }
        ?>
</tbody>
</table>
	<?php 
    }
}