예제 #1
1
<?php

/*
 *	
 *		Basic LastFM Data Dump
 *		This file will download your last.fm public data
 *
 */
header('Content-type: text/plain');
include 'class.feedparser.php';
$feed = new FeedParser();
$limit = 1;
$user = '******';
$stream = 'user.getrecenttracks';
$data = $feed->lastfm($user, $stream, $limit);
$fh = fopen('lastfm.log', 'w');
fwrite($fh, print_r($data, 1));
fclose($fh);
echo "Downloaded " . count($data['posts']) . " posts\n";
echo "Bandwidth Usage: {$feed->bandwidth}\n";
echo "Requests: {$feed->requests}\n";
echo "\n";
if ($_SERVER['HTTP_USER_AGENT']) {
    print_r($data);
}
예제 #2
0
 function execute(&$controller, &$request, &$user)
 {
     $member = $user->getAttribute('member', GLU_NS);
     // my feeds
     $source = DB_DataObject::factory('source');
     $source->whereAdd('member_id = ' . $source->escape($member->id));
     if ($request->hasParameter('id')) {
         $source->whereAdd('id = ' . $source->escape($request->getParameter('id')));
     }
     $source->find();
     $feeds = array();
     while ($source->fetch()) {
         $rss = new FeedParser($source->uri);
         $rss->parse();
         foreach ($rss->getItems() as $item) {
             $feed['id'] = $source->id;
             $feed['title'] = $item['title'];
             $feed['link'] = $item['link'];
             $feed['description'] = isset($item['description']) ? $item['description'] : '';
             $feed['date'] = isset($item['dc:date']) ? $item['dc:date'] : (isset($item['date']) ? $item['date'] : '');
             $feeds[] = $feed;
         }
     }
     $haj = new HTML_AJAX_JSON();
     $output = $haj->encode($feeds);
     header('Content-Type: application/x-javascript; charset=utf-8');
     echo $output;
     return VIEW_NONE;
 }
예제 #3
0
 function testAtom03()
 {
     $uri = 'http://plnet.jp/test_feed/blogger-atom03.xml';
     $feed = new FeedParser($uri);
     $feed->parse();
     $this->assertEquals('p0t blogger', $feed->getTitle());
     $this->assertEquals('http://komagata.blogspot.com', $feed->getLink());
     $this->assertEquals('http://komagata.blogspot.com/favicon.ico', $feed->getFavicon());
     //print_r($feed->data);
 }
예제 #4
0
/**
 * MyBB 1.8
 * Copyright 2014 MyBB Group, All Rights Reserved
 *
 * Website: http://www.mybb.com
 * License: http://www.mybb.com/about/license
 *
 */
function task_versioncheck($task)
{
    global $cache, $lang, $mybb;
    $current_version = rawurlencode($mybb->version_code);
    $updated_cache = array('last_check' => TIME_NOW);
    // Check for the latest version
    require_once MYBB_ROOT . 'inc/class_xml.php';
    $contents = fetch_remote_file("http://www.mybb.com/version_check.php");
    if (!$contents) {
        add_task_log($task, $lang->task_versioncheck_ran_errors);
        return false;
    }
    $pos = strpos($contents, "<");
    if ($pos > 1) {
        $contents = substr($contents, $pos);
    }
    $pos = strpos(strrev($contents), ">");
    if ($pos > 1) {
        $contents = substr($contents, 0, -1 * ($pos - 1));
    }
    $parser = new XMLParser($contents);
    $tree = $parser->get_tree();
    $latest_code = (int) $tree['mybb']['version_code']['value'];
    $latest_version = "<strong>" . htmlspecialchars_uni($tree['mybb']['latest_version']['value']) . "</strong> (" . $latest_code . ")";
    if ($latest_code > $mybb->version_code) {
        $latest_version = "<span style=\"color: #C00;\">" . $latest_version . "</span>";
        $version_warn = 1;
        $updated_cache['latest_version'] = $latest_version;
        $updated_cache['latest_version_code'] = $latest_code;
    } else {
        $latest_version = "<span style=\"color: green;\">" . $latest_version . "</span>";
    }
    // Check for the latest news
    require_once MYBB_ROOT . "inc/class_feedparser.php";
    $feed_parser = new FeedParser();
    $feed_parser->parse_feed("http://feeds.feedburner.com/MyBBDevelopmentBlog");
    $updated_cache['news'] = array();
    require_once MYBB_ROOT . '/inc/class_parser.php';
    $post_parser = new postParser();
    if ($feed_parser->error == '') {
        foreach ($feed_parser->items as $item) {
            if (isset($updated_cache['news'][2])) {
                break;
            }
            $description = $item['description'];
            $description = $post_parser->parse_message($description, array('allow_html' => true));
            $description = preg_replace('#<img(.*)/>#', '', $description);
            $updated_cache['news'][] = array('title' => htmlspecialchars_uni($item['title']), 'description' => $description, 'link' => htmlspecialchars_uni($item['link']), 'author' => htmlspecialchars_uni($item['author']), 'dateline' => $item['date_timestamp']);
        }
    }
    $cache->update("update_check", $updated_cache);
    add_task_log($task, $lang->task_versioncheck_ran);
}
예제 #5
0
 function execute(&$controller, &$request, &$user)
 {
     $uri = $request->getParameter('uri');
     $feed = new FeedParser($uri);
     $response = '';
     if ($feed->isValid() === false) {
         $response = 'false';
     } else {
         $response = 'true';
     }
     header('Content-Type: text/plain; charset=utf-8');
     echo $response;
     return VIEW_NONE;
 }
예제 #6
0
 function parse()
 {
     $feed = DB_DataObject::factory('feed');
     $feed->uri = $this->uri;
     // was cached
     if ($feed->count() > 0) {
         $this->struct = $this->_getCache($this->uri);
         // no cache
     } else {
         $f = new FeedParser($this->uri);
         $f->parse();
         $this->struct = $f->toArray();
     }
 }
예제 #7
0
 public function executeRefresh()
 {
     $post = PostPeer::retrieveByPK($this->getRequestParameter('id'));
     $blog = $post->getBlog();
     $this->forward404Unless($blog->getId() == $this->getUser()->getId());
     if ($post) {
         try {
             $items = FeedParser::parse($blog->getFeed());
             foreach ($items as $item) {
                 if ($item->link == $post->getLink()) {
                     $post->removeTags();
                     foreach ($item->tags as $name) {
                         $tag = TagPeer::retriveByName($name, true);
                         $post->addTag($tag);
                     }
                     if ($post->hasTags()) {
                         $shortened = $post->setFullContent($item->content);
                         $post->setLink($item->link);
                         $post->setTitle($item->title);
                         $post->setCreatedAt($item->pubdate);
                         $post->setShortened($shortened);
                         $post->save();
                     }
                     break;
                 }
             }
             $this->setFlash('updated', 'Wpis został odświeżony.');
         } catch (Exception $e) {
             $this->setFlash('updated', 'Odswieżanie wpisu nie powiodło się.');
         }
     }
     $this->redirect('ucp/index');
 }
예제 #8
0
 /**
  * Displays a static page.
  */
 function display()
 {
     $path = func_get_args();
     $count = count($path);
     if (!$count) {
         $this->redirect('/');
     }
     $page = $subpage = $title_for_layout = null;
     if (!empty($path[0])) {
         $page = $path[0];
     }
     if (!empty($path[1])) {
         $subpage = $path[1];
     }
     if (!empty($path[$count - 1])) {
         $this->title_for_layout = Inflector::humanize($path[$count - 1]);
         if ($this->title_for_layout == 'Home') {
             $this->title_for_layout = '';
         }
     }
     App::import('Vendor', 'feedparser/feedparser');
     $Parser = new FeedParser();
     $Parser->parse('http://blog.simpleve.com/feed/');
     $items = $Parser->getItems();
     $this->set('blogrss', $items);
     $Parser = new FeedParser();
     $Parser->parse('http://www.eveonline.com/feed/rdfdevblog.asp');
     $items = $Parser->getItems();
     $this->set('evedevblogrss', $items);
     $motd = file_get_contents('http://www.eveonline.com/motd.asp?s=xml');
     $motd = trim(str_replace('MOTD', '', $motd));
     $motd = trim(str_replace('shellexec:', '', $motd));
     $motd = trim(str_replace('<center>', '', $motd));
     $motd = trim(str_replace('</center>', '', $motd));
     $this->set('evemotd', $motd);
     $this->set(compact('page', 'subpage', 'title_for_layout'));
     $this->render(implode('/', $path));
 }
예제 #9
0
 function subscribeRoute($feedUrl, $parentFolderId)
 {
     // Check to see if the system already has the feed
     $storage = Storage::getInstance();
     $feed = $storage->getFeed($feedUrl);
     if (!$feed) {
         $matches = $storage->findFeedFromLinks($feedUrl);
         if (count($matches) > 0) {
             $feed = $matches[0];
         }
         // TODO: allow selection if > 1
     }
     if (!$feed) {
         // Not in the system. Fetch it from www
         // Check URL for validity
         if (!filter_var($feedUrl, FILTER_VALIDATE_URL)) {
             throw new JsonError(l("Incorrect or unrecognized URL"));
         }
         // Fetch and parse the feed
         try {
             $parser = FeedParser::create($feedUrl, true);
         } catch (Exception $e) {
             throw new JsonError(l("Could not read contents of feed"));
         }
         if (!$parser) {
             throw new JsonError(l("Could not determine type of feed"));
         }
         try {
             $feed = $parser->parse();
         } catch (Exception $e) {
             throw new JsonError(l("Could not parse the contents of the feed"));
         }
         // Import the feed contents
         $feed->id = $storage->importFeed($this->user->id, $feed);
         if ($feed->id === false) {
             throw new JsonError(l("An error occurred while adding feed"));
         }
         // Import any links
         $links = $parser->getLinks();
         if (!in_array($feed->link, $links)) {
             $links[] = $feed->link;
         }
         $storage->addLinks($feed->id, $links);
     }
     // Subscribe to feed
     if (!$storage->subscribeToFeed($this->user->id, $feed->id, $parentFolderId)) {
         throw new JsonError(l("Could not subscribe to feed"));
     }
     return array("feed" => array("title" => $feed->title), "allItems" => $storage->getUserFeeds($this->user));
 }
예제 #10
0
파일: Crawler.php 프로젝트: huluwa/grr
 private function parseFeed($feedUrl)
 {
     $now = microtime(true);
     $parser = FeedParser::create($feedUrl);
     $this->secondsSpentDownloading += microtime(true) - $now;
     if (!$parser) {
         throw new Exception("Could not determine type of feed from content");
     }
     $now = microtime(true);
     echo "  (-) parsing (" . get_class($parser) . ") ... ";
     $feed = $parser->parse();
     $secondsSpentParsingFeed = microtime(true) - $now;
     $this->secondsSpentParsing += $secondsSpentParsingFeed;
     echo sprintf("done! (%.04fs)\n", $secondsSpentParsingFeed);
     return $feed;
 }
 /**
  * Loads images from a MediaRSS or ATOM feed
  */
 function _loadRSS($url)
 {
     require_once DOKU_INC . 'inc/FeedParser.php';
     $feed = new FeedParser();
     $feed->set_feed_url($url);
     $feed->init();
     $files = array();
     // base url to use for broken feeds with non-absolute links
     $main = parse_url($url);
     $host = $main['scheme'] . '://' . $main['host'] . ($main['port'] ? ':' . $main['port'] : '');
     $path = dirname($main['path']) . '/';
     foreach ($feed->get_items() as $item) {
         if ($enclosure = $item->get_enclosure()) {
             // skip non-image enclosures
             if ($enclosure->get_type()) {
                 if (substr($enclosure->get_type(), 0, 5) != 'image') {
                     continue;
                 }
             } else {
                 if (!preg_match('/\\.(jpe?g|png|gif)(\\?|$)/i', $enclosure->get_link())) {
                     continue;
                 }
             }
             // non absolute links
             $ilink = $enclosure->get_link();
             if (!preg_match('/^https?:\\/\\//i', $ilink)) {
                 if ($ilink[0] == '/') {
                     $ilink = $host . $ilink;
                 } else {
                     $ilink = $host . $path . $ilink;
                 }
             }
             $link = $item->link;
             if (!preg_match('/^https?:\\/\\//i', $link)) {
                 if ($link[0] == '/') {
                     $link = $host . $link;
                 } else {
                     $link = $host . $path . $link;
                 }
             }
             $files[] = array('id' => $ilink, 'isimg' => true, 'file' => basename($ilink), 'title' => SimplePie_Misc::htmlspecialchars_decode($enclosure->get_title(), ENT_COMPAT), 'desc' => strip_tags(SimplePie_Misc::htmlspecialchars_decode($enclosure->get_description(), ENT_COMPAT)), 'width' => $enclosure->get_width(), 'height' => $enclosure->get_height(), 'mtime' => $item->get_date('U'), 'ctime' => $item->get_date('U'), 'detail' => $link);
         }
     }
     return $files;
 }
