本文整理汇总了PHP中SimplePie::set_useragent方法的典型用法代码示例。如果您正苦于以下问题:PHP SimplePie::set_useragent方法的具体用法?PHP SimplePie::set_useragent怎么用?PHP SimplePie::set_useragent使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SimplePie
的用法示例。
在下文中一共展示了SimplePie::set_useragent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: tweetimport_import_twitter_feed
function tweetimport_import_twitter_feed($twitter_account)
{
require_once (ABSPATH . WPINC . '/class-feed.php');
$feed = new SimplePie();
$account_parts = explode ('/', $twitter_account['twitter_name'], 2);
if ($twitter_account['account_type'] == 1): //Account is Favorites
$feed->set_feed_url(str_replace('#=#USER#=#', $account_parts[0], TWEETIMPORT_API_FAVORITES_URL));
elseif ($twitter_account['account_type'] == 0 && count($account_parts) == 1): //User timeline
$feed->set_feed_url(str_replace('#=#USER#=#', $account_parts[0], TWEETIMPORT_API_USER_TIMELINE_URL));
elseif ($twitter_account['account_type'] == 2 && count($account_parts) == 2): //Account is list
$feed_url = str_replace('#=#USER#=#', $account_parts[0], TWEETIMPORT_API_LIST_URL);
$feed_url = str_replace('#=#LIST#=#', $account_parts[1], $feed_url);
$feed->set_feed_url($feed_url);
else :
return '<strong>ERROR: Account information not correct. Account type wrong?</strong>';
endif;
$feed->set_useragent('Tweet Import http://skinju.com/wordpress/tweetimport');
$feed->set_cache_class('WP_Feed_Cache');
$feed->set_file_class('WP_SimplePie_File');
$feed->enable_cache(true);
$feed->set_cache_duration (apply_filters('tweetimport_cache_duration', 880));
$feed->enable_order_by_date(false);
$feed->init();
$feed->handle_content_type();
if ($feed->error()):
return '<strong>ERROR: Feed Reading Error.</strong>';
endif;
$rss_items = $feed->get_items();
$imported_count = 0;
foreach ($rss_items as $item)
{
$item = apply_filters ('tweetimport_tweet_before_new_post', $item); //return false to stop processing an item.
if (!$item) continue;
$processed_description = $item->get_description();
//Get the twitter author from the beginning of the tweet text
$twitter_author = trim(preg_replace("~^(\w+):(.*?)$~", "\\1", $processed_description));
if ($twitter_account['strip_name'] == 1):
$processed_description = preg_replace("~^(\w+):(.*?)~i", "\\2", $processed_description);
endif;
if ($twitter_account['names_clickable'] == 1):
$processed_description = preg_replace("~@(\w+)~", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $processed_description);
$processed_description = preg_replace("~^(\w+):~", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>:", $processed_description);
endif;
if ($twitter_account['hashtags_clickable'] == 1):
if ($twitter_account['hashtags_clickable_twitter'] == 1):
$processed_description = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $processed_description);
else:
$processed_description = preg_replace("/#(\w+)/", "<a href=\"" . skinju_get_tag_link("\\1") . "\">#\\1</a>", $processed_description);
endif;
endif;
$processed_description = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $processed_description);
$processed_description = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $processed_description);
$new_post = array('post_title' => trim (substr (preg_replace("~{$account_parts[0]}: ~i", "", $item->get_title()), 0, 25) . '...'),
'post_content' => trim ($processed_description),
'post_date' => $item->get_date('Y-m-d H:i:s'),
'post_author' => $twitter_account['author'],
'post_category' => array($twitter_account['category']),
'post_status' => 'publish');
$new_post = apply_filters('tweetimport_new_post_before_create', $new_post); // Offer the chance to manipulate new post data. return false to skip
if (!$new_post) continue;
$new_post_id = wp_insert_post($new_post);
$imported_count++;
add_post_meta ($new_post_id, 'tweetimport_twitter_author', $twitter_author, true);
add_post_meta ($new_post_id, 'tweetimport_date_imported', date ('Y-m-d H:i:s'), true);
add_post_meta ($new_post_id, 'tweetimport_twitter_id', $item->get_id(), true);
add_post_meta ($new_post_id, 'tweetimport_twitter_id', $item->get_id(), true);
add_post_meta ($new_post_id, '_tweetimport_twitter_id_hash', $item->get_id(true), true);
add_post_meta ($new_post_id, 'tweetimport_twitter_post_uri', $item->get_link(0));
add_post_meta ($new_post_id, 'tweetimport_author_avatar', $item->get_link(0, 'image'));
preg_match_all ('~#([A-Za-z0-9_]+)(?=\s|\Z)~', $item->get_description(), $out);
if ($twitter_account['add_tag']) $out[0][] = $twitter_account['add_tag'];
wp_set_post_tags($new_post_id, implode (',', $out[0]));
}
return $imported_count;
}
示例2: rssmaker_plugin_action
function rssmaker_plugin_action($_, $myUser)
{
if ($_['action'] == 'show_folder_rss') {
header('Content-Type: text/xml; charset=utf-8');
$feedManager = new Feed();
$feeds = $feedManager->loadAll(array('folder' => $_['id']));
$items = array();
foreach ($feeds as $feed) {
$parsing = new SimplePie();
$parsing->set_feed_url($feed->getUrl());
$parsing->init();
$parsing->set_useragent('Mozilla/4.0 Leed (LightFeed Agregator) ' . VERSION_NAME . ' by idleman http://projet.idleman.fr/leed');
$parsing->handle_content_type();
// UTF-8 par défaut pour SimplePie
$items = array_merge($parsing->get_items(), $items);
}
$link = 'http://projet.idleman.fr/leed';
echo '<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/">
<channel>
<title>Leed dossier ' . $_['name'] . '</title>
<atom:link href="' . $link . '" rel="self" type="application/rss+xml"/>
<link>' . $link . '</link>
<description>Aggrégation des flux du dossier leed ' . $_['name'] . '</description>
<language>fr-fr</language>
<copyright>DWTFYW</copyright>
<pubDate>' . date('r', gmstrftime(time())) . '</pubDate>
<lastBuildDate>' . date('r', gmstrftime(time())) . '</lastBuildDate>
<sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<generator>Leed (LightFeed Agregator) ' . VERSION_NAME . '</generator>';
usort($items, 'rssmaker_plugin_compare');
foreach ($items as $item) {
echo '<item>
<title><![CDATA[' . $item->get_title() . ']]></title>
<link>' . $item->get_permalink() . '</link>
<pubDate>' . date('r', gmstrftime(strtotime($item->get_date()))) . '</pubDate>
<guid isPermaLink="true">' . $item->get_permalink() . '</guid>
<description>
<![CDATA[
' . $item->get_description() . '
]]>
</description>
<content:encoded><![CDATA[' . $item->get_content() . ']]></content:encoded>
<dc:creator>' . ('' == $item->get_author() ? 'Anonyme' : $item->get_author()->name) . '</dc:creator>
</item>';
}
echo '</channel></rss>';
}
}
示例3: SimplePie
function get_rss_feed($url)
{
require_once ABSPATH . WPINC . '/class-feed.php';
$feed = new SimplePie();
$feed->set_sanitize_class('WP_SimplePie_Sanitize_KSES');
$feed->sanitize = new WP_SimplePie_Sanitize_KSES();
$feed->set_useragent('Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36');
$feed->set_cache_class('WP_Feed_Cache');
$feed->set_file_class('WP_SimplePie_File');
$feed->set_feed_url($url);
$feed->set_cache_duration(apply_filters('wp_feed_cache_transient_lifetime', 12 * HOUR_IN_SECONDS, $url));
do_action_ref_array('wp_feed_options', array(&$feed, $url));
$feed->init();
$feed->handle_content_type();
if ($feed->error()) {
return new WP_Error('simplepie-error', $feed->error());
}
return $feed;
}
示例4: die
<?php
if (!isset($_GET['uid']) or !is_numeric($_GET['uid'])) {
die('Erreur: aucun id n\'a été spécifié!');
}
// Nécéssaire au bon déroulement de l'agrégation
set_time_limit(0);
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
// On charge SimplePie
include 'core/private/simplepie.php';
$simple = new SimplePie();
$simple->enable_cache(false);
// On désactive la mise en cache
$simple->set_useragent('Mozilla/5.0 (compatible; SimplePie.org; simple.tuxfamily.org)');
// User-Agent propre à SRR
$sqlite = new PDO('sqlite:core/private/data.db');
// On charge la base de données
$query = $sqlite->query('SELECT id,url,last_check FROM feeds WHERE user_id=' . $sqlite->quote($_GET['uid']));
// On récupère la liste des flux
$time = time();
while ($response = $query->fetch()) {
if ($time > $response['last_check'] + 600) {
$feed_id = $response['id'];
$simple->set_feed_url($response['url']);
$simple->init();
$simple->handle_content_type();
$error = 0;
if ($simple->error()) {
$error = 1;
}
foreach ($simple->get_items() as $item) {
示例5: add_feed
/**
* Add a new feed to the database
*
* Adds the specified feed name and URL to the global <tt>$data</tt> array. If no name is set
* by the user, it fetches one from the feed. If the URL specified is a HTML page and not a
* feed, it lets SimplePie do autodiscovery and uses the XML url returned.
*
* @since 1.0
* @uses $data Contains all feeds, this is what we add the new feed to
*
* @param string $url URL to feed or website (if autodiscovering)
* @param string $name Title/Name of feed
* @param string $cat Category to add feed to
* @param bool $return If true, return the new feed's details. Otherwise, use the global $data array
* @return bool True if succeeded, false if failed
*/
function add_feed($url, $name = '', $cat = 'default', $return = false)
{
if (empty($url)) {
throw new Exception(_r("Couldn't add feed: No feed URL supplied"), Errors::get_code('admin.feeds.no_url'));
}
require_once LILINA_INCPATH . '/contrib/simplepie/simplepie.inc';
$feed_info = new SimplePie();
$feed_info->set_useragent('Lilina/' . LILINA_CORE_VERSION . '; (' . get_option('baseurl') . '; http://getlilina.org/; Allow Like Gecko) SimplePie/' . SIMPLEPIE_BUILD);
$feed_info->set_stupidly_fast(true);
$feed_info->enable_cache(false);
$feed_info->set_feed_url(urldecode($url));
$feed_info->init();
$feed_error = $feed_info->error();
$feed_url = $feed_info->subscribe_url();
if (!empty($feed_error)) {
//No feeds autodiscovered;
throw new Exception(sprintf(_r("Couldn't add feed: %s is not a valid URL or the server could not be accessed. Additionally, no feeds could be found by autodiscovery."), $url), Errors::get_code('admin.feeds.invalid_url'));
}
if (empty($name)) {
//Get it from the feed
$name = $feed_info->get_title();
}
if ($return === true) {
return array('feed' => $feed_url, 'url' => $feed_info->get_link(), 'name' => $name, 'cat' => $cat);
}
global $data;
$data['feeds'][] = array('feed' => $feed_url, 'url' => $feed_info->get_link(), 'name' => $name, 'cat' => $cat);
save_feeds();
return sprintf(_r('Added feed "%1$s"'), $name);
}
示例6: check_for_update
function check_for_update($link)
{
$releases_feed = "http://tt-rss.org/releases.rss";
if (!CHECK_FOR_NEW_VERSION || $_SESSION["access_level"] < 10) {
return;
}
error_reporting(0);
if (ENABLE_SIMPLEPIE) {
$rss = new SimplePie();
$rss->set_useragent(SIMPLEPIE_USERAGENT . MAGPIE_USER_AGENT_EXT);
// $rss->set_timeout(MAGPIE_FETCH_TIME_OUT);
$rss->set_feed_url($fetch_url);
$rss->set_output_encoding('UTF-8');
$rss->init();
} else {
$rss = fetch_rss($releases_feed);
}
error_reporting(DEFAULT_ERROR_LEVEL);
if ($rss) {
if (ENABLE_SIMPLEPIE) {
$items = $rss->get_items();
} else {
$items = $rss->items;
if (!$items || !is_array($items)) {
$items = $rss->entries;
}
if (!$items || !is_array($items)) {
$items = $rss;
}
}
if (!is_array($items) || count($items) == 0) {
return;
}
$latest_item = $items[0];
if (ENABLE_SIMPLEPIE) {
$last_title = $latest_item->get_title();
} else {
$last_title = $latest_item["title"];
}
$latest_version = trim(preg_replace("/(Milestone)|(completed)/", "", $last_title));
if (ENABLE_SIMPLEPIE) {
$release_url = sanitize_rss($link, $latest_item->get_link());
$content = sanitize_rss($link, $latest_item->get_description());
} else {
$release_url = sanitize_rss($link, $latest_item["link"]);
$content = sanitize_rss($link, $latest_item["description"]);
}
if (version_compare(VERSION, $latest_version) == -1) {
return sprintf("New version of Tiny-Tiny RSS (%s) is available:", $latest_version) . "<div class='milestoneDetails'>{$content}</div>";
} else {
return false;
}
}
}
示例7: upgrade_single
protected function upgrade_single($feed)
{
require_once LILINA_INCPATH . '/contrib/simplepie.class.php';
$sp = new SimplePie();
$sp->set_useragent(LILINA_USERAGENT . ' SimplePie/' . SIMPLEPIE_BUILD);
$sp->set_stupidly_fast(true);
$sp->set_cache_location(get_option('cachedir'));
$sp->set_favicon_handler(get_option('baseurl') . '/lilina-favicon.php');
$sp->set_feed_url($feed['feed']);
$sp->init();
if (!isset($feed['icon'])) {
$feed['icon'] = $sp->get_favicon();
}
return $feed;
}
示例8: updateRSS
function updateRSS()
{
$db = DBCxn::get();
$selectRSS = $db->query("SELECT id, rssLink, updateMd5 FROM rss");
$selectRSS->setFetchMode(PDO::FETCH_ASSOC);
$selectRSS = $selectRSS->fetchAll();
//构建分析
$feed = new SimplePie();
$feed->enable_order_by_date(false);
$feed->enable_cache(true);
$feed->set_useragent('Mozilla/4.0 ' . SIMPLEPIE_USERAGENT);
$feed->set_cache_location($_SERVER['DOCUMENT_ROOT'] . '/cache');
//拿出每个RSS调用分析函数
foreach ($selectRSS as $rows) {
$rssId = $rows['id'];
//博客ID
$updateMd5 = $rows['updateMd5'];
//最后更新记录的md5值
$feed->set_feed_url($rows['rssLink']);
//feed地址做参数进行解析操作
$feed->set_timeout(30);
$feed->init();
//如果feed出错,执行下一个
if ($feed->error()) {
continue;
}
readRSS($rssId, $updateMd5, $feed);
}
return true;
}
示例9: exit
/**
* Only permit execution from the command-line.
*/
if (php_sapi_name() !== 'cli') {
echo "This script must be called from the command line.";
exit(1);
}
require_once __DIR__ . '/vendor/autoload.php';
/**
* Get the feed list and set up SimplePie.
*/
$simplepie = new SimplePie();
$feedUrls = array_filter(file(__DIR__ . '/feeds.csv', FILE_IGNORE_NEW_LINES));
$simplepie->set_feed_url($feedUrls);
$ua = 'Mozilla/4.0 (compatible; Sourdust Feed Aggregator https://github.com/samwilson/sourdust-feed-aggregator)';
$simplepie->set_useragent($ua);
/**
* Set up caching.
*/
$cacheDir = __DIR__ . '/cache';
if (!is_dir($cacheDir)) {
mkdir($cacheDir);
}
$simplepie->set_cache_location($cacheDir);
/**
* Run the actual feed aggregation and check for errors.
*/
$simplepie->init();
if ($simplepie->error()) {
echo "Errors:\n " . join("\n ", $simplepie->error()) . "\n";
}
示例10: SimplePie
/**
* Load and process a feed using SimplePie
*
* @param string $feed Feed detail array, as returned by Feeds::get()
* @return SimplePie
*/
public static function &load_feed($feed)
{
// This loads the useragent
class_exists('HTTPRequest');
global $lilina;
$sp = new SimplePie();
$sp->set_useragent(LILINA_USERAGENT . ' SimplePie/' . SIMPLEPIE_BUILD);
$sp->set_stupidly_fast(true);
$sp->set_cache_location(get_option('cachedir'));
//$sp->set_cache_duration(0);
$sp = apply_filters('simplepie-config', $sp);
$sp->set_feed_url($feed['feed']);
$sp->init();
/** We need this so we have something to work with. */
$sp->get_items();
if (!isset($sp->data['ordered_items'])) {
$sp->data['ordered_items'] = $sp->data['items'];
}
/** Let's force sorting */
usort($sp->data['ordered_items'], array(&$sp, 'sort_items'));
usort($sp->data['items'], array(&$sp, 'sort_items'));
do_action_ref_array('iu-load-feed', array(&$sp, $feed));
return $sp;
}
示例11: customSimplePie
function customSimplePie()
{
$simplePie = new SimplePie();
$simplePie->set_useragent(Minz_Translate::t('freshrss') . '/' . FRESHRSS_VERSION . ' (' . PHP_OS . '; ' . FRESHRSS_WEBSITE . ') ' . SIMPLEPIE_NAME . '/' . SIMPLEPIE_VERSION);
$simplePie->set_cache_location(CACHE_PATH);
$simplePie->set_cache_duration(1500);
$simplePie->strip_htmltags(array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'link', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'plaintext', 'script', 'style'));
$simplePie->strip_attributes(array_merge($simplePie->strip_attributes, array('autoplay', 'onload', 'onunload', 'onclick', 'ondblclick', 'onmousedown', 'onmouseup', 'onmouseover', 'onmousemove', 'onmouseout', 'onfocus', 'onblur', 'onkeypress', 'onkeydown', 'onkeyup', 'onselect', 'onchange', 'seamless')));
$simplePie->add_attributes(array('img' => array('lazyload' => ''), 'audio' => array('preload' => 'none'), 'iframe' => array('postpone' => '', 'sandbox' => 'allow-scripts allow-same-origin'), 'video' => array('postpone' => '', 'preload' => 'none')));
$simplePie->set_url_replacements(array('a' => 'href', 'area' => 'href', 'audio' => 'src', 'blockquote' => 'cite', 'del' => 'cite', 'form' => 'action', 'iframe' => 'src', 'img' => array('longdesc', 'src'), 'input' => 'src', 'ins' => 'cite', 'q' => 'cite', 'source' => 'src', 'track' => 'src', 'video' => array('poster', 'src')));
return $simplePie;
}
示例12: fetch_feed
private function fetch_feed($url)
{
require_once ABSPATH . WPINC . '/class-feed.php';
$feed = new SimplePie();
$feed->set_sanitize_class('WP_SimplePie_Sanitize_KSES');
// We must manually overwrite $feed->sanitize because SimplePie's
// constructor sets it before we have a chance to set the sanitization class
$feed->sanitize = new WP_SimplePie_Sanitize_KSES();
$feed->set_cache_class('WP_Feed_Cache');
$feed->set_file_class('WP_SimplePie_File');
$feed->set_feed_url($url);
$feed->set_cache_duration(apply_filters('wp_feed_cache_transient_lifetime', 12 * HOUR_IN_SECONDS, $url));
do_action_ref_array('wp_feed_options', array(&$feed, $url));
$feed->set_useragent(self::USER_AGENT);
$feed->init();
$feed->handle_content_type();
if ($feed->error()) {
return new WP_Error('simplepie-error', $feed->error());
}
return $feed;
}
示例13: COM_rdfImport
/**
* Syndication import function. Imports headline data to a portal block.
*
* Rewritten December 19th 2004 by Michael Jervis (mike@*censored*ingbrit.com). Now
* utilises a Factory Pattern to open a URL and automaticaly retreive a feed
* object populated with feed data. Then import it into the portal block.
*
* @param string $bid Block ID
* @param string $rdfurl URL to get content from
* @param int $maxheadlines Maximum number of headlines to display
* @return void
* @see function COM_rdfCheck
*
*/
function COM_rdfImport($bid, $rdfurl, $maxheadlines = 0)
{
global $_CONF, $_TABLES, $LANG21;
require_once $_CONF['path'] . '/lib/simplepie/autoloader.php';
$result = DB_query("SELECT rdf_last_modified, rdf_etag FROM {$_TABLES['blocks']} WHERE bid = " . (int) $bid);
list($last_modified, $etag) = DB_fetchArray($result);
// Load the actual feed handlers:
$feed = new SimplePie();
$feed->set_useragent('glFusion/' . GVERSION . ' ' . SIMPLEPIE_USERAGENT);
$feed->set_feed_url($rdfurl);
$feed->set_cache_location($_CONF['path'] . '/data/layout_cache');
$rc = $feed->init();
if ($rc == true) {
$feed->handle_content_type();
/* We have located a reader, and populated it with the information from
* the syndication file. Now we will sort out our display, and update
* the block.
*/
if ($maxheadlines == 0) {
if (!empty($_CONF['syndication_max_headlines'])) {
$maxheadlines = $_CONF['syndication_max_headlines'];
}
}
if ($maxheadlines == 0) {
$number_of_items = $feed->get_item_quantity();
} else {
$number_of_items = $feed->get_item_quantity($maxheadlines);
}
$etag = '';
$update = date('Y-m-d H:i:s');
$last_modified = $update;
$last_modified = DB_escapeString($last_modified);
if (empty($last_modified)) {
DB_query("UPDATE {$_TABLES['blocks']} SET rdfupdated = '{$update}', rdf_last_modified = NULL, rdf_etag = NULL WHERE bid = " . (int) $bid);
} else {
DB_query("UPDATE {$_TABLES['blocks']} SET rdfupdated = '{$update}', rdf_last_modified = '{$last_modified}', rdf_etag = '{$etag}' WHERE bid = " . (int) $bid);
}
for ($i = 0; $i < $number_of_items; $i++) {
$item = $feed->get_item($i);
$title = $item->get_title();
if (empty($title)) {
$title = $LANG21[61];
}
$link = $item->get_permalink();
$enclosure = $item->get_enclosure();
if ($link != '') {
$content = COM_createLink($title, $link, $attr = array('target' => '_blank'));
} elseif ($enclosure != '') {
$content = COM_createLink($title, $enclosure, $attr = array('target' => '_blank'));
} else {
$content = $title;
}
$articles[] = $content;
}
// build a list
$content = COM_makeList($articles, 'list-feed');
$content = str_replace(array("\r", "\n"), '', $content);
if (strlen($content) > 65000) {
$content = $LANG21[68];
}
// Standard theme based function to put it in the block
$result = DB_change($_TABLES['blocks'], 'content', DB_escapeString($content), 'bid', (int) $bid);
} else {
$err = $feed->error();
COM_errorLog($err);
$content = DB_escapeString($err);
DB_query("UPDATE {$_TABLES['blocks']} SET content = '{$content}', rdf_last_modified = NULL, rdf_etag = NULL WHERE bid = " . (int) $bid);
}
}
示例14: parse
function parse($syncId, &$nbEvents = 0, $enableCache = true, $forceFeed = false)
{
$nbEvents = 0;
assert('is_int($syncId) && $syncId>0');
if (empty($this->id) || 0 == $this->id) {
/* Le flux ne dispose pas pas d'id !. Ça arrive si on appelle
parse() sans avoir appelé save() pour un nouveau flux.
@TODO: un create() pour un nouveau flux ? */
$msg = 'Empty or null id for a feed! ' . 'See ' . __FILE__ . ' on line ' . __LINE__;
error_log($msg, E_USER_ERROR);
die($msg);
// Arrêt, sinon création événements sans flux associé.
}
$feed = new SimplePie();
$feed->enable_cache($enableCache);
$feed->force_feed($forceFeed);
$feed->set_feed_url($this->url);
$feed->set_useragent('Mozilla/4.0 Leed (LightFeed Aggregator) ' . VERSION_NAME . ' by idleman http://projet.idleman.fr/leed');
if (!$feed->init()) {
$this->error = $feed->error;
$this->lastupdate = $_SERVER['REQUEST_TIME'];
$this->save();
return false;
}
$feed->handle_content_type();
// UTF-8 par défaut pour SimplePie
if ($this->name == '') {
$this->name = $feed->get_title();
}
if ($this->name == '') {
$this->name = $this->url;
}
$this->website = $feed->get_link();
$this->description = $feed->get_description();
$items = $feed->get_items();
$eventManager = new Event();
$events = array();
$iEvents = 0;
foreach ($items as $item) {
// Ne retient que les 100 premiers éléments de flux.
if ($iEvents++ >= 100) {
break;
}
// Si le guid existe déjà, on évite de le reparcourir.
$alreadyParsed = $eventManager->load(array('guid' => $item->get_id(), 'feed' => $this->id));
if (isset($alreadyParsed) && $alreadyParsed != false) {
$events[] = $alreadyParsed->getId();
continue;
}
// Initialisation des informations de l'événement (élt. de flux)
$event = new Event();
$event->setSyncId($syncId);
$event->setGuid($item->get_id());
$event->setTitle($item->get_title());
$event->setPubdate($item->get_date());
$event->setCreator('' == $item->get_author() ? '' : $item->get_author()->name);
$event->setLink($item->get_permalink());
$event->setFeed($this->id);
$event->setUnread(1);
// inexistant, donc non-lu
//Gestion de la balise enclosure pour les podcasts et autre cochonneries :)
$enclosure = $item->get_enclosure();
if ($enclosure != null && $enclosure->link != '') {
$enclosureName = substr($enclosure->link, strrpos($enclosure->link, '/') + 1, strlen($enclosure->link));
$enclosureArgs = strpos($enclosureName, '?');
if ($enclosureArgs !== false) {
$enclosureName = substr($enclosureName, 0, $enclosureArgs);
}
$enclosureFormat = isset($enclosure->handler) ? $enclosure->handler : substr($enclosureName, strrpos($enclosureName, '.') + 1);
$enclosure = '<div class="enclosure"><h1>Fichier média :</h1><a href="' . $enclosure->link . '"> ' . $enclosureName . '</a> <span>(Format ' . strtoupper($enclosureFormat) . ', ' . Functions::convertFileSize($enclosure->length) . ')</span></div>';
} else {
$enclosure = '';
}
$event->setContent($item->get_content() . $enclosure);
$event->setDescription($item->get_description() . $enclosure);
if (trim($event->getDescription()) == '') {
$event->setDescription(substr($event->getContent(), 0, 300) . '…<br><a href="' . $event->getLink() . '">Lire la suite de l\'article</a>');
}
if (trim($event->getContent()) == '') {
$event->setContent($event->getDescription());
}
$event->setCategory($item->get_category());
$event->save();
$nbEvents++;
}
$listid = "";
foreach ($events as $item) {
$listid .= ',' . $item;
}
$query = 'UPDATE `' . MYSQL_PREFIX . 'event` SET syncId=' . $syncId . ' WHERE id in (0' . $listid . ');';
$myQuery = $this->customQuery($query);
$this->lastupdate = $_SERVER['REQUEST_TIME'];
$this->save();
return true;
}
示例15: update_rss_feed
function update_rss_feed($link, $feed, $ignore_daemon = false, $no_cache = false, $override_url = false)
{
require_once "lib/simplepie/simplepie.inc";
require_once "lib/magpierss/rss_fetch.inc";
require_once 'lib/magpierss/rss_utils.inc';
$debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
if (!$_REQUEST["daemon"] && !$ignore_daemon) {
return false;
}
if ($debug_enabled) {
_debug("update_rss_feed: start");
}
if (!$ignore_daemon) {
if (DB_TYPE == "pgsql") {
$updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '120 seconds')";
} else {
$updstart_thresh_qpart = "(ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 120 SECOND))";
}
$result = db_query($link, "SELECT id,update_interval,auth_login,\n\t\t\t\tauth_pass,cache_images,update_method,last_updated\n\t\t\t\tFROM ttrss_feeds WHERE id = '{$feed}' AND {$updstart_thresh_qpart}");
} else {
$result = db_query($link, "SELECT id,update_interval,auth_login,\n\t\t\t\tfeed_url,auth_pass,cache_images,update_method,last_updated,\n\t\t\t\tmark_unread_on_update, owner_uid, update_on_checksum_change,\n\t\t\t\tpubsub_state\n\t\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'");
}
if (db_num_rows($result) == 0) {
if ($debug_enabled) {
_debug("update_rss_feed: feed {$feed} NOT FOUND/SKIPPED");
}
return false;
}
$update_method = db_fetch_result($result, 0, "update_method");
$last_updated = db_fetch_result($result, 0, "last_updated");
$owner_uid = db_fetch_result($result, 0, "owner_uid");
$mark_unread_on_update = sql_bool_to_bool(db_fetch_result($result, 0, "mark_unread_on_update"));
$update_on_checksum_change = sql_bool_to_bool(db_fetch_result($result, 0, "update_on_checksum_change"));
$pubsub_state = db_fetch_result($result, 0, "pubsub_state");
db_query($link, "UPDATE ttrss_feeds SET last_update_started = NOW()\n\t\t\tWHERE id = '{$feed}'");
$auth_login = db_fetch_result($result, 0, "auth_login");
$auth_pass = db_fetch_result($result, 0, "auth_pass");
if ($update_method == 0) {
$update_method = DEFAULT_UPDATE_METHOD + 1;
}
// 1 - Magpie
// 2 - SimplePie
// 3 - Twitter OAuth
if ($update_method == 2) {
$use_simplepie = true;
} else {
$use_simplepie = false;
}
if ($debug_enabled) {
_debug("update method: {$update_method} (feed setting: {$update_method}) (use simplepie: {$use_simplepie})\n");
}
if ($update_method == 1) {
$auth_login = urlencode($auth_login);
$auth_pass = urlencode($auth_pass);
}
$cache_images = sql_bool_to_bool(db_fetch_result($result, 0, "cache_images"));
$fetch_url = db_fetch_result($result, 0, "feed_url");
$feed = db_escape_string($feed);
if ($auth_login && $auth_pass) {
$url_parts = array();
preg_match("/(^[^:]*):\\/\\/(.*)/", $fetch_url, $url_parts);
if ($url_parts[1] && $url_parts[2]) {
$fetch_url = $url_parts[1] . "://{$auth_login}:{$auth_pass}@" . $url_parts[2];
}
}
if ($override_url) {
$fetch_url = $override_url;
}
if ($debug_enabled) {
_debug("update_rss_feed: fetching [{$fetch_url}]...");
}
// Ignore cache if new feed or manual update.
$cache_age = is_null($last_updated) || $last_updated == '1970-01-01 00:00:00' ? -1 : get_feed_update_interval($link, $feed) * 60;
if ($update_method == 3) {
$rss = fetch_twitter_rss($link, $fetch_url, $owner_uid);
} else {
if ($update_method == 1) {
define('MAGPIE_CACHE_AGE', $cache_age);
define('MAGPIE_CACHE_ON', !$no_cache);
define('MAGPIE_FETCH_TIME_OUT', 60);
define('MAGPIE_CACHE_DIR', CACHE_DIR . "/magpie");
$rss = @fetch_rss($fetch_url);
} else {
$simplepie_cache_dir = CACHE_DIR . "/simplepie";
if (!is_dir($simplepie_cache_dir)) {
mkdir($simplepie_cache_dir);
}
$rss = new SimplePie();
$rss->set_useragent(SELF_USER_AGENT);
# $rss->set_timeout(10);
$rss->set_feed_url($fetch_url);
$rss->set_output_encoding('UTF-8');
//$rss->force_feed(true);
if ($debug_enabled) {
_debug("feed update interval (sec): " . get_feed_update_interval($link, $feed) * 60);
}
$rss->enable_cache(!$no_cache);
if (!$no_cache) {
$rss->set_cache_location($simplepie_cache_dir);
$rss->set_cache_duration($cache_age);
//.........这里部分代码省略.........