예제 #12
0
파일: favicon.php 프로젝트: komagata/plnet
<?php

require_once dirname(dirname(__FILE__)) . '/webapp/config.php';
require_once 'FeedParser.php';
$uri = $_SERVER['argv'][1];
$feed = new FeedParser($uri);
$res = $feed->parse();
echo "favicon: " . $feed->getFavicon() . "\n";
예제 #13
0
 /**
  * Render the output of an RSS feed
  *
  * @param string $url    URL of the feed
  * @param array  $params Finetuning of the output
  */
 function rss($url, $params)
 {
     global $lang;
     require_once DOKU_INC . 'inc/FeedParser.php';
     $feed = new FeedParser();
     $feed->feed_url($url);
     //disable warning while fetching
     $elvl = null;
     if (!defined('DOKU_E_LEVEL')) {
         $elvl = error_reporting(E_ERROR);
     }
     $rc = $feed->init();
     if (!defined('DOKU_E_LEVEL')) {
         error_reporting($elvl);
     }
     //decide on start and end
     if ($params['reverse']) {
         $mod = -1;
         $start = $feed->get_item_quantity() - 1;
         $end = $start - $params['max'];
         $end = $end < -1 ? -1 : $end;
     } else {
         $mod = 1;
         $start = 0;
         $end = $feed->get_item_quantity();
         $end = $end > $params['max'] ? $params['max'] : $end;
     }
     $this->listu_open();
     if ($rc) {
         for ($x = $start; $x != $end; $x += $mod) {
             $item = $feed->get_item($x);
             $this->listitem_open(0);
             $this->listcontent_open();
             $this->externallink($item->get_permalink(), $item->get_title());
             if ($params['author']) {
                 $author = $item->get_author(0);
                 if ($author) {
                     $name = $author->get_name();
                     if (!$name) {
                         $name = $author->get_email();
                     }
                     if ($name) {
                         $this->cdata(' ' . $lang['by'] . ' ' . $name);
                     }
                 }
             }
             if ($params['date']) {
                 $this->cdata(' (' . $item->get_date($this->config->getParam('dformat')) . ')');
             }
             if ($params['details']) {
                 $this->cdata(strip_tags($item->get_description()));
             }
             $this->listcontent_close();
             $this->listitem_close();
         }
     } else {
         $this->listitem_open(0);
         $this->listcontent_open();
         $this->emphasis_open();
         $this->cdata($lang['rssfailed']);
         $this->emphasis_close();
         $this->externallink($url);
         $this->listcontent_close();
         $this->listitem_close();
     }
     $this->listu_close();
 }
 /**
  * 
  *
  * @param Doku_Event $event  Not used
  * @param mixed      $param  Not used
  * @return void
  */
 public function handle(Doku_Event &$event, $param)
 {
     global $conf;
     if ($event->data != 'feedaggregator') {
         return;
     }
     $event->preventDefault();
     // See if we need a token and whether it matches.
     $requiredToken = $this->getConf('token');
     $suppliedToken = isset($_GET['token']) ? $_GET['token'] : false;
     if (!empty($requiredToken) && $suppliedToken !== $requiredToken) {
         msg("Token doesn't match for feedaggregator");
         return true;
     }
     // Get the feed list.
     $feeds = file(fullpath($conf['tmpdir'] . '/feedaggregator.csv'));
     // Set up SimplePie and merge all the feeds together.
     $simplepie = new FeedParser();
     $ua = 'Mozilla/4.0 (compatible; DokuWiki feedaggregator plugin ' . wl('', '', true) . ')';
     $simplepie->set_useragent($ua);
     $simplepie->force_feed($this->getConf('force_feed'));
     $simplepie->force_fsockopen($this->getConf('force_fsockopen'));
     $simplepie->set_feed_url($feeds);
     // Set up caching.
     $cacheDir = fullpath($conf['cachedir'] . '/feedaggregator');
     io_mkdir_p($cacheDir);
     $simplepie->enable_cache();
     $simplepie->set_cache_location($cacheDir);
     // Run the actual feed aggregation.
     $simplepie->init();
     // Check for errors.
     if ($simplepie->error()) {
         header("Content-type:text/plain");
         echo join("\n", $simplepie->error());
     }
     // Create the output HTML and cache it for use by the syntax component.
     $html = '';
     foreach ($simplepie->get_items() as $item) {
         $html .= "<div class='feedaggregator_item'>\n" . "<h2>" . $item->get_title() . "</h2>\n" . $item->get_content() . "\n" . "<p>" . "  <a href='" . $item->get_permalink() . "'>Published " . $item->get_date('j M Y') . "</a> " . "  in <a href='" . $item->get_feed()->get_permalink() . "'>" . $item->get_feed()->get_title() . "</a>" . "</p>\n" . "</div>\n\n";
     }
     io_saveFile($cacheDir . '/output.html', $html);
     // Output nothing, as this should be run from cron and we don't want to
     // flood the logs with success.
     exit(0);
 }
예제 #15
0
 /**
  * Renders an RSS feed
  *
  * @author Andreas Gohr <*****@*****.**>
  */
 function rss($url, $params)
 {
     global $lang;
     global $conf;
     require_once DOKU_INC . 'inc/FeedParser.php';
     $feed = new FeedParser();
     $feed->feed_url($url);
     //disable warning while fetching
     if (!defined('DOKU_E_LEVEL')) {
         $elvl = error_reporting(E_ERROR);
     }
     $rc = $feed->init();
     if (!defined('DOKU_E_LEVEL')) {
         error_reporting($elvl);
     }
     //decide on start and end
     if ($params['reverse']) {
         $mod = -1;
         $start = $feed->get_item_quantity() - 1;
         $end = $start - $params['max'];
         $end = $end < -1 ? -1 : $end;
     } else {
         $mod = 1;
         $start = 0;
         $end = $feed->get_item_quantity();
         $end = $end > $params['max'] ? $params['max'] : $end;
     }
     //$this->doc .= '<ul class="rss">';
     $this->listu_open();
     if ($rc) {
         for ($x = $start; $x != $end; $x += $mod) {
             $item = $feed->get_item($x);
             //$this->doc .= '<li><div class="li">';
             $this->listitem_open(1);
             $this->externallink($item->get_permalink(), $item->get_title());
             if ($params['author']) {
                 $author = $item->get_author(0);
                 if ($author) {
                     $name = $author->get_name();
                     if (!$name) {
                         $name = $author->get_email();
                     }
                     if ($name) {
                         $this->cdata(' ' . $lang['by'] . ' ' . $name);
                     }
                     //$this->doc .= ' '.$lang['by'].' '.$name;
                 }
             }
             if ($params['date']) {
                 $this->cdata(' (' . $item->get_date($conf['dformat']) . ')');
                 //$this->doc .= ' ('.$item->get_date($conf['dformat']).')';
             }
             if ($params['details']) {
                 //$this->doc .= '<div class="detail">';
                 if ($htmlok) {
                     $this->cdata($item->get_description());
                 } else {
                     $this->cdata(strip_tags($item->get_description()));
                 }
                 //$this->doc .= '</div>';
             }
             //$this->doc .= '</div></li>';
             $this->listitem_close();
         }
     } else {
         //$this->doc .= '<li><div class="li">';
         $this->listitem_open(1);
         $this->emphasis_open();
         //$this->doc .= '<em>'.$lang['rssfailed'].'</em>';
         $this->cdata($lang['rssfailed']);
         $this->emphasis_close();
         $this->externallink($url);
         //             if($conf['allowdebug']){
         //                 $this->doc .= '<!--'.hsc($feed->error).'-->';
         //             }
         //  $this->doc .= '</div></li>';
         $this->listitem_close();
     }
     //        $this->doc .= '</ul>';
     $this->listu_close();
 }
예제 #16
0
파일: FeedParser.php 프로젝트: huluwa/grr
 private static function extractLinks($sourceUrl, $html)
 {
     $links = array();
     if (preg_match_all("/<link(?:\\s+\\w+=[\"'][^\"']*[\"'])+\\s*\\/?>/", $html, $matches)) {
         foreach ($matches[0] as $match) {
             if (preg_match_all("/(\\w+)=[\"']([^\"']*)[\"']/", $match, $submatches, PREG_SET_ORDER)) {
                 $attrs = array();
                 foreach ($submatches as $submatch) {
                     list(, $key, $value) = $submatch;
                     $attrs[strtolower($key)] = $value;
                 }
                 if (strcasecmp($attrs["rel"], "alternate") === 0 && (strcasecmp($attrs["type"], "application/rss+xml") === 0 || strcasecmp($attrs["type"], "application/atom+xml") === 0)) {
                     $link = new stdClass();
                     $link->title = $attrs["title"];
                     $link->url = FeedParser::resolveUrl($sourceUrl, $attrs["href"]);
                     $links[] = $link;
                 }
             }
         }
     }
     return $links;
 }
예제 #17
0
파일: feed.php 프로젝트: klawdyo/FeedParser
<?php

// The only thing we need is include base class file
require_once 'FeedParser.php';
// Get XML serialization of feed
$xml = file_get_contents($_POST['filename']);
// This is great. To work with feed we invoke only base class. All other work is
// transparent.
$feed = new FeedParser($xml);
//Because we have interface for feeds, we invoke interface methods
echo '<b>Type:</b>' . $feed->getFeedType() . "<br/>";
echo '<b>Title:</b>' . $feed->getTitle() . "<br/>";
echo '<b>Description:</b>' . $feed->getDescription() . "<br/>";
echo '<b>Feed link:</b>' . $feed->getFeedLink() . "<br/>";
echo '<b>Link:</b>' . $feed->getLink() . "<br/>";
$items = $feed->getItems();
// Stuff in your items can be empty, so you should somehow handle it.
// I've prepared is_empty function for you - enjoy.
$i = 1;
foreach ($items as $item) {
    //Because we have interface for items, we invoke interface methods
    echo "<h1>";
    if (is_empty($item->getLink())) {
        echo '<a href="#">';
    } else {
        echo '<a href="' . $item->getLink() . '">';
    }
    if (is_empty($item->getTitle())) {
        echo "No title";
    } else {
        echo "{$i}. " . $item->getTitle();
예제 #18
0
<?php

/*
 *
 *		Simple Example of how to use Feed Parser Class
 *		by Marc Qualie
 *
 */
include 'class.feedparser.php';
$feed = new FeedParser();
// Two different ways of getting blogger feeds, both end up in at the same url
$blog1 = $feed->blogger('blog.marcqualie.com', 1);
$blog2 = $feed->blogger('marcqualie', 1);
// Twitter via Username
$tweets = $feed->twitter('marcqualie', 1);
// Output
header('Content-type: text/plain');
echo "Bandwidth: {$feed->bandwidth}\n";
echo "Requests: {$feed->requests}\n";
echo "\n";
// Dump
$output = 'blog1  = ' . print_r($blog1, 1) . "\n";
$output .= 'blog2  = ' . print_r($blog2, 1) . "\n";
$output .= 'tweets = ' . print_r($tweets, 1) . "\n";
$fh = fopen('example.log', 'w');
fwrite($fh, $output);
fclose($fh);
예제 #19
0
파일: refresh.php 프로젝트: noose/Planeta
set_time_limit(0);
define('SF_ROOT_DIR', realpath(dirname(__FILE__) . '/..'));
define('SF_APP', 'backend');
define('SF_ENVIRONMENT', 'prod');
define('SF_DEBUG', false);
require_once SF_ROOT_DIR . DIRECTORY_SEPARATOR . 'apps' . DIRECTORY_SEPARATOR . SF_APP . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
$databaseManager = new sfDatabaseManager();
$databaseManager->initialize();
$blogs = BlogPeer::getApproved();
logmsg('Skrypt odswiezajacy');
logmsg('Feedow do sprawdzenia: %d', count($blogs));
logmsg(str_repeat('-', 80));
foreach ($blogs as $blog) {
    logmsg('Parsowanie feedu %s', $blog->getFeed());
    try {
        $items = FeedParser::parse($blog->getFeed());
        $ts = PostPeer::getNewestTimestamp($blog);
        logmsg('Najnowszy wpis (timestamp): %d', $ts);
        foreach ($items as $item) {
            if (!parseItem($blog, $item, $ts)) {
                break;
            }
        }
    } catch (Exception $e) {
        logmsg('Blad: %s', $e->getMessage());
    }
    logmsg(str_repeat('-', 80) . "\n");
}
logmsg('Odswiezanie zakonczone.');
function parseItem($blog, $item, $ts)
{
예제 #20
0
파일: xhtml.php 프로젝트: sawachan/dokuwiki
 /**
  * Renders an RSS feed
  *
  * @author Andreas Gohr <*****@*****.**>
  */
 function rss($url, $params)
 {
     global $lang;
     global $conf;
     require_once DOKU_INC . 'inc/FeedParser.php';
     $feed = new FeedParser();
     $feed->set_feed_url($url);
     //disable warning while fetching
     if (!defined('DOKU_E_LEVEL')) {
         $elvl = error_reporting(E_ERROR);
     }
     $rc = $feed->init();
     if (isset($elvl)) {
         error_reporting($elvl);
     }
     if ($params['nosort']) {
         $feed->enable_order_by_date(false);
     }
     //decide on start and end
     if ($params['reverse']) {
         $mod = -1;
         $start = $feed->get_item_quantity() - 1;
         $end = $start - $params['max'];
         $end = $end < -1 ? -1 : $end;
     } else {
         $mod = 1;
         $start = 0;
         $end = $feed->get_item_quantity();
         $end = $end > $params['max'] ? $params['max'] : $end;
     }
     $this->doc .= '<ul class="rss">';
     if ($rc) {
         for ($x = $start; $x != $end; $x += $mod) {
             $item = $feed->get_item($x);
             $this->doc .= '<li><div class="li">';
             // support feeds without links
             $lnkurl = $item->get_permalink();
             if ($lnkurl) {
                 // title is escaped by SimplePie, we unescape here because it
                 // is escaped again in externallink() FS#1705
                 $this->externallink($item->get_permalink(), html_entity_decode($item->get_title(), ENT_QUOTES, 'UTF-8'));
             } else {
                 $this->doc .= ' ' . $item->get_title();
             }
             if ($params['author']) {
                 $author = $item->get_author(0);
                 if ($author) {
                     $name = $author->get_name();
                     if (!$name) {
                         $name = $author->get_email();
                     }
                     if ($name) {
                         $this->doc .= ' ' . $lang['by'] . ' ' . $name;
                     }
                 }
             }
             if ($params['date']) {
                 $this->doc .= ' (' . $item->get_local_date($conf['dformat']) . ')';
             }
             if ($params['details']) {
                 $this->doc .= '<div class="detail">';
                 if ($conf['htmlok']) {
                     $this->doc .= $item->get_description();
                 } else {
                     $this->doc .= strip_tags($item->get_description());
                 }
                 $this->doc .= '</div>';
             }
             $this->doc .= '</div></li>';
         }
     } else {
         $this->doc .= '<li><div class="li">';
         $this->doc .= '<em>' . $lang['rssfailed'] . '</em>';
         $this->externallink($url);
         if ($conf['allowdebug']) {
             $this->doc .= '<!--' . hsc($feed->error) . '-->';
         }
         $this->doc .= '</div></li>';
     }
     $this->doc .= '</ul>';
 }
예제 #21
0
 function execute(&$controller, &$request, &$user)
 {
     $uri = $request->getParameter('uri');
     $member = $user->getAttribute('member', GLU_NS);
     $redirect = $request->hasParameter('redirect') ? $request->getParameter('redirect') : null;
     $cc_id = $this->getContentCategoryIdByUri($uri) ? $this->getContentCategoryIdByUri($uri) : 8;
     // get feed
     $f = new FeedParser($uri);
     $parse_result = $f->parse();
     if ($parse_result === false) {
         trigger_error(__CLASS__ . '::' . __FUNCTION__ . '(): ' . "Failed to parse feed uri: {$uri}", E_USER_NOTICE);
         header('Content-Type: text/plain; charset=utf-8');
         echo 'false';
         return VIEW_NONE;
     }
     $name = $f->getTitle();
     $favicon = $f->getFavicon() ? $f->getFavicon() : SCRIPT_PATH . 'images/favicon.ico';
     $db =& DBUtils::connect(false);
     $db->query('BEGIN');
     // get feedId
     $feedId = $this->getFeedIdByUri($uri);
     if ($feedId === false) {
         // add feed
         $fields = array('uri' => $uri, 'link' => $f->getLink(), 'title' => $f->getTitle(), 'description' => $f->getDescription(), 'favicon' => $favicon, 'lastupdatedtime' => date("Y-m-d H:i:s"));
         $res = $db->autoExecute('feed', $fields, DB_AUTOQUERY_INSERT);
         if (DB::isError($res)) {
             $db->rollback();
             trigger_error(__CLASS__ . '::' . __FUNCTION__ . '(): ' . "Failed to insert. " . $res->toString(), E_USER_ERROR);
             header('Content-Type: text/plain; charset=utf-8');
             echo 'false';
             return VIEW_NONE;
         }
         // specific mysql
         $feedId = $db->getOne('SELECT LAST_INSERT_ID()');
     }
     // add member_to_feed
     $m2f_fields = array('member_id' => MemberUtils::get_id_by_account($member->account), 'feed_id' => $feedId);
     if (DBUtils::get('member_to_feed', $m2f_fields)) {
         echo "'already exists'";
         // already exists
         return VIEW_NONE;
     }
     $res = $db->autoExecute('member_to_feed', $m2f_fields, DB_AUTOQUERY_INSERT);
     if (DB::isError($res)) {
         $db->rollback();
         trigger_error(__CLASS__ . '::' . __FUNCTION__ . '(): ' . "Failed to insert m2f. " . $res->toString(), E_USER_WARNING);
         header('Content-Type: text/plain; charset=utf-8');
         echo 'false';
         return VIEW_NONE;
     }
     // add member_to_content_category_to_feed
     $m2cc2f_fields = array('member_id' => $member->id, 'content_category_id' => $cc_id, 'feed_id' => $feedId);
     $sql = "SELECT count(*)\n            FROM member_to_content_category_to_feed\n            WHERE member_id = ?\n            AND content_category_id = ?\n            AND feed_id = ? ";
     if ($db->getOne($sql, array_values($m2cc2f_fields)) == 0) {
         $res = $db->autoExecute('member_to_content_category_to_feed', $m2cc2f_fields, DB_AUTOQUERY_INSERT);
         if (DB::isError($res)) {
             $db->rollback();
             trigger_error(__CLASS__ . '::' . __FUNCTION__ . '(): ' . 'Failed to insert m2cc2f. ' . $res->toString(), E_USER_WARNING);
             header('Content-Type: text/plain; charset=utf-8');
             echo 'false';
             return VIEW_NONE;
         }
     }
     // try to crawl
     $crawler =& new Crawler();
     $crawl_result = $crawler->crawl($uri);
     if ($crawl_result === false) {
         $db->rollback();
         trigger_error("AddFeedAction::execute(): Failed to crawl: {$uri}", E_USER_NOTICE);
         header('Content-Type: text/plain; charset=utf-8');
         echo 'false';
         return VIEW_NONE;
     }
     $db->commit();
     if ($redirect) {
         Controller::redirect(SCRIPT_PATH . 'setting/feed');
     } else {
         header('Content-Type: text/plain; charset=utf-8');
         echo 'true';
     }
     return VIEW_NONE;
 }
예제 #22
0
파일: parse.php 프로젝트: komagata/plnet
<?php

require_once dirname(dirname(__FILE__)) . '/webapp/config.php';
require_once 'FeedParser.php';
$uri = $_SERVER['argv'][1];
$feed = new FeedParser($uri);
$res = $feed->parse();
print_r($feed->toArray());
예제 #23
0
<?php

require 'inc/config.php';
require 'inc/db.php';
require 'lib/FeedParser.class.php';
require 'lib/Parser.class.php';
echo "Loading feeds...";
$feed_parser = new FeedParser();
$i = 0;
$opml = simplexml_load_file('http://news.bbc.co.uk/rss/feeds.opml');
foreach ($opml->xpath('//outline') as $item) {
    if ((string) $item['language'] == 'en-gb') {
        $feed_parser->add((string) $item['xmlUrl']);
    }
}
$feed_parser->add('http://www.guardian.co.uk/rss');
$feed_parser->add('http://www.guardian.co.uk/rssfeed/0,,11,00.xml');
$feed_parser->add('http://www.guardian.co.uk/rssfeed/0,,12,00.xml');
$feed_parser->add('http://www.guardian.co.uk/rssfeed/0,,5,00.xml');
$feed_parser->add('http://www.guardian.co.uk/rssfeed/0,,24,00.xml');
$feed_parser->add('http://www.guardian.co.uk/rssfeed/0,15065,19,00.xml');
$feed_parser->add('http://www.guardian.co.uk/rssfeed/0,,18,00.xml');
$feed_parser->add('http://www.guardian.co.uk/rssfeed/0,,7,00.xml');
$feed_parser->add('http://english.aljazeera.net/Services/Rss/?PostingId=2007731105943979989');
echo "DONE\n";
$parser_factory = ParserFactory::create();
function prompt($parser, $item, $category, $locations)
{
    echo "\n" . $item->title() . "\n";
    echo $locations[0]['name'] . ' <-> ' . $locations[1]['name'] . "\n";
    if ($category) {
예제 #24
0
<?php

include 'FeedParser.php';
$Parser = new FeedParser();
$Parser->parse('http://www.sitepoint.com/rss.php');
$channels = $Parser->getChannels();
$items = $Parser->getItems();
?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Testing the PHP Universal Feed Parser</title>
	<style type="text/css">
	body{
		padding: 0px;
		margin: 50px 150px;
		border: 1px solid #ddd;
		font-family: verdana, arial;
	}
	
	h1#title {
		background-color: #eee;
		border-bottom : 1px solid #ddd;
		margin: 0px 0px 15px;
		padding:10px;
		text-align: center;
	}
	h1#title a{
		font-size: 18px;
	}
	
     exit;
 }
 $latest_code = $tree['mybb']['version_code']['value'];
 $latest_version = "<strong>" . $tree['mybb']['latest_version']['value'] . "</strong> (" . $latest_code . ")";
 if ($latest_code > $mybb->version_code) {
     $latest_version = "<span style=\"color: #C00;\">" . $latest_version . "</span>";
     $version_warn = 1;
     $updated_cache['latest_version'] = $latest_version;
     $updated_cache['latest_version_code'] = $latest_code;
 } else {
     $version_warn = 0;
     $latest_version = "<span style=\"color: green;\">" . $latest_version . "</span>";
 }
 $cache->update("update_check", $updated_cache);
 require_once MYBB_ROOT . "inc/class_feedparser.php";
 $feed_parser = new FeedParser();
 $feed_parser->parse_feed("http://feeds.feedburner.com/MyBBDevelopmentBlog");
 $table = new Table();
 $table->construct_header($lang->your_version);
 $table->construct_header($lang->latest_version);
 $table->construct_cell("<strong>" . $mybb->version . "</strong> (" . $mybb->version_code . ")");
 $table->construct_cell($latest_version);
 $table->construct_row();
 $table->output($lang->version_check);
 if ($version_warn) {
     $page->output_error("<p><em>{$lang->error_out_of_date}</em> {$lang->update_forum}</p>");
 } else {
     $page->output_success("<p><em>{$lang->success_up_to_date}</em></p>");
 }
 if ($feed_parser->error == '') {
     foreach ($feed_parser->items as $item) {
예제 #26
0
function update_rss_feed($feed, $ignore_daemon = false, $no_cache = false, $rss = false)
{
    $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
    _debug_suppress(!$debug_enabled);
    _debug("start", $debug_enabled);
    $result = db_query("SELECT title FROM ttrss_feeds\n\t\t\tWHERE id = '{$feed}'");
    $title = db_fetch_result($result, 0, "title");
    // feed was batch-subscribed or something, we need to get basic info
    // this is not optimal currently as it fetches stuff separately TODO: optimize
    if ($title == "[Unknown]") {
        _debug("setting basic feed info for {$feed}...");
        set_basic_feed_info($feed);
    }
    $result = db_query("SELECT id,update_interval,auth_login,\n\t\t\tfeed_url,auth_pass,cache_images,\n\t\t\tmark_unread_on_update, owner_uid,\n\t\t\tpubsub_state, auth_pass_encrypted,\n\t\t\tfeed_language,\n\t\t\t(SELECT max(date_entered) FROM\n\t\t\t\tttrss_entries, ttrss_user_entries where ref_id = id AND feed_id = '{$feed}') AS last_article_timestamp\n\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'");
    if (db_num_rows($result) == 0) {
        _debug("feed {$feed} NOT FOUND/SKIPPED", $debug_enabled);
        return false;
    }
    $last_article_timestamp = @strtotime(db_fetch_result($result, 0, "last_article_timestamp"));
    if (defined('_DISABLE_HTTP_304')) {
        $last_article_timestamp = 0;
    }
    $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"));
    $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
    $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result, 0, "auth_pass_encrypted"));
    db_query("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 ($auth_pass_encrypted) {
        require_once "crypt.php";
        $auth_pass = decrypt_string($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_language = db_escape_string(mb_strtolower(db_fetch_result($result, 0, "feed_language")));
    if (!$feed_language) {
        $feed_language = 'english';
    }
    $feed = db_escape_string($feed);
    $date_feed_processed = date('Y-m-d H:i');
    $cache_filename = CACHE_DIR . "/simplepie/" . sha1($fetch_url) . ".xml";
    $pluginhost = new PluginHost();
    $pluginhost->set_debug($debug_enabled);
    $user_plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
    $pluginhost->load(PLUGINS, PluginHost::KIND_ALL);
    $pluginhost->load($user_plugins, PluginHost::KIND_USER, $owner_uid);
    $pluginhost->load_data();
    if ($rss && is_object($rss) && get_class($rss) == "FeedParser") {
        _debug("using previously initialized parser object");
    } else {
        $rss_hash = false;
        $force_refetch = isset($_REQUEST["force_refetch"]);
        foreach ($pluginhost->get_hooks(PluginHost::HOOK_FETCH_FEED) as $plugin) {
            $feed_data = $plugin->hook_fetch_feed($feed_data, $fetch_url, $owner_uid, $feed, $last_article_timestamp, $auth_login, $auth_pass);
        }
        // try cache
        if (!$feed_data && file_exists($cache_filename) && is_readable($cache_filename) && !$auth_login && !$auth_pass && filemtime($cache_filename) > time() - 30) {
            _debug("using local cache [{$cache_filename}].", $debug_enabled);
            @($feed_data = file_get_contents($cache_filename));
            if ($feed_data) {
                $rss_hash = sha1($feed_data);
            }
        } else {
            _debug("local cache will not be used for this feed", $debug_enabled);
        }
        // fetch feed from source
        if (!$feed_data) {
            _debug("fetching [{$fetch_url}]...", $debug_enabled);
            _debug("If-Modified-Since: " . gmdate('D, d M Y H:i:s \\G\\M\\T', $last_article_timestamp), $debug_enabled);
            $feed_data = fetch_file_contents($fetch_url, false, $auth_login, $auth_pass, false, $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT : FEED_FETCH_TIMEOUT, $force_refetch ? 0 : $last_article_timestamp);
            global $fetch_curl_used;
            if (!$fetch_curl_used) {
                $tmp = @gzdecode($feed_data);
                if ($tmp) {
                    $feed_data = $tmp;
                }
            }
            $feed_data = trim($feed_data);
            _debug("fetch done.", $debug_enabled);
            // cache vanilla feed data for re-use
            if ($feed_data && !$auth_pass && !$auth_login && is_writable(CACHE_DIR . "/simplepie")) {
                $new_rss_hash = sha1($feed_data);
                if ($new_rss_hash != $rss_hash) {
                    _debug("saving {$cache_filename}", $debug_enabled);
                    @file_put_contents($cache_filename, $feed_data);
                }
            }
        }
        if (!$feed_data) {
            global $fetch_last_error;
            global $fetch_last_error_code;
            _debug("unable to fetch: {$fetch_last_error} [{$fetch_last_error_code}]", $debug_enabled);
            $error_escaped = '';
            // If-Modified-Since
            if ($fetch_last_error_code != 304) {
                $error_escaped = db_escape_string($fetch_last_error);
            } else {
                _debug("source claims data not modified, nothing to do.", $debug_enabled);
            }
            db_query("UPDATE ttrss_feeds SET last_error = '{$error_escaped}',\n\t\t\t\t\t\tlast_updated = NOW() WHERE id = '{$feed}'");
            return;
        }
    }
    foreach ($pluginhost->get_hooks(PluginHost::HOOK_FEED_FETCHED) as $plugin) {
        $feed_data = $plugin->hook_feed_fetched($feed_data, $fetch_url, $owner_uid, $feed);
    }
    // set last update to now so if anything *simplepie* crashes later we won't be
    // continuously failing on the same feed
    //db_query("UPDATE ttrss_feeds SET last_updated = NOW() WHERE id = '$feed'");
    if (!$rss) {
        $rss = new FeedParser($feed_data);
        $rss->init();
    }
    //		print_r($rss);
    $feed = db_escape_string($feed);
    if (!$rss->error()) {
        // We use local pluginhost here because we need to load different per-user feed plugins
        $pluginhost->run_hooks(PluginHost::HOOK_FEED_PARSED, "hook_feed_parsed", $rss);
        _debug("language: {$feed_language}", $debug_enabled);
        _debug("processing feed data...", $debug_enabled);
        //			db_query("BEGIN");
        if (DB_TYPE == "pgsql") {
            $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
        } else {
            $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
        }
        $result = db_query("SELECT owner_uid,favicon_avg_color,\n\t\t\t\t(favicon_last_checked IS NULL OR {$favicon_interval_qpart}) AS\n\t\t\t\t\t\tfavicon_needs_check\n\t\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'");
        $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0, "favicon_needs_check"));
        $favicon_avg_color = db_fetch_result($result, 0, "favicon_avg_color");
        $owner_uid = db_fetch_result($result, 0, "owner_uid");
        $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
        _debug("site_url: {$site_url}", $debug_enabled);
        _debug("feed_title: " . $rss->get_title(), $debug_enabled);
        if ($favicon_needs_check || $force_refetch) {
            /* terrible hack: if we crash on floicon shit here, we won't check
             * the icon avgcolor again (unless the icon got updated) */
            $favicon_file = ICONS_DIR . "/{$feed}.ico";
            $favicon_modified = @filemtime($favicon_file);
            _debug("checking favicon...", $debug_enabled);
            check_feed_favicon($site_url, $feed);
            $favicon_modified_new = @filemtime($favicon_file);
            if ($favicon_modified_new > $favicon_modified) {
                $favicon_avg_color = '';
            }
            if (file_exists($favicon_file) && function_exists("imagecreatefromstring") && $favicon_avg_color == '') {
                require_once "colors.php";
                db_query("UPDATE ttrss_feeds SET favicon_avg_color = 'fail' WHERE\n\t\t\t\t\t\t\tid = '{$feed}'");
                $favicon_color = db_escape_string(calculate_avg_color($favicon_file));
                $favicon_colorstring = ",favicon_avg_color = '" . $favicon_color . "'";
            } else {
                if ($favicon_avg_color == 'fail') {
                    _debug("floicon failed on this file, not trying to recalculate avg color", $debug_enabled);
                }
            }
            db_query("UPDATE ttrss_feeds SET favicon_last_checked = NOW()\n\t\t\t\t\t{$favicon_colorstring}\n\t\t\t\t\tWHERE id = '{$feed}'");
        }
        _debug("loading filters & labels...", $debug_enabled);
        $filters = load_filters($feed, $owner_uid);
        _debug("" . count($filters) . " filters loaded.", $debug_enabled);
        $items = $rss->get_items();
        if (!is_array($items)) {
            _debug("no articles found.", $debug_enabled);
            db_query("UPDATE ttrss_feeds\n\t\t\t\t\tSET last_updated = NOW(), last_error = '' WHERE id = '{$feed}'");
            return;
            // no articles
        }
        if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
            _debug("checking for PUSH hub...", $debug_enabled);
            $feed_hub_url = false;
            $links = $rss->get_links('hub');
            if ($links && is_array($links)) {
                foreach ($links as $l) {
                    $feed_hub_url = $l;
                    break;
                }
            }
            _debug("feed hub url: {$feed_hub_url}", $debug_enabled);
            $feed_self_url = $fetch_url;
            $links = $rss->get_links('self');
            if ($links && is_array($links)) {
                foreach ($links as $l) {
                    $feed_self_url = $l;
                    break;
                }
            }
            _debug("feed self url = {$feed_self_url}");
            if ($feed_hub_url && $feed_self_url && function_exists('curl_init') && !ini_get("open_basedir")) {
                require_once 'lib/pubsubhubbub/subscriber.php';
                $callback_url = get_self_url_prefix() . "/public.php?op=pubsub&id={$feed}";
                $s = new Subscriber($feed_hub_url, $callback_url);
                $rc = $s->subscribe($feed_self_url);
                _debug("feed hub url found, subscribe request sent. [rc={$rc}]", $debug_enabled);
                db_query("UPDATE ttrss_feeds SET pubsub_state = 1\n\t\t\t\t\t\tWHERE id = '{$feed}'");
            }
        }
        _debug("processing articles...", $debug_enabled);
        $tstart = time();
        foreach ($items as $item) {
            if ($_REQUEST['xdebug'] == 3) {
                print_r($item);
            }
            if (ini_get("max_execution_time") > 0 && time() - $tstart >= ini_get("max_execution_time") * 0.7) {
                _debug("looks like there's too many articles to process at once, breaking out", $debug_enabled);
                break;
            }
            $entry_guid = $item->get_id();
            if (!$entry_guid) {
                $entry_guid = $item->get_link();
            }
            if (!$entry_guid) {
                $entry_guid = make_guid_from_title($item->get_title());
            }
            if (!$entry_guid) {
                continue;
            }
            $entry_guid = "{$owner_uid},{$entry_guid}";
            $entry_guid_hashed = db_escape_string('SHA1:' . sha1($entry_guid));
            _debug("guid {$entry_guid} / {$entry_guid_hashed}", $debug_enabled);
            $entry_timestamp = "";
            $entry_timestamp = $item->get_date();
            _debug("orig date: " . $item->get_date(), $debug_enabled);
            if ($entry_timestamp == -1 || !$entry_timestamp || $entry_timestamp > time()) {
                $entry_timestamp = time();
            }
            $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
            _debug("date {$entry_timestamp} [{$entry_timestamp_fmt}]", $debug_enabled);
            //				$entry_title = html_entity_decode($item->get_title(), ENT_COMPAT, 'UTF-8');
            //				$entry_title = decode_numeric_entities($entry_title);
            $entry_title = $item->get_title();
            $entry_link = rewrite_relative_url($site_url, $item->get_link());
            _debug("title {$entry_title}", $debug_enabled);
            _debug("link {$entry_link}", $debug_enabled);
            if (!$entry_title) {
                $entry_title = date("Y-m-d H:i:s", $entry_timestamp);
            }
            $entry_content = $item->get_content();
            if (!$entry_content) {
                $entry_content = $item->get_description();
            }
            if ($_REQUEST["xdebug"] == 2) {
                print "content: ";
                print $entry_content;
                print "\n";
            }
            $entry_comments = $item->get_comments_url();
            $entry_author = $item->get_author();
            $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245));
            $entry_comments = db_escape_string(mb_substr(trim($entry_comments), 0, 245));
            $entry_author = db_escape_string(mb_substr(trim($entry_author), 0, 245));
            $num_comments = (int) $item->get_comments_count();
            _debug("author {$entry_author}", $debug_enabled);
            _debug("num_comments: {$num_comments}", $debug_enabled);
            _debug("looking for tags...", $debug_enabled);
            // parse <category> entries into tags
            $additional_tags = array();
            $additional_tags_src = $item->get_categories();
            if (is_array($additional_tags_src)) {
                foreach ($additional_tags_src as $tobj) {
                    array_push($additional_tags, $tobj);
                }
            }
            $entry_tags = array_unique($additional_tags);
            for ($i = 0; $i < count($entry_tags); $i++) {
                $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
            }
            _debug("tags found: " . join(",", $entry_tags), $debug_enabled);
            _debug("done collecting data.", $debug_enabled);
            $result = db_query("SELECT id, content_hash, lang FROM ttrss_entries\n\t\t\t\t\tWHERE guid = '" . db_escape_string($entry_guid) . "' OR guid = '{$entry_guid_hashed}'");
            if (db_num_rows($result) != 0) {
                $base_entry_id = db_fetch_result($result, 0, "id");
                $entry_stored_hash = db_fetch_result($result, 0, "content_hash");
                $article_labels = get_article_labels($base_entry_id, $owner_uid);
                $entry_language = db_fetch_result($result, 0, "lang");
            } else {
                $base_entry_id = false;
                $entry_stored_hash = "";
                $article_labels = array();
                $entry_language = "";
            }
            $article = array("owner_uid" => $owner_uid, "guid" => $entry_guid, "guid_hashed" => $entry_guid_hashed, "title" => $entry_title, "content" => $entry_content, "link" => $entry_link, "labels" => $article_labels, "tags" => $entry_tags, "author" => $entry_author, "force_catchup" => false, "score_modifier" => 0, "language" => $entry_language, "feed" => array("id" => $feed, "fetch_url" => $fetch_url, "site_url" => $site_url));
            $entry_plugin_data = "";
            $entry_current_hash = calculate_article_hash($article, $pluginhost);
            _debug("article hash: {$entry_current_hash} [stored={$entry_stored_hash}]", $debug_enabled);
            if ($entry_current_hash == $entry_stored_hash && !isset($_REQUEST["force_rehash"])) {
                _debug("stored article seems up to date [IID: {$base_entry_id}], updating timestamp only", $debug_enabled);
                // we keep encountering the entry in feeds, so we need to
                // update date_updated column so that we don't get horrible
                // dupes when the entry gets purged and reinserted again e.g.
                // in the case of SLOW SLOW OMG SLOW updating feeds
                $base_entry_id = db_fetch_result($result, 0, "id");
                db_query("UPDATE ttrss_entries SET date_updated = NOW()\n\t\t\t\t\t\tWHERE id = '{$base_entry_id}'");
                // if we allow duplicate posts, we have to continue to
                // create the user entries for this feed
                if (!get_pref("ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
                    continue;
                }
            }
            _debug("hash differs, applying plugin filters:", $debug_enabled);
            foreach ($pluginhost->get_hooks(PluginHost::HOOK_ARTICLE_FILTER) as $plugin) {
                _debug("... " . get_class($plugin), $debug_enabled);
                $start = microtime(true);
                $article = $plugin->hook_article_filter($article);
                _debug("=== " . sprintf("%.4f (sec)", microtime(true) - $start), $debug_enabled);
                $entry_plugin_data .= mb_strtolower(get_class($plugin)) . ",";
            }
            $entry_plugin_data = db_escape_string($entry_plugin_data);
            _debug("plugin data: {$entry_plugin_data}", $debug_enabled);
            // Workaround: 4-byte unicode requires utf8mb4 in MySQL. See https://tt-rss.org/forum/viewtopic.php?f=1&t=3377&p=20077#p20077
            if (DB_TYPE == "mysql") {
                foreach ($article as $k => $v) {
                    // i guess we'll have to take the risk of 4byte unicode labels & tags here
                    if (!is_array($article[$k])) {
                        $article[$k] = preg_replace('/[\\x{10000}-\\x{10FFFF}]/u', "�", $v);
                    }
                }
            }
            $entry_tags = $article["tags"];
            $entry_guid = db_escape_string($entry_guid);
            $entry_title = db_escape_string($article["title"]);
            $entry_author = db_escape_string($article["author"]);
            $entry_link = db_escape_string($article["link"]);
            $entry_content = $article["content"];
            // escaped below
            $entry_force_catchup = $article["force_catchup"];
            $article_labels = $article["labels"];
            $entry_score_modifier = (int) $article["score_modifier"];
            $entry_language = db_escape_string($article["language"]);
            if ($debug_enabled) {
                _debug("article labels:", $debug_enabled);
                print_r($article_labels);
            }
            _debug("force catchup: {$entry_force_catchup}");
            if ($cache_images && is_writable(CACHE_DIR . '/images')) {
                cache_images($entry_content, $site_url, $debug_enabled);
            }
            $entry_content = db_escape_string($entry_content, false);
            db_query("BEGIN");
            $result = db_query("SELECT id FROM\tttrss_entries\n\t\t\t\t\tWHERE (guid = '{$entry_guid}' OR guid = '{$entry_guid_hashed}')");
            if (db_num_rows($result) == 0) {
                _debug("base guid [{$entry_guid}] not found", $debug_enabled);
                // base post entry does not exist, create it
                $result = db_query("INSERT INTO ttrss_entries\n\t\t\t\t\t\t\t(title,\n\t\t\t\t\t\t\tguid,\n\t\t\t\t\t\t\tlink,\n\t\t\t\t\t\t\tupdated,\n\t\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t\tcontent_hash,\n\t\t\t\t\t\t\tno_orig_date,\n\t\t\t\t\t\t\tdate_updated,\n\t\t\t\t\t\t\tdate_entered,\n\t\t\t\t\t\t\tcomments,\n\t\t\t\t\t\t\tnum_comments,\n\t\t\t\t\t\t\tplugin_data,\n\t\t\t\t\t\t\tlang,\n\t\t\t\t\t\t\tauthor)\n\t\t\t\t\t\tVALUES\n\t\t\t\t\t\t\t('{$entry_title}',\n\t\t\t\t\t\t\t'{$entry_guid_hashed}',\n\t\t\t\t\t\t\t'{$entry_link}',\n\t\t\t\t\t\t\t'{$entry_timestamp_fmt}',\n\t\t\t\t\t\t\t'{$entry_content}',\n\t\t\t\t\t\t\t'{$entry_current_hash}',\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\tNOW(),\n\t\t\t\t\t\t\t'{$date_feed_processed}',\n\t\t\t\t\t\t\t'{$entry_comments}',\n\t\t\t\t\t\t\t'{$num_comments}',\n\t\t\t\t\t\t\t'{$entry_plugin_data}',\n\t\t\t\t\t\t\t'{$entry_language}',\n\t\t\t\t\t\t\t'{$entry_author}')");
            } else {
                $base_entry_id = db_fetch_result($result, 0, "id");
            }
            // now it should exist, if not - bad luck then
            $result = db_query("SELECT id FROM ttrss_entries\n\t\t\t\t\tWHERE guid = '{$entry_guid}' OR guid = '{$entry_guid_hashed}'");
            $entry_ref_id = 0;
            $entry_int_id = 0;
            if (db_num_rows($result) == 1) {
                _debug("base guid found, checking for user record", $debug_enabled);
                $ref_id = db_fetch_result($result, 0, "id");
                $entry_ref_id = $ref_id;
                /* $stored_guid = db_fetch_result($result, 0, "guid");
                					if ($stored_guid != $entry_guid_hashed) {
                						if ($debug_enabled) _debug("upgrading compat guid to hashed one", $debug_enabled);
                
                						db_query("UPDATE ttrss_entries SET guid = '$entry_guid_hashed' WHERE
                							id = '$ref_id'");
                					} */
                // check for user post link to main table
                // do we allow duplicate posts with same GUID in different feeds?
                if (get_pref("ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
                    $dupcheck_qpart = "AND (feed_id = '{$feed}' OR feed_id IS NULL)";
                } else {
                    $dupcheck_qpart = "";
                }
                /* Collect article tags here so we could filter by them: */
                $article_filters = get_article_filters($filters, $entry_title, $entry_content, $entry_link, $entry_timestamp, $entry_author, $entry_tags);
                if ($debug_enabled) {
                    _debug("article filters: ", $debug_enabled);
                    if (count($article_filters) != 0) {
                        print_r($article_filters);
                    }
                }
                if (find_article_filter($article_filters, "filter")) {
                    db_query("COMMIT");
                    // close transaction in progress
                    continue;
                }
                $score = calculate_article_score($article_filters) + $entry_score_modifier;
                _debug("initial score: {$score} [including plugin modifier: {$entry_score_modifier}]", $debug_enabled);
                $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE\n\t\t\t\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}'\n\t\t\t\t\t\t\t{$dupcheck_qpart}";
                //					if ($_REQUEST["xdebug"]) print "$query\n";
                $result = db_query($query);
                // okay it doesn't exist - create user entry
                if (db_num_rows($result) == 0) {
                    _debug("user record not found, creating...", $debug_enabled);
                    if ($score >= -500 && !find_article_filter($article_filters, 'catchup') && !$entry_force_catchup) {
                        $unread = 'true';
                        $last_read_qpart = 'NULL';
                    } else {
                        $unread = 'false';
                        $last_read_qpart = 'NOW()';
                    }
                    if (find_article_filter($article_filters, 'mark') || $score > 1000) {
                        $marked = 'true';
                    } else {
                        $marked = 'false';
                    }
                    if (find_article_filter($article_filters, 'publish')) {
                        $published = 'true';
                    } else {
                        $published = 'false';
                    }
                    // N-grams
                    /* if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
                    
                    							$result = db_query("SELECT COUNT(*) AS similar FROM
                    									ttrss_entries,ttrss_user_entries
                    								WHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'
                    									AND similarity(title, '$entry_title') >= "._NGRAM_TITLE_DUPLICATE_THRESHOLD."
                    									AND owner_uid = $owner_uid");
                    
                    							$ngram_similar = db_fetch_result($result, 0, "similar");
                    
                    							_debug("N-gram similar results: $ngram_similar", $debug_enabled);
                    
                    							if ($ngram_similar > 0) {
                    								$unread = 'false';
                    							}
                    						} */
                    $last_marked = $marked == 'true' ? 'NOW()' : 'NULL';
                    $last_published = $published == 'true' ? 'NOW()' : 'NULL';
                    $result = db_query("INSERT INTO ttrss_user_entries\n\t\t\t\t\t\t\t\t(ref_id, owner_uid, feed_id, unread, last_read, marked,\n\t\t\t\t\t\t\t\tpublished, score, tag_cache, label_cache, uuid,\n\t\t\t\t\t\t\t\tlast_marked, last_published)\n\t\t\t\t\t\t\tVALUES ('{$ref_id}', '{$owner_uid}', '{$feed}', {$unread},\n\t\t\t\t\t\t\t\t{$last_read_qpart}, {$marked}, {$published}, '{$score}', '', '',\n\t\t\t\t\t\t\t\t'', {$last_marked}, {$last_published})");
                    if (PUBSUBHUBBUB_HUB && $published == 'true') {
                        $rss_link = get_self_url_prefix() . "/public.php?op=rss&id=-2&key=" . get_feed_access_key(-2, false, $owner_uid);
                        $p = new Publisher(PUBSUBHUBBUB_HUB);
                        /* $pubsub_result = */
                        $p->publish_update($rss_link);
                    }
                    $result = db_query("SELECT int_id FROM ttrss_user_entries WHERE\n\t\t\t\t\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}' AND\n\t\t\t\t\t\t\t\tfeed_id = '{$feed}' LIMIT 1");
                    if (db_num_rows($result) == 1) {
                        $entry_int_id = db_fetch_result($result, 0, "int_id");
                    }
                } else {
                    _debug("user record FOUND", $debug_enabled);
                    $entry_ref_id = db_fetch_result($result, 0, "ref_id");
                    $entry_int_id = db_fetch_result($result, 0, "int_id");
                }
                _debug("RID: {$entry_ref_id}, IID: {$entry_int_id}", $debug_enabled);
                if (DB_TYPE == "pgsql") {
                    $tsvector_combined = db_escape_string(mb_substr($entry_title . ' ' . strip_tags($entry_content), 0, 1000000));
                    $tsvector_qpart = "tsvector_combined = to_tsvector('{$feed_language}', '{$tsvector_combined}'),";
                } else {
                    $tsvector_qpart = "";
                }
                db_query("UPDATE ttrss_entries\n\t\t\t\t\t\tSET title = '{$entry_title}',\n\t\t\t\t\t\t\tcontent = '{$entry_content}',\n\t\t\t\t\t\t\tcontent_hash = '{$entry_current_hash}',\n\t\t\t\t\t\t\tupdated = '{$entry_timestamp_fmt}',\n\t\t\t\t\t\t\t{$tsvector_qpart}\n\t\t\t\t\t\t\tnum_comments = '{$num_comments}',\n\t\t\t\t\t\t\tplugin_data = '{$entry_plugin_data}',\n\t\t\t\t\t\t\tauthor = '{$entry_author}',\n\t\t\t\t\t\t\tlang = '{$entry_language}'\n\t\t\t\t\t\tWHERE id = '{$ref_id}'");
                // update aux data
                db_query("UPDATE ttrss_user_entries\n\t\t\t\t\t\t\tSET score = '{$score}' WHERE ref_id = '{$ref_id}'");
                if ($mark_unread_on_update) {
                    db_query("UPDATE ttrss_user_entries\n\t\t\t\t\t\t\tSET last_read = null, unread = true WHERE ref_id = '{$ref_id}'");
                }
            }
            db_query("COMMIT");
            _debug("assigning labels [other]...", $debug_enabled);
            foreach ($article_labels as $label) {
                label_add_article($entry_ref_id, $label[1], $owner_uid);
            }
            _debug("assigning labels [filters]...", $debug_enabled);
            assign_article_to_label_filters($entry_ref_id, $article_filters, $owner_uid, $article_labels);
            _debug("looking for enclosures...", $debug_enabled);
            // enclosures
            $enclosures = array();
            $encs = $item->get_enclosures();
            if (is_array($encs)) {
                foreach ($encs as $e) {
                    $e_item = array($e->link, $e->type, $e->length, $e->title, $e->width, $e->height);
                    array_push($enclosures, $e_item);
                }
            }
            if ($debug_enabled) {
                _debug("article enclosures:", $debug_enabled);
                print_r($enclosures);
            }
            db_query("BEGIN");
            //				debugging
            //				db_query("DELETE FROM ttrss_enclosures WHERE post_id = '$entry_ref_id'");
            foreach ($enclosures as $enc) {
                $enc_url = db_escape_string($enc[0]);
                $enc_type = db_escape_string($enc[1]);
                $enc_dur = db_escape_string($enc[2]);
                $enc_title = db_escape_string($enc[3]);
                $enc_width = intval($enc[4]);
                $enc_height = intval($enc[5]);
                $result = db_query("SELECT id FROM ttrss_enclosures\n\t\t\t\t\t\tWHERE content_url = '{$enc_url}' AND post_id = '{$entry_ref_id}'");
                if (db_num_rows($result) == 0) {
                    db_query("INSERT INTO ttrss_enclosures\n\t\t\t\t\t\t\t(content_url, content_type, title, duration, post_id, width, height) VALUES\n\t\t\t\t\t\t\t('{$enc_url}', '{$enc_type}', '{$enc_title}', '{$enc_dur}', '{$entry_ref_id}', {$enc_width}, {$enc_height})");
                }
            }
            db_query("COMMIT");
            // check for manual tags (we have to do it here since they're loaded from filters)
            foreach ($article_filters as $f) {
                if ($f["type"] == "tag") {
                    $manual_tags = trim_array(explode(",", $f["param"]));
                    foreach ($manual_tags as $tag) {
                        if (tag_is_valid($tag)) {
                            array_push($entry_tags, $tag);
                        }
                    }
                }
            }
            // Skip boring tags
            $boring_tags = trim_array(explode(",", mb_strtolower(get_pref('BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
            $filtered_tags = array();
            $tags_to_cache = array();
            if ($entry_tags && is_array($entry_tags)) {
                foreach ($entry_tags as $tag) {
                    if (array_search($tag, $boring_tags) === false) {
                        array_push($filtered_tags, $tag);
                    }
                }
            }
            $filtered_tags = array_unique($filtered_tags);
            if ($debug_enabled) {
                _debug("filtered article tags:", $debug_enabled);
                print_r($filtered_tags);
            }
            // Save article tags in the database
            if (count($filtered_tags) > 0) {
                db_query("BEGIN");
                foreach ($filtered_tags as $tag) {
                    $tag = sanitize_tag($tag);
                    $tag = db_escape_string($tag);
                    if (!tag_is_valid($tag)) {
                        continue;
                    }
                    $result = db_query("SELECT id FROM ttrss_tags\n\t\t\t\t\t\t\tWHERE tag_name = '{$tag}' AND post_int_id = '{$entry_int_id}' AND\n\t\t\t\t\t\t\towner_uid = '{$owner_uid}' LIMIT 1");
                    if ($result && db_num_rows($result) == 0) {
                        db_query("INSERT INTO ttrss_tags\n\t\t\t\t\t\t\t\t\t(owner_uid,tag_name,post_int_id)\n\t\t\t\t\t\t\t\t\tVALUES ('{$owner_uid}','{$tag}', '{$entry_int_id}')");
                    }
                    array_push($tags_to_cache, $tag);
                }
                /* update the cache */
                $tags_to_cache = array_unique($tags_to_cache);
                $tags_str = db_escape_string(join(",", $tags_to_cache));
                db_query("UPDATE ttrss_user_entries\n\t\t\t\t\t\tSET tag_cache = '{$tags_str}' WHERE ref_id = '{$entry_ref_id}'\n\t\t\t\t\t\tAND owner_uid = {$owner_uid}");
                db_query("COMMIT");
            }
            _debug("article processed", $debug_enabled);
        }
        _debug("purging feed...", $debug_enabled);
        purge_feed($feed, 0, $debug_enabled);
        db_query("UPDATE ttrss_feeds\n\t\t\t\tSET last_updated = NOW(), last_error = '' WHERE id = '{$feed}'");
        //			db_query("COMMIT");
    } else {
        $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245));
        _debug("fetch error: {$error_msg}", $debug_enabled);
        if (count($rss->errors()) > 1) {
            foreach ($rss->errors() as $error) {
                _debug("+ {$error}");
            }
        }
        db_query("UPDATE ttrss_feeds SET last_error = '{$error_msg}',\n\t\t\t\tlast_updated = NOW() WHERE id = '{$feed}'");
        unset($rss);
    }
    _debug("done", $debug_enabled);
    return $rss;
}
function update_rss_feed($feed, $ignore_daemon = false, $no_cache = false)
{
    $debug_enabled = defined('DAEMON_EXTENDED_DEBUG') || $_REQUEST['xdebug'];
    _debug("start", $debug_enabled);
    $result = db_query("SELECT id,update_interval,auth_login,\n\t\t\tfeed_url,auth_pass,cache_images,last_updated,\n\t\t\tmark_unread_on_update, owner_uid,\n\t\t\tpubsub_state, auth_pass_encrypted,\n\t\t\t(SELECT max(date_entered) FROM\n\t\t\t\tttrss_entries, ttrss_user_entries where ref_id = id AND feed_id = '{$feed}') AS last_article_timestamp\n\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'");
    if (db_num_rows($result) == 0) {
        _debug("feed {$feed} NOT FOUND/SKIPPED", $debug_enabled);
        return false;
    }
    $last_updated = db_fetch_result($result, 0, "last_updated");
    $last_article_timestamp = @strtotime(db_fetch_result($result, 0, "last_article_timestamp"));
    if (defined('_DISABLE_HTTP_304')) {
        $last_article_timestamp = 0;
    }
    $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"));
    $pubsub_state = db_fetch_result($result, 0, "pubsub_state");
    $auth_pass_encrypted = sql_bool_to_bool(db_fetch_result($result, 0, "auth_pass_encrypted"));
    db_query("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 ($auth_pass_encrypted) {
        require_once "crypt.php";
        $auth_pass = decrypt_string($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);
    $date_feed_processed = date('Y-m-d H:i');
    $cache_filename = CACHE_DIR . "/simplepie/" . sha1($fetch_url) . ".xml";
    $pluginhost = new PluginHost();
    $pluginhost->set_debug($debug_enabled);
    $user_plugins = get_pref("_ENABLED_PLUGINS", $owner_uid);
    $pluginhost->load(PLUGINS, PluginHost::KIND_ALL);
    $pluginhost->load($user_plugins, PluginHost::KIND_USER, $owner_uid);
    $pluginhost->load_data();
    $rss = false;
    $rss_hash = false;
    $force_refetch = isset($_REQUEST["force_refetch"]);
    if (file_exists($cache_filename) && is_readable($cache_filename) && !$auth_login && !$auth_pass && filemtime($cache_filename) > time() - 30) {
        _debug("using local cache.", $debug_enabled);
        @($feed_data = file_get_contents($cache_filename));
        if ($feed_data) {
            $rss_hash = sha1($feed_data);
        }
    } else {
        _debug("local cache will not be used for this feed", $debug_enabled);
    }
    if (!$rss) {
        foreach ($pluginhost->get_hooks(PluginHost::HOOK_FETCH_FEED) as $plugin) {
            $feed_data = $plugin->hook_fetch_feed($feed_data, $fetch_url, $owner_uid, $feed);
        }
        if (!$feed_data) {
            _debug("fetching [{$fetch_url}]...", $debug_enabled);
            _debug("If-Modified-Since: " . gmdate('D, d M Y H:i:s \\G\\M\\T', $last_article_timestamp), $debug_enabled);
            $feed_data = fetch_file_contents($fetch_url, false, $auth_login, $auth_pass, false, $no_cache ? FEED_FETCH_NO_CACHE_TIMEOUT : FEED_FETCH_TIMEOUT, $force_refetch ? 0 : $last_article_timestamp);
            global $fetch_curl_used;
            if (!$fetch_curl_used) {
                $tmp = @gzdecode($feed_data);
                if ($tmp) {
                    $feed_data = $tmp;
                }
            }
            $feed_data = trim($feed_data);
            _debug("fetch done.", $debug_enabled);
            /* if ($feed_data) {
            					$error = verify_feed_xml($feed_data);
            
            					if ($error) {
            						_debug("error verifying XML, code: " . $error->code, $debug_enabled);
            
            						if ($error->code == 26) {
            							_debug("got error 26, trying to decode entities...", $debug_enabled);
            
            							$feed_data = html_entity_decode($feed_data, ENT_COMPAT, 'UTF-8');
            
            							$error = verify_feed_xml($feed_data);
            
            							if ($error) $feed_data = '';
            						}
            					}
            				} */
        }
        if (!$feed_data) {
            global $fetch_last_error;
            global $fetch_last_error_code;
            _debug("unable to fetch: {$fetch_last_error} [{$fetch_last_error_code}]", $debug_enabled);
            $error_escaped = '';
            // If-Modified-Since
            if ($fetch_last_error_code != 304) {
                $error_escaped = db_escape_string($fetch_last_error);
            } else {
                _debug("source claims data not modified, nothing to do.", $debug_enabled);
            }
            db_query("UPDATE ttrss_feeds SET last_error = '{$error_escaped}',\n\t\t\t\t\t\tlast_updated = NOW() WHERE id = '{$feed}'");
            return;
        }
    }
    foreach ($pluginhost->get_hooks(PluginHost::HOOK_FEED_FETCHED) as $plugin) {
        $feed_data = $plugin->hook_feed_fetched($feed_data, $fetch_url, $owner_uid, $feed);
    }
    // set last update to now so if anything *simplepie* crashes later we won't be
    // continuously failing on the same feed
    //db_query("UPDATE ttrss_feeds SET last_updated = NOW() WHERE id = '$feed'");
    if (!$rss) {
        $rss = new FeedParser($feed_data);
        $rss->init();
    }
    //		print_r($rss);
    $feed = db_escape_string($feed);
    if (!$rss->error()) {
        // cache data for later
        if (!$auth_pass && !$auth_login && is_writable(CACHE_DIR . "/simplepie")) {
            $new_rss_hash = sha1($rss_data);
            if ($new_rss_hash != $rss_hash && count($rss->get_items()) > 0) {
                _debug("saving {$cache_filename}", $debug_enabled);
                @file_put_contents($cache_filename, $feed_data);
            }
        }
        // We use local pluginhost here because we need to load different per-user feed plugins
        $pluginhost->run_hooks(PluginHost::HOOK_FEED_PARSED, "hook_feed_parsed", $rss);
        _debug("processing feed data...", $debug_enabled);
        //			db_query("BEGIN");
        if (DB_TYPE == "pgsql") {
            $favicon_interval_qpart = "favicon_last_checked < NOW() - INTERVAL '12 hour'";
        } else {
            $favicon_interval_qpart = "favicon_last_checked < DATE_SUB(NOW(), INTERVAL 12 HOUR)";
        }
        $result = db_query("SELECT title,site_url,owner_uid,favicon_avg_color,\n\t\t\t\t(favicon_last_checked IS NULL OR {$favicon_interval_qpart}) AS\n\t\t\t\t\t\tfavicon_needs_check\n\t\t\t\tFROM ttrss_feeds WHERE id = '{$feed}'");
        $registered_title = db_fetch_result($result, 0, "title");
        $orig_site_url = db_fetch_result($result, 0, "site_url");
        $favicon_needs_check = sql_bool_to_bool(db_fetch_result($result, 0, "favicon_needs_check"));
        $favicon_avg_color = db_fetch_result($result, 0, "favicon_avg_color");
        $owner_uid = db_fetch_result($result, 0, "owner_uid");
        $site_url = db_escape_string(mb_substr(rewrite_relative_url($fetch_url, $rss->get_link()), 0, 245));
        _debug("site_url: {$site_url}", $debug_enabled);
        _debug("feed_title: " . $rss->get_title(), $debug_enabled);
        if ($favicon_needs_check || $force_refetch) {
            /* terrible hack: if we crash on floicon shit here, we won't check
             * the icon avgcolor again (unless the icon got updated) */
            $favicon_file = ICONS_DIR . "/{$feed}.ico";
            $favicon_modified = @filemtime($favicon_file);
            _debug("checking favicon...", $debug_enabled);
            check_feed_favicon($site_url, $feed);
            $favicon_modified_new = @filemtime($favicon_file);
            if ($favicon_modified_new > $favicon_modified) {
                $favicon_avg_color = '';
            }
            if (file_exists($favicon_file) && function_exists("imagecreatefromstring") && $favicon_avg_color == '') {
                require_once "colors.php";
                db_query("UPDATE ttrss_feeds SET favicon_avg_color = 'fail' WHERE\n\t\t\t\t\t\t\tid = '{$feed}'");
                $favicon_color = db_escape_string(calculate_avg_color($favicon_file));
                $favicon_colorstring = ",favicon_avg_color = '" . $favicon_color . "'";
            } else {
                if ($favicon_avg_color == 'fail') {
                    _debug("floicon failed on this file, not trying to recalculate avg color", $debug_enabled);
                }
            }
            db_query("UPDATE ttrss_feeds SET favicon_last_checked = NOW()\n\t\t\t\t\t{$favicon_colorstring}\n\t\t\t\t\tWHERE id = '{$feed}'");
        }
        if (!$registered_title || $registered_title == "[Unknown]") {
            $feed_title = db_escape_string($rss->get_title());
            if ($feed_title) {
                _debug("registering title: {$feed_title}", $debug_enabled);
                db_query("UPDATE ttrss_feeds SET\n\t\t\t\t\t\ttitle = '{$feed_title}' WHERE id = '{$feed}'");
            }
        }
        if ($site_url && $orig_site_url != $site_url) {
            db_query("UPDATE ttrss_feeds SET\n\t\t\t\t\tsite_url = '{$site_url}' WHERE id = '{$feed}'");
        }
        _debug("loading filters & labels...", $debug_enabled);
        $filters = load_filters($feed, $owner_uid);
        $labels = get_all_labels($owner_uid);
        _debug("" . count($filters) . " filters loaded.", $debug_enabled);
        $items = $rss->get_items();
        if (!is_array($items)) {
            _debug("no articles found.", $debug_enabled);
            db_query("UPDATE ttrss_feeds\n\t\t\t\t\tSET last_updated = NOW(), last_error = '' WHERE id = '{$feed}'");
            return;
            // no articles
        }
        if ($pubsub_state != 2 && PUBSUBHUBBUB_ENABLED) {
            _debug("checking for PUSH hub...", $debug_enabled);
            $feed_hub_url = false;
            $links = $rss->get_links('hub');
            if ($links && is_array($links)) {
                foreach ($links as $l) {
                    $feed_hub_url = $l;
                    break;
                }
            }
            _debug("feed hub url: {$feed_hub_url}", $debug_enabled);
            if ($feed_hub_url && function_exists('curl_init') && !ini_get("open_basedir")) {
                require_once 'lib/pubsubhubbub/subscriber.php';
                $callback_url = get_self_url_prefix() . "/public.php?op=pubsub&id={$feed}";
                $s = new Subscriber($feed_hub_url, $callback_url);
                $rc = $s->subscribe($fetch_url);
                _debug("feed hub url found, subscribe request sent.", $debug_enabled);
                db_query("UPDATE ttrss_feeds SET pubsub_state = 1\n\t\t\t\t\t\tWHERE id = '{$feed}'");
            }
        }
        _debug("processing articles...", $debug_enabled);
        foreach ($items as $item) {
            if ($_REQUEST['xdebug'] == 3) {
                print_r($item);
            }
            $entry_guid = $item->get_id();
            if (!$entry_guid) {
                $entry_guid = $item->get_link();
            }
            if (!$entry_guid) {
                $entry_guid = make_guid_from_title($item->get_title());
            }
            _debug("f_guid {$entry_guid}", $debug_enabled);
            if (!$entry_guid) {
                continue;
            }
            $entry_guid = "{$owner_uid},{$entry_guid}";
            $entry_guid_hashed = db_escape_string('SHA1:' . sha1($entry_guid));
            _debug("guid {$entry_guid} / {$entry_guid_hashed}", $debug_enabled);
            $entry_timestamp = "";
            $entry_timestamp = $item->get_date();
            _debug("orig date: " . $item->get_date(), $debug_enabled);
            if ($entry_timestamp == -1 || !$entry_timestamp || $entry_timestamp > time()) {
                $entry_timestamp = time();
                $no_orig_date = 'true';
            } else {
                $no_orig_date = 'false';
            }
            $entry_timestamp_fmt = strftime("%Y/%m/%d %H:%M:%S", $entry_timestamp);
            _debug("date {$entry_timestamp} [{$entry_timestamp_fmt}]", $debug_enabled);
            //				$entry_title = html_entity_decode($item->get_title(), ENT_COMPAT, 'UTF-8');
            //				$entry_title = decode_numeric_entities($entry_title);
            $entry_title = $item->get_title();
            $entry_link = rewrite_relative_url($site_url, $item->get_link());
            _debug("title {$entry_title}", $debug_enabled);
            _debug("link {$entry_link}", $debug_enabled);
            if (!$entry_title) {
                $entry_title = date("Y-m-d H:i:s", $entry_timestamp);
            }
            $entry_content = $item->get_content();
            if (!$entry_content) {
                $entry_content = $item->get_description();
            }
            if ($_REQUEST["xdebug"] == 2) {
                print "content: ";
                print $entry_content;
                print "\n";
            }
            $entry_comments = $item->get_comments_url();
            $entry_author = $item->get_author();
            $entry_guid = db_escape_string(mb_substr($entry_guid, 0, 245));
            $entry_comments = db_escape_string(mb_substr(trim($entry_comments), 0, 245));
            $entry_author = db_escape_string(mb_substr(trim($entry_author), 0, 245));
            $num_comments = (int) $item->get_comments_count();
            _debug("author {$entry_author}", $debug_enabled);
            _debug("num_comments: {$num_comments}", $debug_enabled);
            _debug("looking for tags...", $debug_enabled);
            // parse <category> entries into tags
            $additional_tags = array();
            $additional_tags_src = $item->get_categories();
            if (is_array($additional_tags_src)) {
                foreach ($additional_tags_src as $tobj) {
                    array_push($additional_tags, $tobj);
                }
            }
            $entry_tags = array_unique($additional_tags);
            for ($i = 0; $i < count($entry_tags); $i++) {
                $entry_tags[$i] = mb_strtolower($entry_tags[$i], 'utf-8');
            }
            _debug("tags found: " . join(",", $entry_tags), $debug_enabled);
            _debug("done collecting data.", $debug_enabled);
            // TODO: less memory-hungry implementation
            _debug("applying plugin filters..", $debug_enabled);
            // FIXME not sure if owner_uid is a good idea here, we may have a base entry without user entry (?)
            $result = db_query("SELECT plugin_data,title,content,link,tag_cache,author FROM ttrss_entries, ttrss_user_entries\n\t\t\t\t\tWHERE ref_id = id AND (guid = '" . db_escape_string($entry_guid) . "' OR guid = '{$entry_guid_hashed}') AND owner_uid = {$owner_uid}");
            if (db_num_rows($result) != 0) {
                $entry_plugin_data = db_fetch_result($result, 0, "plugin_data");
                $stored_article = array("title" => db_fetch_result($result, 0, "title"), "content" => db_fetch_result($result, 0, "content"), "link" => db_fetch_result($result, 0, "link"), "tags" => explode(",", db_fetch_result($result, 0, "tag_cache")), "author" => db_fetch_result($result, 0, "author"));
            } else {
                $entry_plugin_data = "";
                $stored_article = array();
            }
            $article = array("owner_uid" => $owner_uid, "guid" => $entry_guid, "title" => $entry_title, "content" => $entry_content, "link" => $entry_link, "tags" => $entry_tags, "plugin_data" => $entry_plugin_data, "author" => $entry_author, "stored" => $stored_article);
            foreach ($pluginhost->get_hooks(PluginHost::HOOK_ARTICLE_FILTER) as $plugin) {
                $article = $plugin->hook_article_filter($article);
            }
            $entry_tags = $article["tags"];
            $entry_guid = db_escape_string($entry_guid);
            $entry_title = db_escape_string($article["title"]);
            $entry_author = db_escape_string($article["author"]);
            $entry_link = db_escape_string($article["link"]);
            $entry_plugin_data = db_escape_string($article["plugin_data"]);
            $entry_content = $article["content"];
            // escaped below
            _debug("plugin data: {$entry_plugin_data}", $debug_enabled);
            if ($cache_images && is_writable(CACHE_DIR . '/images')) {
                cache_images($entry_content, $site_url, $debug_enabled);
            }
            $entry_content = db_escape_string($entry_content, false);
            $content_hash = "SHA1:" . sha1($entry_content);
            db_query("BEGIN");
            $result = db_query("SELECT id FROM\tttrss_entries\n\t\t\t\t\tWHERE (guid = '{$entry_guid}' OR guid = '{$entry_guid_hashed}')");
            if (db_num_rows($result) == 0) {
                _debug("base guid [{$entry_guid}] not found", $debug_enabled);
                // base post entry does not exist, create it
                $result = db_query("INSERT INTO ttrss_entries\n\t\t\t\t\t\t\t(title,\n\t\t\t\t\t\t\tguid,\n\t\t\t\t\t\t\tlink,\n\t\t\t\t\t\t\tupdated,\n\t\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t\tcontent_hash,\n\t\t\t\t\t\t\tno_orig_date,\n\t\t\t\t\t\t\tdate_updated,\n\t\t\t\t\t\t\tdate_entered,\n\t\t\t\t\t\t\tcomments,\n\t\t\t\t\t\t\tnum_comments,\n\t\t\t\t\t\t\tplugin_data,\n\t\t\t\t\t\t\tauthor)\n\t\t\t\t\t\tVALUES\n\t\t\t\t\t\t\t('{$entry_title}',\n\t\t\t\t\t\t\t'{$entry_guid_hashed}',\n\t\t\t\t\t\t\t'{$entry_link}',\n\t\t\t\t\t\t\t'{$entry_timestamp_fmt}',\n\t\t\t\t\t\t\t'{$entry_content}',\n\t\t\t\t\t\t\t'{$content_hash}',\n\t\t\t\t\t\t\t{$no_orig_date},\n\t\t\t\t\t\t\tNOW(),\n\t\t\t\t\t\t\t'{$date_feed_processed}',\n\t\t\t\t\t\t\t'{$entry_comments}',\n\t\t\t\t\t\t\t'{$num_comments}',\n\t\t\t\t\t\t\t'{$entry_plugin_data}',\n\t\t\t\t\t\t\t'{$entry_author}')");
                $article_labels = array();
            } else {
                // we keep encountering the entry in feeds, so we need to
                // update date_updated column so that we don't get horrible
                // dupes when the entry gets purged and reinserted again e.g.
                // in the case of SLOW SLOW OMG SLOW updating feeds
                $base_entry_id = db_fetch_result($result, 0, "id");
                db_query("UPDATE ttrss_entries SET date_updated = NOW()\n\t\t\t\t\t\tWHERE id = '{$base_entry_id}'");
                $article_labels = get_article_labels($base_entry_id, $owner_uid);
            }
            // now it should exist, if not - bad luck then
            $result = db_query("SELECT\n\t\t\t\t\t\tid,content_hash,no_orig_date,title,plugin_data,guid,\n\t\t\t\t\t\t" . SUBSTRING_FOR_DATE . "(date_updated,1,19) as date_updated,\n\t\t\t\t\t\t" . SUBSTRING_FOR_DATE . "(updated,1,19) as updated,\n\t\t\t\t\t\tnum_comments\n\t\t\t\t\tFROM\n\t\t\t\t\t\tttrss_entries\n\t\t\t\t\tWHERE guid = '{$entry_guid}' OR guid = '{$entry_guid_hashed}'");
            $entry_ref_id = 0;
            $entry_int_id = 0;
            if (db_num_rows($result) == 1) {
                _debug("base guid found, checking for user record", $debug_enabled);
                // this will be used below in update handler
                $orig_content_hash = db_fetch_result($result, 0, "content_hash");
                $orig_title = db_fetch_result($result, 0, "title");
                $orig_num_comments = db_fetch_result($result, 0, "num_comments");
                $orig_date_updated = strtotime(db_fetch_result($result, 0, "date_updated"));
                $orig_plugin_data = db_fetch_result($result, 0, "plugin_data");
                $ref_id = db_fetch_result($result, 0, "id");
                $entry_ref_id = $ref_id;
                /* $stored_guid = db_fetch_result($result, 0, "guid");
                					if ($stored_guid != $entry_guid_hashed) {
                						if ($debug_enabled) _debug("upgrading compat guid to hashed one", $debug_enabled);
                
                						db_query("UPDATE ttrss_entries SET guid = '$entry_guid_hashed' WHERE
                							id = '$ref_id'");
                					} */
                // check for user post link to main table
                // do we allow duplicate posts with same GUID in different feeds?
                if (get_pref("ALLOW_DUPLICATE_POSTS", $owner_uid, false)) {
                    $dupcheck_qpart = "AND (feed_id = '{$feed}' OR feed_id IS NULL)";
                } else {
                    $dupcheck_qpart = "";
                }
                /* Collect article tags here so we could filter by them: */
                $article_filters = get_article_filters($filters, $entry_title, $entry_content, $entry_link, $entry_timestamp, $entry_author, $entry_tags);
                if ($debug_enabled) {
                    _debug("article filters: ", $debug_enabled);
                    if (count($article_filters) != 0) {
                        print_r($article_filters);
                    }
                }
                if (find_article_filter($article_filters, "filter")) {
                    db_query("COMMIT");
                    // close transaction in progress
                    continue;
                }
                $score = calculate_article_score($article_filters);
                _debug("initial score: {$score}", $debug_enabled);
                $query = "SELECT ref_id, int_id FROM ttrss_user_entries WHERE\n\t\t\t\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}'\n\t\t\t\t\t\t\t{$dupcheck_qpart}";
                //					if ($_REQUEST["xdebug"]) print "$query\n";
                $result = db_query($query);
                // okay it doesn't exist - create user entry
                if (db_num_rows($result) == 0) {
                    _debug("user record not found, creating...", $debug_enabled);
                    if ($score >= -500 && !find_article_filter($article_filters, 'catchup')) {
                        $unread = 'true';
                        $last_read_qpart = 'NULL';
                    } else {
                        $unread = 'false';
                        $last_read_qpart = 'NOW()';
                    }
                    if (find_article_filter($article_filters, 'mark') || $score > 1000) {
                        $marked = 'true';
                    } else {
                        $marked = 'false';
                    }
                    if (find_article_filter($article_filters, 'publish')) {
                        $published = 'true';
                    } else {
                        $published = 'false';
                    }
                    // N-grams
                    if (DB_TYPE == "pgsql" and defined('_NGRAM_TITLE_DUPLICATE_THRESHOLD')) {
                        $result = db_query("SELECT COUNT(*) AS similar FROM\n\t\t\t\t\t\t\t\t\tttrss_entries,ttrss_user_entries\n\t\t\t\t\t\t\t\tWHERE ref_id = id AND updated >= NOW() - INTERVAL '7 day'\n\t\t\t\t\t\t\t\t\tAND similarity(title, '{$entry_title}') >= " . _NGRAM_TITLE_DUPLICATE_THRESHOLD . "\n\t\t\t\t\t\t\t\t\tAND owner_uid = {$owner_uid}");
                        $ngram_similar = db_fetch_result($result, 0, "similar");
                        _debug("N-gram similar results: {$ngram_similar}", $debug_enabled);
                        if ($ngram_similar > 0) {
                            $unread = 'false';
                        }
                    }
                    $last_marked = $marked == 'true' ? 'NOW()' : 'NULL';
                    $last_published = $published == 'true' ? 'NOW()' : 'NULL';
                    $result = db_query("INSERT INTO ttrss_user_entries\n\t\t\t\t\t\t\t\t(ref_id, owner_uid, feed_id, unread, last_read, marked,\n\t\t\t\t\t\t\t\tpublished, score, tag_cache, label_cache, uuid,\n\t\t\t\t\t\t\t\tlast_marked, last_published)\n\t\t\t\t\t\t\tVALUES ('{$ref_id}', '{$owner_uid}', '{$feed}', {$unread},\n\t\t\t\t\t\t\t\t{$last_read_qpart}, {$marked}, {$published}, '{$score}', '', '',\n\t\t\t\t\t\t\t\t'', {$last_marked}, {$last_published})");
                    if (PUBSUBHUBBUB_HUB && $published == 'true') {
                        $rss_link = get_self_url_prefix() . "/public.php?op=rss&id=-2&key=" . get_feed_access_key(-2, false, $owner_uid);
                        $p = new Publisher(PUBSUBHUBBUB_HUB);
                        $pubsub_result = $p->publish_update($rss_link);
                    }
                    $result = db_query("SELECT int_id FROM ttrss_user_entries WHERE\n\t\t\t\t\t\t\t\tref_id = '{$ref_id}' AND owner_uid = '{$owner_uid}' AND\n\t\t\t\t\t\t\t\tfeed_id = '{$feed}' LIMIT 1");
                    if (db_num_rows($result) == 1) {
                        $entry_int_id = db_fetch_result($result, 0, "int_id");
                    }
                } else {
                    _debug("user record FOUND", $debug_enabled);
                    $entry_ref_id = db_fetch_result($result, 0, "ref_id");
                    $entry_int_id = db_fetch_result($result, 0, "int_id");
                }
                _debug("RID: {$entry_ref_id}, IID: {$entry_int_id}", $debug_enabled);
                $post_needs_update = false;
                $update_insignificant = false;
                if ($orig_num_comments != $num_comments) {
                    $post_needs_update = true;
                    $update_insignificant = true;
                }
                if ($entry_plugin_data != $orig_plugin_data) {
                    $post_needs_update = true;
                    $update_insignificant = true;
                }
                if ($content_hash != $orig_content_hash) {
                    $post_needs_update = true;
                    $update_insignificant = false;
                }
                if (db_escape_string($orig_title) != $entry_title) {
                    $post_needs_update = true;
                    $update_insignificant = false;
                }
                // if post needs update, update it and mark all user entries
                // linking to this post as updated
                if ($post_needs_update) {
                    if (defined('DAEMON_EXTENDED_DEBUG')) {
                        _debug("post {$entry_guid_hashed} needs update...", $debug_enabled);
                    }
                    //						print "<!-- post $orig_title needs update : $post_needs_update -->";
                    db_query("UPDATE ttrss_entries\n\t\t\t\t\t\t\tSET title = '{$entry_title}', content = '{$entry_content}',\n\t\t\t\t\t\t\t\tcontent_hash = '{$content_hash}',\n\t\t\t\t\t\t\t\tupdated = '{$entry_timestamp_fmt}',\n\t\t\t\t\t\t\t\tnum_comments = '{$num_comments}',\n\t\t\t\t\t\t\t\tplugin_data = '{$entry_plugin_data}'\n\t\t\t\t\t\t\tWHERE id = '{$ref_id}'");
                    if (!$update_insignificant) {
                        if ($mark_unread_on_update) {
                            db_query("UPDATE ttrss_user_entries\n\t\t\t\t\t\t\t\t\tSET last_read = null, unread = true WHERE ref_id = '{$ref_id}'");
                        }
                    }
                }
            }
            db_query("COMMIT");
            _debug("assigning labels...", $debug_enabled);
            assign_article_to_label_filters($entry_ref_id, $article_filters, $owner_uid, $article_labels);
            _debug("looking for enclosures...", $debug_enabled);
            // enclosures
            $enclosures = array();
            $encs = $item->get_enclosures();
            if (is_array($encs)) {
                foreach ($encs as $e) {
                    $e_item = array($e->link, $e->type, $e->length);
                    array_push($enclosures, $e_item);
                }
            }
            if ($debug_enabled) {
                _debug("article enclosures:", $debug_enabled);
                print_r($enclosures);
            }
            db_query("BEGIN");
            foreach ($enclosures as $enc) {
                $enc_url = db_escape_string($enc[0]);
                $enc_type = db_escape_string($enc[1]);
                $enc_dur = db_escape_string($enc[2]);
                $result = db_query("SELECT id FROM ttrss_enclosures\n\t\t\t\t\t\tWHERE content_url = '{$enc_url}' AND post_id = '{$entry_ref_id}'");
                if (db_num_rows($result) == 0) {
                    db_query("INSERT INTO ttrss_enclosures\n\t\t\t\t\t\t\t(content_url, content_type, title, duration, post_id) VALUES\n\t\t\t\t\t\t\t('{$enc_url}', '{$enc_type}', '', '{$enc_dur}', '{$entry_ref_id}')");
                }
            }
            db_query("COMMIT");
            // check for manual tags (we have to do it here since they're loaded from filters)
            foreach ($article_filters as $f) {
                if ($f["type"] == "tag") {
                    $manual_tags = trim_array(explode(",", $f["param"]));
                    foreach ($manual_tags as $tag) {
                        if (tag_is_valid($tag)) {
                            array_push($entry_tags, $tag);
                        }
                    }
                }
            }
            // Skip boring tags
            $boring_tags = trim_array(explode(",", mb_strtolower(get_pref('BLACKLISTED_TAGS', $owner_uid, ''), 'utf-8')));
            $filtered_tags = array();
            $tags_to_cache = array();
            if ($entry_tags && is_array($entry_tags)) {
                foreach ($entry_tags as $tag) {
                    if (array_search($tag, $boring_tags) === false) {
                        array_push($filtered_tags, $tag);
                    }
                }
            }
            $filtered_tags = array_unique($filtered_tags);
            if ($debug_enabled) {
                _debug("filtered article tags:", $debug_enabled);
                print_r($filtered_tags);
            }
            // Save article tags in the database
            if (count($filtered_tags) > 0) {
                db_query("BEGIN");
                foreach ($filtered_tags as $tag) {
                    $tag = sanitize_tag($tag);
                    $tag = db_escape_string($tag);
                    if (!tag_is_valid($tag)) {
                        continue;
                    }
                    $result = db_query("SELECT id FROM ttrss_tags\n\t\t\t\t\t\t\tWHERE tag_name = '{$tag}' AND post_int_id = '{$entry_int_id}' AND\n\t\t\t\t\t\t\towner_uid = '{$owner_uid}' LIMIT 1");
                    if ($result && db_num_rows($result) == 0) {
                        db_query("INSERT INTO ttrss_tags\n\t\t\t\t\t\t\t\t\t(owner_uid,tag_name,post_int_id)\n\t\t\t\t\t\t\t\t\tVALUES ('{$owner_uid}','{$tag}', '{$entry_int_id}')");
                    }
                    array_push($tags_to_cache, $tag);
                }
                /* update the cache */
                $tags_to_cache = array_unique($tags_to_cache);
                $tags_str = db_escape_string(join(",", $tags_to_cache));
                db_query("UPDATE ttrss_user_entries\n\t\t\t\t\t\tSET tag_cache = '{$tags_str}' WHERE ref_id = '{$entry_ref_id}'\n\t\t\t\t\t\tAND owner_uid = {$owner_uid}");
                db_query("COMMIT");
            }
            if (get_pref("AUTO_ASSIGN_LABELS", $owner_uid, false)) {
                _debug("auto-assigning labels...", $debug_enabled);
                foreach ($labels as $label) {
                    $caption = preg_quote($label["caption"]);
                    if ($caption && preg_match("/\\b{$caption}\\b/i", "{$tags_str} " . strip_tags($entry_content) . " {$entry_title}")) {
                        if (!labels_contains_caption($article_labels, $caption)) {
                            label_add_article($entry_ref_id, $caption, $owner_uid);
                        }
                    }
                }
            }
            _debug("article processed", $debug_enabled);
        }
        _debug("purging feed...", $debug_enabled);
        purge_feed($feed, 0, $debug_enabled);
        db_query("UPDATE ttrss_feeds\n\t\t\t\tSET last_updated = NOW(), last_error = '' WHERE id = '{$feed}'");
        //			db_query("COMMIT");
    } else {
        $error_msg = db_escape_string(mb_substr($rss->error(), 0, 245));
        _debug("error fetching feed: {$error_msg}", $debug_enabled);
        db_query("UPDATE ttrss_feeds SET last_error = '{$error_msg}',\n\t\t\t\t\tlast_updated = NOW() WHERE id = '{$feed}'");
    }
    unset($rss);
    _debug("done", $debug_enabled);
}
예제 #28
0
<?php

/*
 *	
 *		Basic Blogger Data Dump
 *		This file will download your blogger feed and save to log file
 *
 */
include 'class.feedparser.php';
$feed = new FeedParser();
$limit = 1;
$user = '******';
$data = $feed->blogger($user, $limit);
$fh = fopen('blogger.log', 'w');
fwrite($fh, print_r($data, 1));
fclose($fh);
echo "Downloaded " . count($data['posts']) . " posts\n";
echo "Bandwidth Usage: {$feed->bandwidth}\n";
echo "Requests: {$feed->requests}\n";
echo "\n";