get_description() public méthode

Uses , , , , or
Since: 1.0 (previously called `get_feed_description()` since 0.8)
public get_description ( ) : string | null
Résultat string | null
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     if ($this->rss_template != 'rss_default') {
         $this->strTemplate = $this->rss_template;
         /** @var FrontendTemplate|object $objTemplate */
         $objTemplate = new \FrontendTemplate($this->strTemplate);
         $this->Template = $objTemplate;
         $this->Template->setData($this->arrData);
     }
     $this->Template->link = $this->objFeed->get_link();
     $this->Template->title = $this->objFeed->get_title();
     $this->Template->language = $this->objFeed->get_language();
     $this->Template->description = $this->objFeed->get_description();
     $this->Template->copyright = $this->objFeed->get_copyright();
     // Add image
     if ($this->objFeed->get_image_url()) {
         $this->Template->image = true;
         $this->Template->src = $this->objFeed->get_image_url();
         $this->Template->alt = $this->objFeed->get_image_title();
         $this->Template->href = $this->objFeed->get_image_link();
         $this->Template->height = $this->objFeed->get_image_height();
         $this->Template->width = $this->objFeed->get_image_width();
     }
     // Get the items (see #6107)
     $arrItems = array_slice($this->objFeed->get_items(0, intval($this->numberOfItems) + intval($this->skipFirst)), intval($this->skipFirst), intval($this->numberOfItems) ?: null);
     $limit = count($arrItems);
     $offset = 0;
     // Split pages
     if ($this->perPage > 0) {
         // Get the current page
         $id = 'page_r' . $this->id;
         $page = \Input::get($id) !== null ? \Input::get($id) : 1;
         // Do not index or cache the page if the page number is outside the range
         if ($page < 1 || $page > max(ceil(count($arrItems) / $this->perPage), 1)) {
             throw new PageNotFoundException('Page not found: ' . \Environment::get('uri'));
         }
         // Set limit and offset
         $offset = ($page - 1) * $this->perPage;
         $limit = $this->perPage + $offset;
         $objPagination = new \Pagination(count($arrItems), $this->perPage, \Config::get('maxPaginationLinks'), $id);
         $this->Template->pagination = $objPagination->generate("\n  ");
     }
     $items = array();
     $last = min($limit, count($arrItems)) - 1;
     /** @var \SimplePie_Item[] $arrItems */
     for ($i = $offset, $c = count($arrItems); $i < $limit && $i < $c; $i++) {
         $items[$i] = array('link' => $arrItems[$i]->get_link(), 'title' => $arrItems[$i]->get_title(), 'permalink' => $arrItems[$i]->get_permalink(), 'description' => str_replace(array('<?', '?>'), array('&lt;?', '?&gt;'), $arrItems[$i]->get_description()), 'class' => ($i == 0 ? ' first' : '') . ($i == $last ? ' last' : '') . ($i % 2 == 0 ? ' even' : ' odd'), 'pubdate' => \Date::parse($objPage->datimFormat, $arrItems[$i]->get_date('U')), 'category' => $arrItems[$i]->get_category(0), 'object' => $arrItems[$i]);
         // Add author
         if (($objAuthor = $arrItems[$i]->get_author(0)) != false) {
             $items[$i]['author'] = trim($objAuthor->name . ' ' . $objAuthor->email);
         }
         // Add enclosure
         if (($objEnclosure = $arrItems[$i]->get_enclosure(0)) != false) {
             $items[$i]['enclosure'] = $objEnclosure->get_link();
         }
     }
     $this->Template->items = array_values($items);
 }
Exemple #2
0
 function tagAction()
 {
     $tag = $this->_request->getParam('tag');
     if (empty($tag)) {
         $this->_redirect('/index');
     }
     $feed = new SimplePie("http://baphled.wordpress.com/tag/{$tag}/feed");
     $feed->init();
     $this->view->description = $feed->get_description();
     $this->view->title = $feed->get_title();
     $this->view->items = $feed->get_items();
     $this->render('feed');
 }
 public function addAction()
 {
     require_once PLUGIN_DIR . "/FeedImporter/libraries/SimplePie/simplepie.inc";
     $feed = new SimplePie();
     $varName = strtolower($this->_modelClass);
     $class = $this->_modelClass;
     $record = new FeedImporter_Feed();
     //Need an id to work with the tags, so save it now, even though it might be sloppy/confusing
     $record->save();
     if ($_GET['feed_url']) {
         $feed_url = $_GET['feed_url'];
         $debug = new stdClass();
         $feed->set_feed_url($feed_url);
         // Run SimplePie.
         $feed->init();
         $feed->handle_content_type();
         if ($feed->error()) {
             $this->flash($feed->error());
             //return here?
         }
         $debug->title = $feed->get_title();
         $debug->description = $feed->get_description();
         //Set up the tag configurations for the first import
         $import = new FeedImporter_Import();
         $import->processFeedTags($feed, $record->id);
         $record->feed_url = $feed_url;
         $record->feed_title = $feed->get_title();
         $record->feed_description = $feed->get_description();
     }
     $record->save();
     // Create a new FakeCron_Task for the feed
     $fc_task = new FakeCron_Task();
     $fc_task->interval = 0;
     $fc_task->name = "Cron for feed " . $record->feed_title;
     $fc_task->plugin_class = "FeedImporter_FakeCronTask";
     $fc_task->plugin_name = 'FeedImporter';
     $fc_task->params = serialize(array($record->id));
     $fc_task->save();
     $record->task_id = $fc_task->id;
     $_POST['task_id'] = $fc_task->id;
     $this->view->assign(array($varName => $record));
     try {
         if ($record->saveForm($_POST)) {
             $this->redirect->goto('browse');
         }
     } catch (Omeka_Validator_Exception $e) {
         $this->flashValidationErrors($e);
     } catch (Exception $e) {
         $this->flash($e->getMessage());
     }
 }
 /**
  * Handles all of the heavy lifting for getting the feed, parsing it, and managing customizations.
  *
  * @access private
  * @param mixed $url Either a single feed URL (as a string) or an array of feed URLs (as an array of strings).
  * @param array $options An associative array of options that the function should take into account when rendering the markup.
  * <ul>
  *     <li>string $classname  - The classname that the <div> surrounding the feed should have. Defaults to nb-list for newsblocks::listing() and nb-wide for newsblocks::wide().</li>
  *     <li>string $copyright - The copyright string to use for a feed. Not part of the standard output, but it's available if you want to use it. Defaults to NULL with multifeeds; Use $item->get_feed()->get_copyright() instead.</li>
  *     <li>string $date_format - The format to use when displaying dates on items. Uses values from http://php.net/strftime, NOT http://php.net/date.</li>
  *     <li>string $description - The description for the feed (not the item). Not part of the standard output, but it's available if you want to use it. Defaults to NULL with multifeeds; Use $item->get_feed()->get_description() instead.</li>
  *     <li>string $direction - The direction of the text. Valid values are "ltr" and "rtl". Defaults to "ltr".</li>
  *     <li>string $favicon - The favicon URL to use for the feed. Since favicon URLs aren't actually located in feeds, SimplePie guesses. Sometimes that guess is wrong. Give it the correct favicon with this option. Defaults to NULL with multifeeds; Use $item->get_feed()->get_favicon() instead.</li>
  *     <li>string $id - The ID attribute that the <div> surrounding the feed should have. This value should be unique per feed. Defaults to a SHA1 hash value based on the URL(s).</li>
  *     <li>string $item_classname - The classname for the items. Useful for styling with CSS. Also useful for JavaScript in creating custom tooltips for a feed. Defaults to "tips".</li>
  *     <li>integer $items - The number of items to show (the rest are hidden until "More" is clicked). Defaults to 10.</li>
  *     <li>string $language - The language of the feed. Not part of the standard output, but it's available if you want to use it. Defaults to NULL with multifeeds; Use $item->get_feed()->get_language() instead.</li>
  *     <li>integer $length - The maximum character length of the item description in the tooltip. Defaults to 200.</li>
  *     <li>string $more - The text to use for the "More" link. Defaults to "More &raquo;"</li>
  *     <li>boolean $more_move - Whether the "More" link should move when it's clicked. Defaults to FALSE (i.e. stays in the same place).</li>
  *     <li>boolean $more_fx - Whether the secondary list should slide or simply appear/disappear when the "More" link is clicked. Defaults to TRUE (i.e. slides).</li>
  *     <li>string $permalink - The permalink for the feed (not the item). Defaults to NULL with multifeeds; Use $item->get_feed()->get_permalink() instead.</li>
  *     <li>boolean $show_title - Whether to show the title of the feed. Defaults to TRUE.</li>
  *     <li>integer $since - A Unix timestamp. Anything posted more recently than this timestamp will get the "New" image applied to it. Defaults to 24 hours ago.</li>
  *     <li>$string $title - The title for the feed (not the item). Defaults to multiple titles with multifeeds, so you should manually set it in that case.</li>
  * </ul>
  * @return string The (X)HTML markup to display on the page.
  */
 function data($url, $options = null)
 {
     // Create a new SimplePie instance with this feed
     $feed = new SimplePie();
     $feed->set_feed_url($url);
     $feed->init();
     // Prep URL values to hash later.
     if (!is_array($url)) {
         $hash_str = array($url);
     } else {
         $hash_str = $url;
     }
     // Set the default values.
     $classname = null;
     $copyright = $feed->get_copyright();
     $date_format = '%a, %e %b %Y, %I:%M %p';
     $description = $feed->get_description();
     $direction = 'ltr';
     $favicon = $feed->get_favicon();
     $id = 'a' . sha1(implode('', $hash_str));
     $item_classname = 'tips';
     $items = 10;
     $language = $feed->get_language();
     $length = 200;
     $more = 'More &raquo;';
     $more_move = false;
     $more_fx = true;
     $permalink = $feed->get_permalink();
     $show_title = true;
     $since = time() - 24 * 60 * 60;
     // 24 hours ago.
     $title = $feed->get_title();
     // Override defaults with passed-in values.
     extract($options);
     // Set values for those that are still null
     if (!$favicon) {
         $favicon = NB_FAVICON_DEFAULT;
     }
     if (!$title) {
         if (is_array($url)) {
             $feed_title = array();
             foreach ($url as $u) {
                 $feed_title[] = newsblocks::name($u);
             }
             $title = implode(', ', $feed_title);
         }
     }
     // Send the data back to the calling function.
     return array('classname' => $classname, 'copyright' => $copyright, 'date_format' => $date_format, 'description' => $description, 'direction' => $direction, 'favicon' => $favicon, 'feed' => $feed, 'id' => $id, 'item_classname' => $item_classname, 'items' => $items, 'language' => $language, 'length' => $length, 'more' => $more, 'more_move' => $more_move, 'more_fx' => $more_fx, 'permalink' => $permalink, 'show_title' => $show_title, 'since' => $since, 'title' => $title);
 }
 /**
  * Implements CollectionAbstract::buildDocument().
  *
  * @param IndexDocument $document
  * @param \SimplePie_Item $data
  */
 public function buildDocument(IndexDocument $document, $data)
 {
     $document->source = $this->_feed->get_title();
     $document->subject = $this->_feed->get_description();
     $document->title = $data->get_title();
     $document->link = $data->get_link();
     $document->description = $data->get_description();
     $document->creator = (array) $data->get_author();
     $document->date = $data->get_date();
     // PHP properties cannot have dashes (-), and the fields below have
     // dashes in the field name.
     $document->source_link = $this->_feed->get_link();
     $document->getField('source_link')->setName('source-link');
     $document->item_subject = $this->_feed->get_link();
     $document->getField('item_subject')->setName('item-subject');
 }
Exemple #6
0
 private function view()
 {
     $feeds = $this->_db->queryAll('SELECT id, url, title FROM feeds WHERE user = ? ORDER BY title, url', $this->getIdUser());
     $this->info = array();
     foreach ($feeds as $feed) {
         $pie = new SimplePie();
         $pie->set_feed_url($feed['url']);
         $pie->set_cache_location(rtrim(DIR_TPL_COMPILE, '/'));
         $pie->init();
         $pie->handle_content_type();
         $items = $pie->get_items(0, self::FEED_MAX_ITEMS);
         $now = time();
         for ($i = count($items) - 1; $i != 0; --$i) {
             $time = $items[$i]->get_date('U');
             if ($time && $now - $time > self::FEED_MAX_DAYS * 86400) {
                 array_pop($items);
             }
         }
         $this->info[] = array('title' => empty($feed['title']) ? $pie->get_title() : $feed['title'], 'id' => $feed['id'], 'description' => $pie->get_description(), 'news' => $items);
     }
 }
Exemple #7
0
function probe_url($url, $mode = PROBE_NORMAL, $level = 1)
{
    require_once 'include/email.php';
    $result = array();
    if (!$url) {
        return $result;
    }
    $result = Cache::get("probe_url:" . $mode . ":" . $url);
    if (!is_null($result)) {
        $result = unserialize($result);
        return $result;
    }
    $network = null;
    $diaspora = false;
    $diaspora_base = '';
    $diaspora_guid = '';
    $diaspora_key = '';
    $has_lrdd = false;
    $email_conversant = false;
    $connectornetworks = false;
    $appnet = false;
    if (strpos($url, 'twitter.com')) {
        $connectornetworks = true;
        $network = NETWORK_TWITTER;
    }
    // Twitter is deactivated since twitter closed its old API
    //$twitter = ((strpos($url,'twitter.com') !== false) ? true : false);
    $lastfm = strpos($url, 'last.fm/user') !== false ? true : false;
    $at_addr = strpos($url, '@') !== false ? true : false;
    if (!$appnet && !$lastfm && !$connectornetworks) {
        if (strpos($url, 'mailto:') !== false && $at_addr) {
            $url = str_replace('mailto:', '', $url);
            $links = array();
        } else {
            $links = lrdd($url);
        }
        if (count($links)) {
            $has_lrdd = true;
            logger('probe_url: found lrdd links: ' . print_r($links, true), LOGGER_DATA);
            foreach ($links as $link) {
                if ($link['@attributes']['rel'] === NAMESPACE_ZOT) {
                    $zot = unamp($link['@attributes']['href']);
                }
                if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
                    $dfrn = unamp($link['@attributes']['href']);
                }
                if ($link['@attributes']['rel'] === 'salmon') {
                    $notify = unamp($link['@attributes']['href']);
                }
                if ($link['@attributes']['rel'] === NAMESPACE_FEED) {
                    $poll = unamp($link['@attributes']['href']);
                }
                if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
                    $hcard = unamp($link['@attributes']['href']);
                }
                if ($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page') {
                    $profile = unamp($link['@attributes']['href']);
                }
                if ($link['@attributes']['rel'] === 'http://portablecontacts.net/spec/1.0') {
                    $poco = unamp($link['@attributes']['href']);
                }
                if ($link['@attributes']['rel'] === 'http://joindiaspora.com/seed_location') {
                    $diaspora_base = unamp($link['@attributes']['href']);
                    $diaspora = true;
                }
                if ($link['@attributes']['rel'] === 'http://joindiaspora.com/guid') {
                    $diaspora_guid = unamp($link['@attributes']['href']);
                    $diaspora = true;
                }
                if ($link['@attributes']['rel'] === 'diaspora-public-key') {
                    $diaspora_key = base64_decode(unamp($link['@attributes']['href']));
                    if (strstr($diaspora_key, 'RSA ')) {
                        $pubkey = rsatopem($diaspora_key);
                    } else {
                        $pubkey = $diaspora_key;
                    }
                    $diaspora = true;
                }
                if ($link['@attributes']['rel'] === 'http://ostatus.org/schema/1.0/subscribe' and $mode == PROBE_NORMAL) {
                    $diaspora = false;
                }
            }
            // Status.Net can have more than one profile URL. We need to match the profile URL
            // to a contact on incoming messages to prevent spam, and we won't know which one
            // to match. So in case of two, one of them is stored as an alias. Only store URL's
            // and not webfinger user@host aliases. If they've got more than two non-email style
            // aliases, let's hope we're lucky and get one that matches the feed author-uri because
            // otherwise we're screwed.
            foreach ($links as $link) {
                if ($link['@attributes']['rel'] === 'alias') {
                    if (strpos($link['@attributes']['href'], '@') === false) {
                        if (isset($profile)) {
                            if ($link['@attributes']['href'] !== $profile) {
                                $alias = unamp($link['@attributes']['href']);
                            }
                        } else {
                            $profile = unamp($link['@attributes']['href']);
                        }
                    }
                }
            }
            // If the profile is different from the url then the url is abviously an alias
            if ($alias == "" and $profile != "" and !$at_addr and normalise_link($profile) != normalise_link($url)) {
                $alias = $url;
            }
        } elseif ($mode == PROBE_NORMAL) {
            // Check email
            $orig_url = $url;
            if (strpos($orig_url, '@') && validate_email($orig_url)) {
                $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval(local_user()));
                $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval(local_user()));
                if (count($x) && count($r)) {
                    $mailbox = construct_mailbox_name($r[0]);
                    $password = '';
                    openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
                    $mbox = email_connect($mailbox, $r[0]['user'], $password);
                    if (!$mbox) {
                        logger('probe_url: email_connect failed.');
                    }
                    unset($password);
                }
                if ($mbox) {
                    $msgs = email_poll($mbox, $orig_url);
                    logger('probe_url: searching ' . $orig_url . ', ' . count($msgs) . ' messages found.', LOGGER_DEBUG);
                    if (count($msgs)) {
                        $addr = $orig_url;
                        $network = NETWORK_MAIL;
                        $name = substr($url, 0, strpos($url, '@'));
                        $phost = substr($url, strpos($url, '@') + 1);
                        $profile = 'http://' . $phost;
                        // fix nick character range
                        $vcard = array('fn' => $name, 'nick' => $name, 'photo' => avatar_img($url));
                        $notify = 'smtp ' . random_string();
                        $poll = 'email ' . random_string();
                        $priority = 0;
                        $x = email_msg_meta($mbox, $msgs[0]);
                        if (stristr($x[0]->from, $orig_url)) {
                            $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
                        } elseif (stristr($x[0]->to, $orig_url)) {
                            $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
                        }
                        if (isset($adr)) {
                            foreach ($adr as $feadr) {
                                if (strcasecmp($feadr->mailbox, $name) == 0 && strcasecmp($feadr->host, $phost) == 0 && strlen($feadr->personal)) {
                                    $personal = imap_mime_header_decode($feadr->personal);
                                    $vcard['fn'] = "";
                                    foreach ($personal as $perspart) {
                                        if ($perspart->charset != "default") {
                                            $vcard['fn'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
                                        } else {
                                            $vcard['fn'] .= $perspart->text;
                                        }
                                    }
                                    $vcard['fn'] = notags($vcard['fn']);
                                }
                            }
                        }
                    }
                    imap_close($mbox);
                }
            }
        }
    }
    if ($mode == PROBE_NORMAL) {
        if (strlen($zot)) {
            $s = fetch_url($zot);
            if ($s) {
                $j = json_decode($s);
                if ($j) {
                    $network = NETWORK_ZOT;
                    $vcard = array('fn' => $j->fullname, 'nick' => $j->nickname, 'photo' => $j->photo);
                    $profile = $j->url;
                    $notify = $j->post;
                    $pubkey = $j->pubkey;
                    $poll = 'N/A';
                }
            }
        }
        if (strlen($dfrn)) {
            $ret = scrape_dfrn($hcard ? $hcard : $dfrn, true);
            if (is_array($ret) && x($ret, 'dfrn-request')) {
                $network = NETWORK_DFRN;
                $request = $ret['dfrn-request'];
                $confirm = $ret['dfrn-confirm'];
                $notify = $ret['dfrn-notify'];
                $poll = $ret['dfrn-poll'];
                $vcard = array();
                $vcard['fn'] = $ret['fn'];
                $vcard['nick'] = $ret['nick'];
                $vcard['photo'] = $ret['photo'];
            }
        }
    }
    if ($diaspora && $diaspora_base && $diaspora_guid) {
        if ($mode == PROBE_DIASPORA || !$notify) {
            $notify = $diaspora_base . 'receive/users/' . $diaspora_guid;
            $batch = $diaspora_base . 'receive/public';
        }
        if (strpos($url, '@')) {
            $addr = str_replace('acct:', '', $url);
        }
    }
    if ($network !== NETWORK_ZOT && $network !== NETWORK_DFRN && $network !== NETWORK_MAIL) {
        if ($diaspora) {
            $network = NETWORK_DIASPORA;
        } elseif ($has_lrdd and $notify) {
            $network = NETWORK_OSTATUS;
        }
        if (strpos($url, '@')) {
            $addr = str_replace('acct:', '', $url);
        }
        $priority = 0;
        if ($hcard && !$vcard) {
            $vcard = scrape_vcard($hcard);
            // Google doesn't use absolute url in profile photos
            if (x($vcard, 'photo') && substr($vcard['photo'], 0, 1) == '/') {
                $h = @parse_url($hcard);
                if ($h) {
                    $vcard['photo'] = $h['scheme'] . '://' . $h['host'] . $vcard['photo'];
                }
            }
            logger('probe_url: scrape_vcard: ' . print_r($vcard, true), LOGGER_DATA);
        }
        if ($diaspora && $addr) {
            // Diaspora returns the name as the nick. As the nick will never be updated,
            // let's use the Diaspora nickname (the first part of the handle) as the nick instead
            $addr_parts = explode('@', $addr);
            $vcard['nick'] = $addr_parts[0];
        }
        /* if($twitter) {
        			logger('twitter: setup');
        			$tid = basename($url);
        			$tapi = 'https://api.twitter.com/1/statuses/user_timeline.rss';
        			if(intval($tid))
        				$poll = $tapi . '?user_id=' . $tid;
        			else
        				$poll = $tapi . '?screen_name=' . $tid;
        			$profile = 'http://twitter.com/#!/' . $tid;
        			//$vcard['photo'] = 'https://api.twitter.com/1/users/profile_image/' . $tid;
        			$vcard['photo'] = 'https://api.twitter.com/1/users/profile_image?screen_name=' . $tid . '&size=bigger';
        			$vcard['nick'] = $tid;
        			$vcard['fn'] = $tid;
        		} */
        if ($lastfm) {
            $profile = $url;
            $poll = str_replace(array('www.', 'last.fm/'), array('', 'ws.audioscrobbler.com/1.0/'), $url) . '/recenttracks.rss';
            $vcard['nick'] = basename($url);
            $vcard['fn'] = $vcard['nick'] . t(' on Last.fm');
            $network = NETWORK_FEED;
        }
        if (!x($vcard, 'fn')) {
            if (x($vcard, 'nick')) {
                $vcard['fn'] = $vcard['nick'];
            }
        }
        $check_feed = false;
        if (stristr($url, 'tumblr.com') && !stristr($url, '/rss')) {
            $poll = $url . '/rss';
            $check_feed = true;
            // Will leave it to others to figure out how to grab the avatar, which is on the $url page in the open graph meta links
        }
        if ($appnet || !$poll) {
            $check_feed = true;
        }
        if (!isset($vcard) || !x($vcard, 'fn') || !$profile) {
            $check_feed = true;
        }
        if ($at_addr && !count($links)) {
            $check_feed = false;
        }
        if ($connectornetworks) {
            $check_feed = false;
        }
        if ($check_feed) {
            $feedret = scrape_feed($poll ? $poll : $url);
            logger('probe_url: scrape_feed ' . ($poll ? $poll : $url) . ' returns: ' . print_r($feedret, true), LOGGER_DATA);
            if (count($feedret) && ($feedret['feed_atom'] || $feedret['feed_rss'])) {
                $poll = x($feedret, 'feed_atom') ? unamp($feedret['feed_atom']) : unamp($feedret['feed_rss']);
                if (!x($vcard)) {
                    $vcard = array();
                }
            }
            if (x($feedret, 'photo') && !x($vcard, 'photo')) {
                $vcard['photo'] = $feedret['photo'];
            }
            require_once 'library/simplepie/simplepie.inc';
            $feed = new SimplePie();
            $xml = fetch_url($poll);
            logger('probe_url: fetch feed: ' . $poll . ' returns: ' . $xml, LOGGER_DATA);
            $a = get_app();
            logger('probe_url: scrape_feed: headers: ' . $a->get_curl_headers(), LOGGER_DATA);
            // Don't try and parse an empty string
            $feed->set_raw_data($xml ? $xml : '<?xml version="1.0" encoding="utf-8" ?><xml></xml>');
            $feed->init();
            if ($feed->error()) {
                logger('probe_url: scrape_feed: Error parsing XML: ' . $feed->error());
                $network = NETWORK_PHANTOM;
            }
            if (!x($vcard, 'photo')) {
                $vcard['photo'] = $feed->get_image_url();
            }
            $author = $feed->get_author();
            if ($author) {
                $vcard['fn'] = unxmlify(trim($author->get_name()));
                if (!$vcard['fn']) {
                    $vcard['fn'] = trim(unxmlify($author->get_email()));
                }
                if (strpos($vcard['fn'], '@') !== false) {
                    $vcard['fn'] = substr($vcard['fn'], 0, strpos($vcard['fn'], '@'));
                }
                $email = unxmlify($author->get_email());
                if (!$profile && $author->get_link()) {
                    $profile = trim(unxmlify($author->get_link()));
                }
                if (!$vcard['photo']) {
                    $rawtags = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
                    if ($rawtags) {
                        $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
                        if (x($elems, 'link') && $elems['link'][0]['attribs']['']['rel'] === 'photo') {
                            $vcard['photo'] = $elems['link'][0]['attribs']['']['href'];
                        }
                    }
                }
                // Fetch fullname via poco:displayName
                $pocotags = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
                if ($pocotags) {
                    $elems = $pocotags[0]['child']['http://portablecontacts.net/spec/1.0'];
                    if (isset($elems["displayName"])) {
                        $vcard['fn'] = $elems["displayName"][0]["data"];
                    }
                    if (isset($elems["preferredUsername"])) {
                        $vcard['nick'] = $elems["preferredUsername"][0]["data"];
                    }
                }
            } else {
                $item = $feed->get_item(0);
                if ($item) {
                    $author = $item->get_author();
                    if ($author) {
                        $vcard['fn'] = trim(unxmlify($author->get_name()));
                        if (!$vcard['fn']) {
                            $vcard['fn'] = trim(unxmlify($author->get_email()));
                        }
                        if (strpos($vcard['fn'], '@') !== false) {
                            $vcard['fn'] = substr($vcard['fn'], 0, strpos($vcard['fn'], '@'));
                        }
                        $email = unxmlify($author->get_email());
                        if (!$profile && $author->get_link()) {
                            $profile = trim(unxmlify($author->get_link()));
                        }
                    }
                    if (!$vcard['photo']) {
                        $rawmedia = $item->get_item_tags('http://search.yahoo.com/mrss/', 'thumbnail');
                        if ($rawmedia && $rawmedia[0]['attribs']['']['url']) {
                            $vcard['photo'] = unxmlify($rawmedia[0]['attribs']['']['url']);
                        }
                    }
                    if (!$vcard['photo']) {
                        $rawtags = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
                        if ($rawtags) {
                            $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
                            if (x($elems, 'link') && $elems['link'][0]['attribs']['']['rel'] === 'photo') {
                                $vcard['photo'] = $elems['link'][0]['attribs']['']['href'];
                            }
                        }
                    }
                }
            }
            // Workaround for misconfigured Friendica servers
            if ($network == "" and strstr($url, "/profile/")) {
                $noscrape = str_replace("/profile/", "/noscrape/", $url);
                $noscrapejson = fetch_url($noscrape);
                if ($noscrapejson) {
                    $network = NETWORK_DFRN;
                    $poco = str_replace("/profile/", "/poco/", $url);
                    $noscrapedata = json_decode($noscrapejson, true);
                    if (isset($noscrapedata["addr"])) {
                        $addr = $noscrapedata["addr"];
                    }
                    if (isset($noscrapedata["fn"])) {
                        $vcard["fn"] = $noscrapedata["fn"];
                    }
                    if (isset($noscrapedata["key"])) {
                        $pubkey = $noscrapedata["key"];
                    }
                    if (isset($noscrapedata["photo"])) {
                        $vcard["photo"] = $noscrapedata["photo"];
                    }
                    if (isset($noscrapedata["dfrn-request"])) {
                        $request = $noscrapedata["dfrn-request"];
                    }
                    if (isset($noscrapedata["dfrn-confirm"])) {
                        $confirm = $noscrapedata["dfrn-confirm"];
                    }
                    if (isset($noscrapedata["dfrn-notify"])) {
                        $notify = $noscrapedata["dfrn-notify"];
                    }
                    if (isset($noscrapedata["dfrn-poll"])) {
                        $poll = $noscrapedata["dfrn-poll"];
                    }
                }
            }
            if (!$vcard['photo'] && strlen($email)) {
                $vcard['photo'] = avatar_img($email);
            }
            if ($poll === $profile) {
                $lnk = $feed->get_permalink();
            }
            if (isset($lnk) && strlen($lnk)) {
                $profile = $lnk;
            }
            if (!$network) {
                $network = NETWORK_FEED;
                // If it is a feed, don't take the author name as feed name
                unset($vcard['fn']);
            }
            if (!x($vcard, 'fn')) {
                $vcard['fn'] = notags($feed->get_title());
            }
            if (!x($vcard, 'fn')) {
                $vcard['fn'] = notags($feed->get_description());
            }
            if (strpos($vcard['fn'], 'Twitter / ') !== false) {
                $vcard['fn'] = substr($vcard['fn'], strpos($vcard['fn'], '/') + 1);
                $vcard['fn'] = trim($vcard['fn']);
            }
            if (!x($vcard, 'nick')) {
                $vcard['nick'] = strtolower(notags(unxmlify($vcard['fn'])));
                if (strpos($vcard['nick'], ' ')) {
                    $vcard['nick'] = trim(substr($vcard['nick'], 0, strpos($vcard['nick'], ' ')));
                }
            }
            if (!$priority) {
                $priority = 2;
            }
        }
    }
    if (!x($vcard, 'photo')) {
        $a = get_app();
        $vcard['photo'] = $a->get_baseurl() . '/images/person-175.jpg';
    }
    if (!$profile) {
        $profile = $url;
    }
    // No human could be associated with this link, use the URL as the contact name
    if ($network === NETWORK_FEED && $poll && !x($vcard, 'fn')) {
        $vcard['fn'] = $url;
    }
    if ($notify != "" and $poll != "") {
        $baseurl = matching(normalise_link($notify), normalise_link($poll));
        $baseurl2 = matching($baseurl, normalise_link($profile));
        if ($baseurl2 != "") {
            $baseurl = $baseurl2;
        }
    }
    if ($baseurl == "" and $notify != "") {
        $baseurl = matching(normalise_link($profile), normalise_link($notify));
    }
    if ($baseurl == "" and $poll != "") {
        $baseurl = matching(normalise_link($profile), normalise_link($poll));
    }
    $baseurl = rtrim($baseurl, "/");
    if (strpos($url, '@') and $addr == "" and $network == NETWORK_DFRN) {
        $addr = str_replace('acct:', '', $url);
    }
    $vcard['fn'] = notags($vcard['fn']);
    $vcard['nick'] = str_replace(' ', '', notags($vcard['nick']));
    $result['name'] = $vcard['fn'];
    $result['nick'] = $vcard['nick'];
    $result['url'] = $profile;
    $result['addr'] = $addr;
    $result['batch'] = $batch;
    $result['notify'] = $notify;
    $result['poll'] = $poll;
    $result['request'] = $request;
    $result['confirm'] = $confirm;
    $result['poco'] = $poco;
    $result['photo'] = $vcard['photo'];
    $result['priority'] = $priority;
    $result['network'] = $network;
    $result['alias'] = $alias;
    $result['pubkey'] = $pubkey;
    $result['baseurl'] = $baseurl;
    logger('probe_url: ' . print_r($result, true), LOGGER_DEBUG);
    if ($level == 1) {
        // Trying if it maybe a diaspora account
        if ($result['network'] == NETWORK_FEED or $result['addr'] == "") {
            require_once 'include/bbcode.php';
            $address = GetProfileUsername($url, "", true);
            $result2 = probe_url($address, $mode, ++$level);
            if ($result2['network'] != "") {
                $result = $result2;
            }
        }
        // Maybe it's some non standard GNU Social installation (Single user, subfolder or no uri rewrite)
        if ($result['network'] == NETWORK_FEED and $result['baseurl'] != "" and $result['nick'] != "") {
            $addr = $result['nick'] . '@' . str_replace("http://", "", $result['baseurl']);
            $result2 = probe_url($addr, $mode, ++$level);
            if ($result2['network'] != "" and $result2['network'] != NETWORK_FEED) {
                $result = $result2;
            }
        }
    }
    // Only store into the cache if the value seems to be valid
    if ($result['network'] != NETWORK_PHANTOM) {
        Cache::set("probe_url:" . $mode . ":" . $url, serialize($result), CACHE_DAY);
    }
    return $result;
}
 public function create()
 {
     if (!$this->axipi_session->userdata('mbr_id')) {
         redirect(base_url() . '?u=' . $this->input->get('u'));
     }
     $data = array();
     $content = array();
     $this->load->library(array('form_validation', 'analyzer_library'));
     if ($this->config->item('folders')) {
         $query = $this->db->query('SELECT flr.* FROM ' . $this->db->dbprefix('folders') . ' AS flr WHERE flr.mbr_id = ? GROUP BY flr.flr_id ORDER BY flr.flr_title ASC', array($this->member->mbr_id));
         $data['folders'] = array();
         $data['folders'][0] = $this->lang->line('no_folder');
         if ($query->num_rows() > 0) {
             foreach ($query->result() as $flr) {
                 $data['folders'][$flr->flr_id] = $flr->flr_title;
             }
         }
     }
     $this->form_validation->set_rules('url', 'lang:url_feed', 'required');
     if ($this->config->item('folders')) {
         $this->form_validation->set_rules('folder', 'lang:folder', 'required');
     }
     $this->form_validation->set_rules('priority', 'lang:priority', 'numeric');
     //$this->form_validation->set_rules('direction', 'lang:direction', '');
     $data['error'] = false;
     $data['feeds'] = array();
     if ($this->input->post('url') && !$this->input->post('analyze_done')) {
         $this->analyzer_library->start($this->input->post('url'));
         $metas = $this->analyzer_library->metas;
         if (count($metas) > 0) {
             $data['feeds'][''] = '-';
             foreach ($metas as $meta) {
                 $add = true;
                 $headers = get_headers($meta['href'], 1);
                 if (isset($headers['Location']) == 1) {
                     $meta['href'] = $headers['Location'];
                     $headers = get_headers($meta['href'], 1);
                     if (isset($headers['Location']) == 1) {
                         $add = false;
                     }
                 }
                 if ($add) {
                     if ($meta['title'] == '') {
                         $data['feeds'][$meta['href']] = $meta['href'];
                     } else {
                         $this->analyzer_library->encoding($meta['title']);
                         $data['feeds'][$meta['href']] = $meta['title'];
                     }
                 }
             }
         }
     }
     if ($this->form_validation->run() == FALSE || count($data['feeds']) > 0) {
         $content = $this->load->view('subscriptions_create', $data, TRUE);
     } else {
         if ($this->config->item('folders')) {
             $folder = false;
             if ($this->input->post('folder')) {
                 $query = $this->db->query('SELECT flr.* FROM ' . $this->db->dbprefix('folders') . ' AS flr WHERE flr.mbr_id = ? AND flr.flr_id = ? GROUP BY flr.flr_id', array($this->member->mbr_id, $this->input->post('folder')));
                 if ($query->num_rows() > 0) {
                     $folder = $this->input->post('folder');
                 }
             }
         }
         $query = $this->db->query('SELECT fed.*, sub.sub_id FROM ' . $this->db->dbprefix('feeds') . ' AS fed LEFT JOIN ' . $this->db->dbprefix('subscriptions') . ' AS sub ON sub.fed_id = fed.fed_id AND sub.mbr_id = ? WHERE fed.fed_link = ? GROUP BY fed.fed_id', array($this->member->mbr_id, $this->input->post('url')));
         if ($query->num_rows() == 0) {
             $parse_url = parse_url($this->input->post('url'));
             if (isset($parse_url['host']) == 1 && $parse_url['host'] == 'instagram.com' && $this->config->item('instagram/enabled')) {
                 if ($this->config->item('instagram/access_token')) {
                     $parts = explode('/', rtrim($parse_url['path'], '/'));
                     $total_parts = count($parts);
                     $last_part = $parts[$total_parts - 1];
                     $result = json_decode(file_get_contents('https://api.instagram.com/v1/users/search?q=' . $last_part . '&count=15&access_token=' . $this->config->item('instagram/access_token')));
                     if (count($result->data) == 0) {
                         $data['error'] = 'User not found';
                     } else {
                         $user_id = false;
                         foreach ($result->data as $user) {
                             if ($user->username == $last_part) {
                                 $user_id = $user->id;
                                 break;
                             }
                         }
                         if (!$user_id) {
                             $data['error'] = 'User not found';
                         } else {
                             $result = json_decode(file_get_contents('https://api.instagram.com/v1/users/' . $user_id . '?access_token=' . $this->config->item('instagram/access_token')));
                             $this->db->set('fed_title', 'Instagram @' . $result->data->username);
                             $this->db->set('fed_url', $this->input->post('url'));
                             $this->db->set('fed_description', $result->data->bio);
                             $this->db->set('fed_image', $result->data->profile_picture);
                             $this->db->set('fed_link', $this->input->post('url'));
                             if (isset($parse_url['host']) == 1) {
                                 $this->db->set('fed_host', $parse_url['host']);
                             }
                             $this->db->set('fed_lastcrawl', date('Y-m-d H:i:s'));
                             $this->db->set('fed_datecreated', date('Y-m-d H:i:s'));
                             $this->db->insert('feeds');
                             $fed_id = $this->db->insert_id();
                             $this->db->set('mbr_id', $this->member->mbr_id);
                             $this->db->set('fed_id', $fed_id);
                             if ($this->config->item('folders')) {
                                 if ($folder) {
                                     $this->db->set('flr_id', $folder);
                                 }
                             }
                             $this->db->set('sub_priority', $this->input->post('priority'));
                             $this->db->set('sub_direction', $this->input->post('direction'));
                             $this->db->set('sub_datecreated', date('Y-m-d H:i:s'));
                             $this->db->insert('subscriptions');
                             $sub_id = $this->db->insert_id();
                             $result = json_decode(file_get_contents('https://api.instagram.com/v1/users/' . $user_id . '/media/recent?access_token=' . $this->config->item('instagram/access_token')));
                             $this->readerself_library->crawl_items_instagram($fed_id, $result->data);
                         }
                     }
                 }
             } else {
                 if (isset($parse_url['host']) == 1 && $parse_url['host'] == 'www.facebook.com' && $this->config->item('facebook/enabled')) {
                     include_once 'thirdparty/facebook/autoload.php';
                     $fb = new Facebook\Facebook(array('app_id' => $this->config->item('facebook/id'), 'app_secret' => $this->config->item('facebook/secret')));
                     $fbApp = $fb->getApp();
                     $accessToken = $fbApp->getAccessToken();
                     try {
                         $parts = explode('/', rtrim($parse_url['path'], '/'));
                         $total_parts = count($parts);
                         $last_part = $parts[$total_parts - 1];
                         $request = new Facebook\FacebookRequest($fbApp, $accessToken, 'GET', $last_part . '?fields=link,name,about');
                         $response = $fb->getClient()->sendRequest($request);
                         $result = $response->getDecodedBody();
                         $this->db->set('fed_title', $result['name']);
                         $this->db->set('fed_url', $result['link']);
                         $this->db->set('fed_description', $result['about']);
                         $this->db->set('fed_link', $result['link']);
                         if (isset($parse_url['host']) == 1) {
                             $this->db->set('fed_host', $parse_url['host']);
                         }
                         $this->db->set('fed_lastcrawl', date('Y-m-d H:i:s'));
                         $this->db->set('fed_datecreated', date('Y-m-d H:i:s'));
                         $this->db->insert('feeds');
                         $fed_id = $this->db->insert_id();
                         $this->db->set('mbr_id', $this->member->mbr_id);
                         $this->db->set('fed_id', $fed_id);
                         if ($this->config->item('folders')) {
                             if ($folder) {
                                 $this->db->set('flr_id', $folder);
                             }
                         }
                         $this->db->set('sub_priority', $this->input->post('priority'));
                         $this->db->set('sub_direction', $this->input->post('direction'));
                         $this->db->set('sub_datecreated', date('Y-m-d H:i:s'));
                         $this->db->insert('subscriptions');
                         $sub_id = $this->db->insert_id();
                         $request = new Facebook\FacebookRequest($fbApp, $accessToken, 'GET', $last_part . '?fields=feed{created_time,id,message,story,full_picture,place,type,status_type,link}');
                         $response = $fb->getClient()->sendRequest($request);
                         $posts = $response->getDecodedBody();
                         $this->readerself_library->crawl_items_facebook($fed_id, $posts['feed']['data']);
                         redirect(base_url() . 'subscriptions/read/' . $sub_id);
                     } catch (Facebook\Exceptions\FacebookResponseException $e) {
                         $data['error'] = 'Graph returned an error: ' . $e->getMessage();
                     } catch (Facebook\Exceptions\FacebookSDKException $e) {
                         $data['error'] = 'Facebook SDK returned an error: ' . $e->getMessage();
                     }
                 } else {
                     include_once 'thirdparty/simplepie/autoloader.php';
                     include_once 'thirdparty/simplepie/idn/idna_convert.class.php';
                     $sp_feed = new SimplePie();
                     $sp_feed->set_feed_url(convert_to_ascii($this->input->post('url')));
                     $sp_feed->enable_cache(false);
                     $sp_feed->set_timeout(60);
                     $sp_feed->force_feed(true);
                     $sp_feed->init();
                     $sp_feed->handle_content_type();
                     if ($sp_feed->error()) {
                         $data['error'] = $sp_feed->error();
                     } else {
                         $parse_url = parse_url($sp_feed->get_link());
                         $this->db->set('fed_title', $sp_feed->get_title());
                         $this->db->set('fed_url', $sp_feed->get_link());
                         $this->db->set('fed_description', $sp_feed->get_description());
                         $this->db->set('fed_link', $sp_feed->subscribe_url());
                         if (isset($parse_url['host']) == 1) {
                             $this->db->set('fed_host', $parse_url['host']);
                         }
                         $this->db->set('fed_lastcrawl', date('Y-m-d H:i:s'));
                         $this->db->set('fed_datecreated', date('Y-m-d H:i:s'));
                         $this->db->insert('feeds');
                         $fed_id = $this->db->insert_id();
                         $this->db->set('mbr_id', $this->member->mbr_id);
                         $this->db->set('fed_id', $fed_id);
                         if ($this->config->item('folders')) {
                             if ($folder) {
                                 $this->db->set('flr_id', $folder);
                             }
                         }
                         $this->db->set('sub_priority', $this->input->post('priority'));
                         $this->db->set('sub_direction', $this->input->post('direction'));
                         $this->db->set('sub_datecreated', date('Y-m-d H:i:s'));
                         $this->db->insert('subscriptions');
                         $sub_id = $this->db->insert_id();
                         $data['sub_id'] = $sub_id;
                         $data['fed_title'] = $sp_feed->get_title();
                         $this->readerself_library->crawl_items($fed_id, $sp_feed->get_items());
                     }
                     $sp_feed->__destruct();
                     unset($sp_feed);
                 }
             }
         } else {
             $fed = $query->row();
             if (!$fed->sub_id) {
                 $this->db->set('mbr_id', $this->member->mbr_id);
                 $this->db->set('fed_id', $fed->fed_id);
                 if ($this->config->item('folders')) {
                     if ($folder) {
                         $this->db->set('flr_id', $folder);
                     }
                 }
                 $this->db->set('sub_priority', $this->input->post('priority'));
                 $this->db->set('sub_direction', $this->input->post('direction'));
                 $this->db->set('sub_datecreated', date('Y-m-d H:i:s'));
                 $this->db->insert('subscriptions');
                 $sub_id = $this->db->insert_id();
             } else {
                 $sub_id = $fed->sub_id;
             }
             $data['sub_id'] = $sub_id;
             $data['fed_title'] = $fed->fed_title;
         }
         if ($data['error']) {
             $content = $this->load->view('subscriptions_create', $data, TRUE);
         } else {
             redirect(base_url() . 'subscriptions/read/' . $sub_id);
         }
     }
     $this->readerself_library->set_content($content);
 }
Exemple #9
0
 public function items()
 {
     if ($this->input->is_ajax_request()) {
         $this->readerself_library->set_template('_json');
         $this->readerself_library->set_content_type('application/json');
         $content = array();
     } else {
         $this->readerself_library->set_template('_plain');
         $this->readerself_library->set_content_type('text/plain');
         $content = '';
     }
     if ($this->input->is_cli_request() && !$this->config->item('refresh_by_cron')) {
         $content .= 'Refresh by cron disabled' . "\n";
     } else {
         include_once 'thirdparty/simplepie/autoloader.php';
         include_once 'thirdparty/simplepie/idn/idna_convert.class.php';
         if ($this->config->item('facebook/enabled')) {
             include_once 'thirdparty/facebook/autoload.php';
             $fb = new Facebook\Facebook(array('app_id' => $this->config->item('facebook/id'), 'app_secret' => $this->config->item('facebook/secret')));
             $fbApp = $fb->getApp();
             $accessToken = $fbApp->getAccessToken();
         }
         $query = $this->db->query('SELECT fed.* FROM ' . $this->db->dbprefix('feeds') . ' AS fed WHERE fed.fed_nextcrawl IS NULL OR fed.fed_nextcrawl <= ? GROUP BY fed.fed_id HAVING (SELECT COUNT(DISTINCT(sub.mbr_id)) FROM ' . $this->db->dbprefix('subscriptions') . ' AS sub WHERE sub.fed_id = fed.fed_id) > 0', array(date('Y-m-d H:i:s')));
         if ($query->num_rows() > 0) {
             $microtime_start = microtime(1);
             $errors = 0;
             foreach ($query->result() as $fed) {
                 $parse_url = parse_url($fed->fed_link);
                 if (isset($parse_url['host']) == 1 && $parse_url['host'] == 'www.facebook.com' && $this->config->item('facebook/enabled')) {
                     try {
                         $parts = explode('/', $parse_url['path']);
                         $total_parts = count($parts);
                         $last_part = $parts[$total_parts - 1];
                         $request = new Facebook\FacebookRequest($fbApp, $accessToken, 'GET', $last_part . '?fields=link,name,about');
                         $response = $fb->getClient()->sendRequest($request);
                         $result = $response->getDecodedBody();
                         $request = new Facebook\FacebookRequest($fbApp, $accessToken, 'GET', $last_part . '?fields=feed{created_time,id,message,story,full_picture,place,type,status_type,link}');
                         $response = $fb->getClient()->sendRequest($request);
                         $posts = $response->getDecodedBody();
                         $this->readerself_library->crawl_items_facebook($fed->fed_id, $posts['feed']['data']);
                         $lastitem = $this->db->query('SELECT itm.itm_datecreated FROM ' . $this->db->dbprefix('items') . ' AS itm WHERE itm.fed_id = ? GROUP BY itm.itm_id ORDER BY itm.itm_id DESC LIMIT 0,1', array($fed->fed_id))->row();
                         $this->db->set('fed_title', $result['name']);
                         $this->db->set('fed_url', $result['link']);
                         $this->db->set('fed_link', $result['link']);
                         if (isset($parse_url['host']) == 1) {
                             $this->db->set('fed_host', $parse_url['host']);
                         }
                         $this->db->set('fed_description', $result['about']);
                         $this->db->set('fed_lasterror', '');
                         $this->db->set('fed_lastcrawl', date('Y-m-d H:i:s'));
                         if ($lastitem) {
                             $nextcrawl = '';
                             //older than 96 hours, next crawl in 12 hours
                             if ($lastitem->itm_datecreated < date('Y-m-d H:i:s', time() - 3600 * 24 * 96)) {
                                 $nextcrawl = date('Y-m-d H:i:s', time() + 3600 * 12);
                                 //older than 48 hours, next crawl in 6 hours
                             } else {
                                 if ($lastitem->itm_datecreated < date('Y-m-d H:i:s', time() - 3600 * 48)) {
                                     $nextcrawl = date('Y-m-d H:i:s', time() + 3600 * 6);
                                     //older than 24 hours, next crawl in 3 hours
                                 } else {
                                     if ($lastitem->itm_datecreated < date('Y-m-d H:i:s', time() - 3600 * 24)) {
                                         $nextcrawl = date('Y-m-d H:i:s', time() + 3600 * 3);
                                     }
                                 }
                             }
                             $this->db->set('fed_nextcrawl', $nextcrawl);
                         }
                         $this->db->where('fed_id', $fed->fed_id);
                         $this->db->update('feeds');
                     } catch (Facebook\Exceptions\FacebookResponseException $e) {
                         $errors++;
                         $this->db->set('fed_lasterror', 'Graph returned an error: ' . $e->getMessage());
                         $this->db->set('fed_lastcrawl', date('Y-m-d H:i:s'));
                         $this->db->where('fed_id', $fed->fed_id);
                         $this->db->update('feeds');
                     } catch (Facebook\Exceptions\FacebookSDKException $e) {
                         $errors++;
                         $this->db->set('fed_lasterror', 'Facebook SDK returned an error: ' . $e->getMessage());
                         $this->db->set('fed_lastcrawl', date('Y-m-d H:i:s'));
                         $this->db->where('fed_id', $fed->fed_id);
                         $this->db->update('feeds');
                     }
                 } else {
                     $sp_feed = new SimplePie();
                     $sp_feed->set_feed_url(convert_to_ascii($fed->fed_link));
                     $sp_feed->enable_cache(false);
                     $sp_feed->set_timeout(5);
                     $sp_feed->force_feed(true);
                     $sp_feed->init();
                     $sp_feed->handle_content_type();
                     if ($sp_feed->error()) {
                         $errors++;
                         $this->db->set('fed_lasterror', $sp_feed->error());
                         $this->db->set('fed_lastcrawl', date('Y-m-d H:i:s'));
                         $this->db->where('fed_id', $fed->fed_id);
                         $this->db->update('feeds');
                     } else {
                         $this->readerself_library->crawl_items($fed->fed_id, $sp_feed->get_items());
                         $lastitem = $this->db->query('SELECT itm.itm_datecreated FROM ' . $this->db->dbprefix('items') . ' AS itm WHERE itm.fed_id = ? GROUP BY itm.itm_id ORDER BY itm.itm_id DESC LIMIT 0,1', array($fed->fed_id))->row();
                         $parse_url = parse_url($sp_feed->get_link());
                         $this->db->set('fed_title', $sp_feed->get_title());
                         $this->db->set('fed_url', $sp_feed->get_link());
                         $this->db->set('fed_link', $sp_feed->subscribe_url());
                         if (isset($parse_url['host']) == 1) {
                             $this->db->set('fed_host', $parse_url['host']);
                         }
                         if ($sp_feed->get_type() & SIMPLEPIE_TYPE_RSS_ALL) {
                             $this->db->set('fed_type', 'rss');
                         } else {
                             if ($sp_feed->get_type() & SIMPLEPIE_TYPE_ATOM_ALL) {
                                 $this->db->set('fed_type', 'atom');
                             }
                         }
                         if ($sp_feed->get_image_url()) {
                             $this->db->set('fed_image', $sp_feed->get_image_url());
                         }
                         $this->db->set('fed_description', $sp_feed->get_description());
                         $this->db->set('fed_lasterror', '');
                         $this->db->set('fed_lastcrawl', date('Y-m-d H:i:s'));
                         if ($lastitem) {
                             $nextcrawl = '';
                             //older than 96 hours, next crawl in 12 hours
                             if ($lastitem->itm_datecreated < date('Y-m-d H:i:s', time() - 3600 * 24 * 96)) {
                                 $nextcrawl = date('Y-m-d H:i:s', time() + 3600 * 12);
                                 //older than 48 hours, next crawl in 6 hours
                             } else {
                                 if ($lastitem->itm_datecreated < date('Y-m-d H:i:s', time() - 3600 * 48)) {
                                     $nextcrawl = date('Y-m-d H:i:s', time() + 3600 * 6);
                                     //older than 24 hours, next crawl in 3 hours
                                 } else {
                                     if ($lastitem->itm_datecreated < date('Y-m-d H:i:s', time() - 3600 * 24)) {
                                         $nextcrawl = date('Y-m-d H:i:s', time() + 3600 * 3);
                                     }
                                 }
                             }
                             $this->db->set('fed_nextcrawl', $nextcrawl);
                         }
                         $this->db->where('fed_id', $fed->fed_id);
                         $this->db->update('feeds');
                     }
                     $sp_feed->__destruct();
                     unset($sp_feed);
                 }
             }
             $this->db->set('crr_time', microtime(1) - $microtime_start);
             if (function_exists('memory_get_peak_usage')) {
                 $this->db->set('crr_memory', memory_get_peak_usage());
             }
             $this->db->set('crr_feeds', $query->num_rows());
             if ($errors > 0) {
                 $this->db->set('crr_errors', $errors);
             }
             $this->db->set('crr_datecreated', date('Y-m-d H:i:s'));
             $this->db->insert('crawler');
             if ($this->db->dbdriver == 'mysqli') {
                 $this->db->query('OPTIMIZE TABLE categories, connections, enclosures, favorites, feeds, folders, history, items, members, share, subscriptions');
             }
         }
     }
     $this->readerself_library->set_content($content);
 }
function feedzy_rss($atts, $content = '')
{
    global $feedzyStyle;
    $feedzyStyle = true;
    $count = 0;
    //Load SimplePie if not already
    if (!class_exists('SimplePie')) {
        require_once ABSPATH . WPINC . '/class-feed.php';
    }
    //Retrieve & extract shorcode parameters
    extract(shortcode_atts(array("feeds" => '', "max" => '5', "feed_title" => 'yes', "target" => '_blank', "title" => '', "meta" => 'yes', "summary" => 'yes', "summarylength" => '', "thumb" => 'yes', "default" => '', "size" => '', "keywords_title" => ''), $atts, 'feedzy_default'));
    //Use "shortcode_atts_feedzy_default" filter to edit shortcode parameters default values or add your owns.
    if (!empty($feeds)) {
        $feeds = rtrim($feeds, ',');
        $feeds = explode(',', $feeds);
        //Remove SSL from HTTP request to prevent fetching errors
        foreach ($feeds as $feed) {
            $feedURL[] = preg_replace("/^https:/i", "http:", $feed);
        }
        if (count($feedURL) === 1) {
            $feedURL = $feedURL[0];
        }
    }
    if ($max == '0') {
        $max = '999';
    } else {
        if (empty($max) || !ctype_digit($max)) {
            $max = '5';
        }
    }
    if (empty($size) || !ctype_digit($size)) {
        $size = '150';
    }
    $sizes = array('width' => $size, 'height' => $size);
    $sizes = apply_filters('feedzy_thumb_sizes', $sizes, $feedURL);
    if (!empty($title) && !ctype_digit($title)) {
        $title = '';
    }
    if (!empty($keywords_title)) {
        $keywords_title = rtrim($keywords_title, ',');
        $keywords_title = array_map('trim', explode(',', $keywords_title));
    }
    if (!empty($summarylength) && !ctype_digit($summarylength)) {
        $summarylength = '';
    }
    if (!empty($default)) {
        $default = $default;
    } else {
        $default = apply_filters('feedzy_default_image', $default, $feedURL);
    }
    //Load SimplePie Instance
    $feed = new SimplePie();
    $feed->set_feed_url($feedURL);
    $feed->enable_cache(true);
    $feed->enable_order_by_date(true);
    $feed->set_cache_class('WP_Feed_Cache');
    $feed->set_file_class('WP_SimplePie_File');
    $feed->set_cache_duration(apply_filters('wp_feed_cache_transient_lifetime', 7200, $feedURL));
    do_action_ref_array('wp_feed_options', array($feed, $feedURL));
    $feed->strip_comments(true);
    $feed->strip_htmltags(array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'));
    $feed->init();
    $feed->handle_content_type();
    // Display the error message
    if ($feed->error()) {
        $content .= apply_filters('feedzy_default_error', $feed->error(), $feedURL);
    }
    $content .= '<div class="feedzy-rss">';
    if ($feed_title == 'yes') {
        $content .= '<div class="rss_header">';
        $content .= '<h2><a href="' . $feed->get_permalink() . '" class="rss_title">' . html_entity_decode($feed->get_title()) . '</a> <span class="rss_description"> ' . $feed->get_description() . '</span></h2>';
        $content .= '</div>';
    }
    $content .= '<ul>';
    //Loop through RSS feed
    $items = apply_filters('feedzy_feed_items', $feed->get_items(), $feedURL);
    foreach ((array) $items as $item) {
        $continue = apply_filters('feedzy_item_keyword', true, $keywords_title, $item, $feedURL);
        if ($continue == true) {
            //Count items
            if ($count >= $max) {
                break;
            }
            $count++;
            //Fetch image thumbnail
            if ($thumb == 'yes' || $thumb == 'auto') {
                $thethumbnail = feedzy_retrieve_image($item);
            }
            $itemAttr = apply_filters('feedzy_item_attributes', $itemAttr = '', $sizes, $item, $feedURL);
            //Build element DOM
            $content .= '<li ' . $itemAttr . '>';
            if ($thumb == 'yes' || $thumb == 'auto') {
                $contentThumb = '';
                if (!empty($thethumbnail) && $thumb == 'auto' || $thumb == 'yes') {
                    $contentThumb .= '<div class="rss_image" style="width:' . $sizes['width'] . 'px; height:' . $sizes['height'] . 'px;">';
                    $contentThumb .= '<a href="' . $item->get_permalink() . '" target="' . $target . '" title="' . $item->get_title() . '" >';
                    if (!empty($thethumbnail)) {
                        $thethumbnail = feedzy_image_encode($thethumbnail);
                        $contentThumb .= '<span class="default" style="width:' . $sizes['width'] . 'px; height:' . $sizes['height'] . 'px; background-image:  url(' . $default . ');" alt="' . $item->get_title() . '"></span>';
                        $contentThumb .= '<span class="fetched" style="width:' . $sizes['width'] . 'px; height:' . $sizes['height'] . 'px; background-image:  url(' . $thethumbnail . ');" alt="' . $item->get_title() . '"></span>';
                    } else {
                        if (empty($thethumbnail) && $thumb == 'yes') {
                            $contentThumb .= '<span style="width:' . $sizes['width'] . 'px; height:' . $sizes['height'] . 'px; background-image:url(' . $default . ');" alt="' . $item->get_title() . '"></span>';
                        }
                    }
                    $contentThumb .= '</a>';
                    $contentThumb .= '</div>';
                }
                //Filter: feedzy_thumb_output
                $content .= apply_filters('feedzy_thumb_output', $contentThumb, $feedURL);
            }
            $contentTitle = '';
            $contentTitle .= '<span class="title"><a href="' . $item->get_permalink() . '" target="' . $target . '">';
            if (is_numeric($title) && strlen($item->get_title()) > $title) {
                $contentTitle .= preg_replace('/\\s+?(\\S+)?$/', '', substr($item->get_title(), 0, $title)) . '...';
            } else {
                $contentTitle .= $item->get_title();
            }
            $contentTitle .= '</a></span>';
            //Filter: feedzy_title_output
            $content .= apply_filters('feedzy_title_output', $contentTitle, $feedURL);
            $content .= '<div class="rss_content">';
            //Define Meta args
            $metaArgs = array('author' => true, 'date' => true, 'date_format' => get_option('date_format'), 'time_format' => get_option('time_format'));
            //Filter: feedzy_meta_args
            $metaArgs = apply_filters('feedzy_meta_args', $metaArgs, $feedURL);
            if ($meta == 'yes' && ($metaArgs['author'] || $metaArgs['date'])) {
                $contentMeta = '';
                $contentMeta .= '<small>' . __('Posted', 'feedzy_rss_translate') . ' ';
                if ($item->get_author() && $metaArgs['author']) {
                    $author = $item->get_author();
                    if (!($authorName = $author->get_name())) {
                        $authorName = $author->get_email();
                    }
                    if ($authorName) {
                        $domain = parse_url($item->get_permalink());
                        $contentMeta .= __('by', 'feedzy_rss_translate') . ' <a href="http://' . $domain['host'] . '" target="' . $target . '" title="' . $domain['host'] . '" >' . $authorName . '</a> ';
                    }
                }
                if ($metaArgs['date']) {
                    $contentMeta .= __('on', 'feedzy_rss_translate') . ' ' . date_i18n($metaArgs['date_format'], $item->get_date('U'));
                    $contentMeta .= ' ';
                    $contentMeta .= __('at', 'feedzy_rss_translate') . ' ' . date_i18n($metaArgs['time_format'], $item->get_date('U'));
                }
                $contentMeta .= '</small>';
                //Filter: feedzy_meta_output
                $content .= apply_filters('feedzy_meta_output', $contentMeta, $feedURL);
            }
            if ($summary == 'yes') {
                $contentSummary = '';
                $contentSummary .= '<p>';
                //Filter: feedzy_summary_input
                $description = $item->get_description();
                $description = apply_filters('feedzy_summary_input', $description, $item->get_content(), $feedURL);
                if (is_numeric($summarylength) && strlen($description) > $summarylength) {
                    $contentSummary .= preg_replace('/\\s+?(\\S+)?$/', '', substr($description, 0, $summarylength)) . ' […]';
                } else {
                    $contentSummary .= $description . ' […]';
                }
                $contentSummary .= '</p>';
                //Filter: feedzy_summary_output
                $content .= apply_filters('feedzy_summary_output', $contentSummary, $item->get_permalink(), $feedURL);
            }
            $content .= '</div>';
            $content .= '</li>';
        }
        //endContinue
    }
    //endforeach
    $content .= '</ul>';
    $content .= '</div>';
    return apply_filters('feedzy_global_output', $content, $feedURL);
}
Exemple #11
0
<input name="url" type="text" value="<?php 
echo $_POST['url'];
?>
" style="width:400px;"><input name="Submit" type="submit" value="Get Feed">
</form>
<?php 
if (isset($_POST['url']) && $_POST['url'] != "") {
    $url = $_POST['url'];
    include_once 'Simple/autoloader.php';
    $feed = new SimplePie();
    $feed->set_feed_url($url);
    $feed->enable_cache(false);
    $feed->set_output_encoding('Windows-1252');
    $feed->init();
    echo "<span><h1>" . $feed->get_title() . "</h1>";
    echo "<b>" . $feed->get_description() . "</b></span><hr />";
    $itemCount = $feed->get_item_quantity();
    $items = $feed->get_items();
    foreach ($items as $item) {
        ?>
<div><a href="<?php 
        echo $item->get_permalink();
        ?>
"><?php 
        echo $item->get_title();
        ?>
</a><br />
<em style="font-size:.7em;color:#666666"><?php 
        echo $item->get_date();
        ?>
</em>
Exemple #12
0
 /**
  *
  * Get posts from feeds:
  * @param array $feeds Array with the feeds.
  * @return array Array with the posts.
  */
 public function getPosts($feeds)
 {
     $posts = array();
     foreach ($feeds as $name => $feed) {
         Debug::info("Getting posts from " . $feed['url']);
         $rss = new SimplePie($feed['url']);
         $rss->handle_content_type();
         $rss->force_feed(true);
         $counter = 1;
         foreach ($rss->get_items() as $item) {
             Debug::info("  post {$counter} of " . MAXPOSTS . ".");
             if (!is_object($item)) {
                 Debug::error("Parsing item (" . $item . ").");
             } else {
                 if (strstr($item->get_title(), "[minipost]")) {
                     Debug::say("Minipost...passing.");
                 } else {
                     $counter++;
                     $timestamp = strtotime($item->get_date());
                     # Post:
                     $posts[$timestamp]['id'] = "p" . $timestamp . "-" . $counter;
                     $posts[$timestamp]['pubdate'] = $item->get_date('r');
                     $posts[$timestamp]['date'] = $item->get_local_date();
                     $posts[$timestamp]['time'] = $item->get_local_date("%T");
                     $posts[$timestamp]['permalink'] = $item->get_permalink();
                     $posts[$timestamp]['title'] = $item->get_title();
                     $posts[$timestamp]['description'] = $item->get_description();
                     $posts[$timestamp]['content'] = $item->get_content();
                     if ($posts[$timestamp]['description'] == $posts[$timestamp]['content'] and strlen($posts[$timestamp]['content']) < 400) {
                         $posts[$timestamp]['description'] = Html::Cut(Html::BurnerClean($item->get_description()));
                         $posts[$timestamp]['content'] = "";
                         $posts[$timestamp]['toggle'] = "";
                     } else {
                         $posts[$timestamp]['description'] = Html::Cut(Html::BurnerClean($item->get_description()));
                         $posts[$timestamp]['content'] = Html::Clean($item->get_content());
                         $posts[$timestamp]['toggle'] = "<a onclick='ToggleContent(\"" . $posts[$timestamp]['id'] . "\"); return false;' href=\"#\">&dArr; Read more</a>";
                     }
                     // Microblogging posts have same description as title
                     if (FALSE !== strpos($posts[$timestamp]['title'], $posts[$timestamp]['description'])) {
                         $posts[$timestamp]['description'] = "";
                         $posts[$timestamp]['content'] = "";
                         $posts[$timestamp]['toggle'] = "";
                     }
                     # Rss:
                     $posts[$timestamp]['description_rss'] = $posts[$timestamp]['description'];
                     $posts[$timestamp]['content_rss'] = $posts[$timestamp]['content'];
                     # author:
                     if (method_exists($item, 'get_author') and is_object($item->get_author())) {
                         # The feed ones:
                         $posts[$timestamp]['author'] = $item->get_author()->get_name();
                         $posts[$timestamp]['author_link'] = $item->get_author()->get_link();
                     } else {
                         Debug::say("No author data feed " . $name);
                         $posts[$timestamp]['author'] = $name;
                         $posts[$timestamp]['author_link'] = $rss->get_permalink();
                     }
                     # Si han quedado vacíos pese a todo:
                     if (empty($posts[$timestamp]['author'])) {
                         $posts[$timestamp]['author'] = $name;
                     }
                     if (empty($posts[$timestamp]['author_link'])) {
                         $posts[$timestamp]['author_link'] = $feed['url'];
                     }
                     $posts[$timestamp]['author_email'] = $feed['email'];
                     # Gravatar:
                     if (strlen($feed['avatar'])) {
                         $posts[$timestamp]['author_avatar'] = "http://www.gravatar.com/avatar.php?gravatar_id=" . md5($feed['avatar']) . "&amp;size=40&amp;default=" . urlencode(DEFAULT_AVATAR);
                     } else {
                         if (strlen($feed['avatar_url'])) {
                             $posts[$timestamp]['author_avatar'] = $feed['avatar_url'];
                         }
                     }
                     # Blog:
                     $posts[$timestamp]['blog_title'] = $rss->get_title();
                     $posts[$timestamp]['blog_url'] = $rss->get_permalink();
                     $posts[$timestamp]['blog_desc'] = $rss->get_description();
                     # Logo:
                     $posts[$timestamp]['logo_url'] = $rss->get_image_url();
                     $posts[$timestamp]['logo_link'] = $rss->get_image_link();
                     $posts[$timestamp]['logo_title'] = $rss->get_image_title();
                 }
             }
             if ($counter > MAXPOSTS) {
                 break;
             }
         }
     }
     krsort($posts);
     #Debug::dump($posts);
     return $posts;
 }
Exemple #13
0
 public function parse_single_feed($flux)
 {
     $feed = new SimplePie();
     $feed->set_feed_url($_POST['url']);
     $feed->init();
     if (!$feed->error()) {
         $feed->enable_cache(false);
         $feed->handle_content_type();
         $feed_title = strip_tags($feed->get_title());
         if (strlen($feed_title) > 50) {
             $feed_title = substr($feed_title, 0, 47) . '...';
         }
         $exist = $this->getConnectionWrapper()->addFlux($_POST['url'], $feed_title, $feed->get_description());
         $idFlux = $this->getConnectionWrapper()->getFluxId($feed_title);
         $this->NON_CLASSE = $this->getConnectionWrapper()->getFolderId($this->session_get("user_id", null), 'Non classé');
         $this->getConnectionWrapper()->addAbonnement($this->session_get("user_id", null), $this->NON_CLASSE, $idFlux);
         if (!$exist) {
             foreach ($feed->get_items() as $item) {
                 $item_title = strip_tags($item->get_title());
                 if (strlen($item_title) > 50) {
                     $item_title = substr($item_title, 0, 47) . '...';
                 }
                 $item_desc = $item->get_description();
                 if (strlen($item_desc) == 0) {
                     $item_desc = 'Aucune description disponible: ' . $item->get_permalink();
                 }
                 $item_content = $item->get_content();
                 if (strlen($item_content) == 0) {
                     $item_content = 'Aucun contenu supplémentaire disponible: ' . $item->get_permalink();
                 }
                 $this->getConnectionWrapper()->addArticle($idFlux, $item_title, $item->get_permalink(), $item_desc, $item_content, $item->get_date('Y-m-j G:i:s'));
             }
         }
     }
     $this->redirect_to('listing');
 }
Exemple #14
0
function discover_by_url($url, $arr = null)
{
    require_once 'library/HTML5/Parser.php';
    $x = scrape_feed($url);
    if (!$x) {
        if (!$arr) {
            return false;
        }
        $network = $arr['network'] ? $arr['network'] : 'unknown';
        $name = $arr['name'] ? $arr['name'] : 'unknown';
        $photo = $arr['photo'] ? $arr['photo'] : '';
        $addr = $arr['addr'] ? $arr['addr'] : '';
        $guid = $url;
    }
    $profile = $url;
    logger('scrape_feed results: ' . print_r($x, true));
    if ($x['feed_atom']) {
        $guid = $x['feed_atom'];
    }
    if ($x['feed_rss']) {
        $guid = $x['feed_rss'];
    }
    if (!$guid) {
        return false;
    }
    // try and discover stuff from the feeed
    require_once 'library/simplepie/simplepie.inc';
    $feed = new SimplePie();
    $level = 0;
    $x = z_fetch_url($guid, false, $level, array('novalidate' => true));
    if (!$x['success']) {
        logger('probe_url: feed fetch failed for ' . $poll);
        return false;
    }
    $xml = $x['body'];
    logger('probe_url: fetch feed: ' . $guid . ' returns: ' . $xml, LOGGER_DATA);
    logger('probe_url: scrape_feed: headers: ' . $x['header'], LOGGER_DATA);
    // Don't try and parse an empty string
    $feed->set_raw_data($xml ? $xml : '<?xml version="1.0" encoding="utf-8" ?><xml></xml>');
    $feed->init();
    if ($feed->error()) {
        logger('probe_url: scrape_feed: Error parsing XML: ' . $feed->error());
    }
    $name = unxmlify(trim($feed->get_title()));
    $photo = $feed->get_image_url();
    $author = $feed->get_author();
    if ($author) {
        if (!$name) {
            $name = unxmlify(trim($author->get_name()));
        }
        if (!$name) {
            $name = trim(unxmlify($author->get_email()));
            if (strpos($name, '@') !== false) {
                $name = substr($name, 0, strpos($name, '@'));
            }
        }
        if (!$profile && $author->get_link()) {
            $profile = trim(unxmlify($author->get_link()));
        }
        if (!$photo) {
            $rawtags = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
            if ($rawtags) {
                $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
                if (x($elems, 'link') && $elems['link'][0]['attribs']['']['rel'] === 'photo') {
                    $photo = $elems['link'][0]['attribs']['']['href'];
                }
            }
        }
    } else {
        $item = $feed->get_item(0);
        if ($item) {
            $author = $item->get_author();
            if ($author) {
                if (!$name) {
                    $name = trim(unxmlify($author->get_name()));
                    if (!$name) {
                        $name = trim(unxmlify($author->get_email()));
                    }
                    if (strpos($name, '@') !== false) {
                        $name = substr($name, 0, strpos($name, '@'));
                    }
                }
                if (!$profile && $author->get_link()) {
                    $profile = trim(unxmlify($author->get_link()));
                }
            }
            if (!$photo) {
                $rawmedia = $item->get_item_tags('http://search.yahoo.com/mrss/', 'thumbnail');
                if ($rawmedia && $rawmedia[0]['attribs']['']['url']) {
                    $photo = unxmlify($rawmedia[0]['attribs']['']['url']);
                }
            }
            if (!$photo) {
                $rawtags = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
                if ($rawtags) {
                    $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
                    if (x($elems, 'link') && $elems['link'][0]['attribs']['']['rel'] === 'photo') {
                        $photo = $elems['link'][0]['attribs']['']['href'];
                    }
                }
            }
        }
    }
    if ($poll === $profile) {
        $lnk = $feed->get_permalink();
    }
    if (isset($lnk) && strlen($lnk)) {
        $profile = $lnk;
    }
    if (!$network) {
        $network = 'rss';
    }
    if (!$name) {
        $name = notags($feed->get_description());
    }
    if (!$guid) {
        return false;
    }
    $r = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($guid));
    if ($r) {
        return true;
    }
    if (!$photo) {
        $photo = z_root() . '/images/rss_icon.png';
    }
    $r = q("insert into xchan ( xchan_hash, xchan_guid, xchan_pubkey, xchan_addr, xchan_url, xchan_name, xchan_network, xchan_instance_url, xchan_name_date ) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') ", dbesc($guid), dbesc($guid), dbesc($pubkey), dbesc($addr), dbesc($profile), dbesc($name), dbesc($network), dbesc(z_root()), dbesc(datetime_convert()));
    $photos = import_xchan_photo($photo, $guid);
    $r = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_hash = '%s'", dbesc(datetime_convert()), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), dbesc($photos[3]), dbesc($guid));
    return true;
}
Exemple #15
0
<?php 
require_once('simplepie.inc');
$feed = new SimplePie();

$path = 'file';
$path = $path.'.xml';
$filename = $path.'.js';
$feed->set_feed_url($path);
$feed->init();
$feed->handle_content_type();
echo "Wrote:<br />";
$return = 'var data = {' . "\n";
$return .= '"info" : [{' . "\n";
$return .= '"title": "'.$feed->get_title().'",' . "\n";
$return .= '"description": "'.$feed->get_description().'"' . "\n";
$return .= '}],' . "\n";
$amount = $feed->get_item_quantity();
$return .= '"playlist" : [' . "\n";
foreach ($feed->get_items() as $item) {
	$return .= '{' . "\n";
	$return .= '"title": "'.$item->get_title().'",' . "\n";
	$return .= '"description": "'.$item->get_description().'",' . "\n";
	$return .= '"href": "'.$item->get_permalink().'",' . "\n";
	if ($enclosure = $item->get_enclosure()) {
		$return .= '"url": "'.$enclosure->get_link().'",' . "\n";
		$return .= '"thumbnail": "'.str_replace('.png', '_thumbnail.png', $enclosure->get_thumbnail()).'",' . "\n";
		$return .= '"time": "'.$enclosure->get_duration(true).'"' . "\n";
	}
	$return .= '}, ';
}
$return = rtrim($return, ", ");
Exemple #16
0
					<!-- If the feed has a link back to the site that publishes it (which 99% of them do), link the feed's title to it. -->
					<h3 class="header"><?php 
    if ($feed->get_link()) {
        echo '<a href="' . $feed->get_link() . '">';
    }
    echo $feed->get_title();
    if ($feed->get_link()) {
        echo '</a>';
    }
    ?>
</h3>

					<!-- If the feed has a description, display it. -->
					<?php 
    echo $feed->get_description();
    ?>

				</div>

				<!-- Let's begin looping through each individual news item in the feed. -->
				<?php 
    foreach ($feed->get_items() as $item) {
        ?>
					<div class="chunk">

						<!-- If the item has a permalink back to the original post (which 99% of them do), link the item's title to it. -->
						<h4><?php 
        if ($item->get_permalink()) {
            echo '<a href="' . $item->get_permalink() . '">';
        }
function fof_update_feed($url)
{
    global $FOF_FEED_TABLE;
    #
    # Get feed data.
    #
    if (!$url) {
        return 0;
    }
    if (!empty($url)) {
        $piefeed = new SimplePie();
        $piefeed->set_feed_url($url);
    } else {
        return 0;
    }
    $piefeed->set_cache_location(FOF_CACHE_DIR);
    //   	echo "Memory usage after set cache: " . number_format(memory_get_usage());
    $piefeed->init();
    //echo "Memory usage after set init: " . number_format(memory_get_usage());
    $piefeed->handle_content_type();
    //echo "Memory usage after contenttype: " . number_format(memory_get_usage());
    if (!$piefeed->data) {
        //print "<font color=\"red\">" . _("error was") . "</font>: <B>" . $piefeed->error . "</b> ";
        //print "<a href=\"http://feedvalidator.org/check?url=$url\">" . _("try to validate it?") . "</a> ";
        //unset($piefeed);
        $piefeed->__destruct();
        // Do what PHP should be doing on it's own.
        return 0;
    }
    $title = $piefeed->get_title();
    $link = $piefeed->get_link();
    $description = $piefeed->get_description();
    $safeurl = mysql_escape_string($url);
    $result = fof_do_query("select id, url, aging from feeds where url='{$safeurl}'");
    $row = mysql_fetch_array($result);
    mysql_free_result($result);
    //	echo "Memory usage after first query: " . number_format(memory_get_usage());
    $feed_id = $row['id'];
    $keep_days = $row['aging'];
    if ($keep_days < 0) {
        $keep_days = 60;
    }
    //	$result2 = fof_do_query("select image from feeds where `id`='$feed_id'");
    //	$row2 = mysql_fetch_array($result2);
    //	mysql_free_result($result);
    //echo "Memory usage after second query: " . number_format(memory_get_usage());
    //  $image2 = $row2['image'];
    /*
    	if (!$image2)
    	{
    		$imagelink = $piefeed->get_favicon(true, '');
    		$HTTPRequest = @fopen($imagelink, 'r'); 
    		if ($HTTPRequest) 
    		{ 
    			stream_set_timeout($HTTPRequest, 0.1);
    			$favicon = fread($HTTPRequest, 8192);
    			$HTTPRequestData = stream_get_meta_data($HTTPRequest);
    			fclose($HTTPRequest);
    			if (!$HTTPRequestData['timed_out'] && strlen($favicon) < 42) 
    			{ 
    				$imagelink = "";
    			} 
    		}
    		else
    		{
    			$imagelink = $piefeed->get_image_url();
    			$HTTPRequest = @fopen($imagelink, 'r'); 
    			if ($HTTPRequest) 
    			{ 
    				stream_set_timeout($HTTPRequest, 0.1);
    				$favicon = fread($HTTPRequest, 8192);
    				$HTTPRequestData = stream_get_meta_data($HTTPRequest);
    				fclose($HTTPRequest);
    				if (!$HTTPRequestData['timed_out'] && strlen($favicon) < 42) 
    				{ 
    					$imagelink = "";
    				} 
    			}
    			else
    			{ 
    					$imagelink="";
    			}
    		}
    	
    		$sql = "update `$FOF_FEED_TABLE` set `image`='$imagelink' where `id`='$feed_id'";
    		$result = fof_do_query($sql);
    	mysql_free_result($result);
      
      
      }  // closes image
    */
    #
    # Get article items and attributes
    #
    foreach ($piefeed->get_items() as $item) {
        $ageflag = "0";
        $dccreator = "";
        $dcsubject = "";
        $link = mysql_escape_string($item->get_permalink());
        if (!$link) {
            $link = $item->get_id();
        }
        $title = mysql_escape_string($item->get_title());
        if (!$title) {
            $title = "[" . _("no title") . "]";
        }
        # get <dc:creator> or <author>
        foreach ($item->get_authors() as $author) {
            $authorname = $author->get_name() . " " . $author->get_email();
            if (!empty($authorname)) {
                $dccreator .= $authorname . ', ';
            }
        }
        $dccreator = mysql_escape_string(substr("{$dccreator}", 0, -2));
        # get <dc:date> and <pubdate>
        $dcdate = mysql_escape_string($item->get_date());
        $dcdate = eregi_replace(",", "", $dcdate);
        # get <dc:subject> or <category>
        $category_array = $item->get_category();
        $category_array = array_unique($category_array);
        foreach ($category_array as $category) {
            if (!empty($category)) {
                $dcsubject .= $category . ', ';
            }
        }
        $dcsubject = substr(mysql_escape_string($dcsubject), 0, -2);
        unset($category_array);
        # get article content
        $content = mysql_escape_string($item->get_description());
        $content = str_replace('"?i=http', '"http', $content);
        # dont know why
        # this creeps in
        if ($enclosure = $item->get_enclosure(0)) {
            $content .= '<br />(' . $enclosure->get_type() . '; ' . $enclosure->get_size() . ' MB)<br />';
        }
        #
        # Now manage the article data
        #
        $sql = "select id from items where feed_id='{$feed_id}' and link='{$link}'";
        #print "<br />" . $sql . "<br />";
        $result = fof_do_query($sql);
        $row = mysql_fetch_array($result);
        $id = $row['id'];
        //mysql_free_result($result);
        # if the item does not already exist, add it
        if (mysql_num_rows($result) == 0) {
            # dcdate   : August 2, 2006, 1:30 am
            # timestamp: 2006-09-16 15:51:53
            # add it only if it's not older than keep_days
            $dcdatetime = strtotime($dcdate);
            # We set ageflag == 1 if its OK to add the item to the database
            if ($dcdatetime < 1) {
                $dcdatetime = NULL;
                $ageflag = 1;
            } else {
                if (time() - $dcdatetime < $keep_days * 24 * 60 * 60) {
                    $ageflag = 1;
                }
            }
            if ($ageflag) {
                //$n++;
                $sql = "insert into items (feed_id,link,title,content,dcdate,dccreator,dcsubject) values ('{$feed_id}','{$link}','{$title}','{$content}','{$dcdatetime}','{$dccreator}','{$dcsubject}')";
                #print "<br />" . $sql . "<br />";
                $result = fof_do_query($sql);
                mysql_free_result($result);
                $ids[] = $id;
                #keep track of it so we don't delete it below
                $ageflag = 0;
            }
        }
        //echo "Memory usage after item foreach loop: " . number_format(memory_get_usage());
    }
    // closes opening foreach loop
    //unset($piefeed);
    $piefeed->__destruct();
    // Do what PHP should be doing on it's own.
    //unset($item);
    //unset($feed);
    unset($title);
    unset($link);
    unset($description);
    unset($content);
    unset($dcdatetime);
    unset($dccreator);
    unset($dcsubject);
    //return $n;
}
     $rss_obj->set_item_limit($rssfeed["item"]);
 }
 // Init Feed
 $rss_obj->init();
 if ($rss_obj->data) {
     // check RSS image
     if ($rss_obj->get_image_url()) {
         $rss['temp_feedinfo'] = '<a href="' . ($rss_obj->get_image_link() ? $rss_obj->get_image_link() : $rss_obj->get_permalink()) . '" target="_blank">';
         $rss['temp_feedinfo'] .= '<img src="' . $rss_obj->get_image_url() . '" alt="' . $rss_obj->get_image_title() . '" />';
         $rss['temp_feedinfo'] .= '</a>';
         $rss['template_FEEDINFO'] = render_cnt_template($rss['template_FEEDINFO'], 'IMAGE', $rss['temp_feedinfo']);
     } else {
         $rss['template_FEEDINFO'] = render_cnt_template($rss['template_FEEDINFO'], 'IMAGE', '');
     }
     $rss['template_FEEDINFO'] = render_cnt_template($rss['template_FEEDINFO'], 'TITLE', $rss_obj->get_title());
     $rss['template_FEEDINFO'] = render_cnt_template($rss['template_FEEDINFO'], 'DESCRIPTION', $rss_obj->get_description());
     $c = 0;
     $rss['items'] = array();
     foreach ($rss_obj->get_items() as $rssvalue) {
         // general item info
         $rss['items'][$c] = render_cnt_template($rss['template_ITEM'], 'LINK', $rssvalue->get_permalink());
         $rss['items'][$c] = render_cnt_template($rss['items'][$c], 'TITLE', $rssvalue->get_title());
         $rss['items'][$c] = render_cnt_template($rss['items'][$c], 'DESCRIPTION', $rssvalue->get_description());
         $rss['items'][$c] = render_cnt_template($rss['items'][$c], 'CONTENT', $rssvalue->get_content());
         // author
         $rss['item_author'] = $rssvalue->get_author();
         $rss['items'][$c] = render_cnt_template($rss['items'][$c], 'AUTHOR', $rss['item_author'] ? $rss['item_author']->get_name() : '');
         // item date
         $rss['items'][$c] = render_cnt_date($rss['items'][$c], $rssvalue->get_date('U'));
         // Thumbnail
         $rss['item_thumbnail'] = '';
/**
 * The actual function that can be called on webpages.
 */
function SimplePieWP($feed_url, $options = null)
{
    // Quit if the SimplePie class isn't loaded.
    if (!class_exists('SimplePie')) {
        die('<p style="font-size:16px; line-height:1.5em; background-color:#c00; color:#fff; padding:10px; border:3px solid #f00; text-align:left;"><img src="' . SIMPLEPIE_PLUGINDIR_WEB . '/images/error.png" /> There is a problem with the SimplePie Plugin for WordPress. Check your <a href="' . WP_CPANEL . '" style="color:#ff0; text-decoration:underline;">Installation Status</a> for more information.</p>');
    }
    if (isset($locale) && !empty($locale) && $locale != 'auto') {
        setlocale(LC_TIME, $locale);
    }
    // Default general settings
    $template = get_option('simplepie_template');
    $items = get_option('simplepie_items');
    $items_per_feed = get_option('simplepie_items_per_feed');
    $date_format = get_option('simplepie_date_format');
    $enable_cache = get_option('simplepie_enable_cache');
    $set_cache_location = get_option('simplepie_set_cache_location');
    $set_cache_duration = get_option('simplepie_set_cache_duration');
    $enable_order_by_date = get_option('simplepie_enable_order_by_date');
    $set_timeout = get_option('simplepie_set_timeout');
    // Default text-shortening settings
    $truncate_feed_title = get_option('simplepie_truncate_feed_title');
    $truncate_feed_description = get_option('simplepie_truncate_feed_description');
    $truncate_item_title = get_option('simplepie_truncate_item_title');
    $truncate_item_description = get_option('simplepie_truncate_item_description');
    // Default advanced settings
    $processing = get_option('simplepie_processing');
    $locale = get_option('simplepie_locale');
    $local_date_format = get_option('simplepie_local_date_format');
    $strip_htmltags = get_option('simplepie_strip_htmltags');
    $strip_attributes = get_option('simplepie_strip_attributes');
    $set_max_checked_feeds = get_option('simplepie_set_max_checked_feeds');
    // Overridden settings
    if ($options) {
        // Fix the template location if one was passed in.
        if (isset($options['template']) && !empty($options['template'])) {
            $options['template'] = SIMPLEPIE_PLUGINDIR . '/templates/' . strtolower(str_replace(' ', '_', $options['template'])) . '.tmpl';
        }
        // Fix the processing location if one was passed in.
        if (isset($options['processing']) && !empty($options['processing'])) {
            $options['processing'] = SIMPLEPIE_PLUGINDIR . '/processing/' . strtolower(str_replace(' ', '_', $options['processing'])) . '.php';
        }
        extract($options);
    }
    // Load post-processing file.
    if ($processing && $processing != '') {
        include_once $processing;
    }
    // If template doesn't exist, die.
    if (!file_exists($template) || !is_readable($template)) {
        die('<p style="font-size:16px; line-height:1.5em; background-color:#c00; color:#fff; padding:10px; border:3px solid #f00; text-align:left;"><img src="' . SIMPLEPIE_PLUGINDIR_WEB . '/images/error.png" /> The SimplePie template file is not readable by WordPress. Check the <a href="' . WP_CPANEL . '" style="color:#ff0; text-decoration:underline;">WordPress Control Panel</a> for more information.</p>');
    }
    // Initialize SimplePie
    $feed = new SimplePie();
    $feed->set_feed_url($feed_url);
    $feed->enable_cache($enable_cache);
    $feed->set_item_limit($items_per_feed);
    $feed->set_cache_location($set_cache_location);
    $feed->set_cache_duration($set_cache_duration);
    $feed->enable_order_by_date($enable_order_by_date);
    $feed->set_timeout($set_timeout);
    $feed->strip_htmltags(explode(' ', $strip_htmltags));
    $feed->strip_attributes(explode(' ', $strip_attributes));
    $feed->set_max_checked_feeds($set_max_checked_feeds);
    $feed->init();
    // Load up the selected template file
    $handle = fopen($template, 'r');
    $tmpl = fread($handle, filesize($template));
    fclose($handle);
    /**************************************************************************************************************/
    // ERRORS
    // I'm absolutely sure that there is a better way to do this.
    // Define what we're looking for
    $error_start_tag = '{IF_ERROR_BEGIN}';
    $error_end_tag = '{IF_ERROR_END}';
    $error_start_length = strlen($error_start_tag);
    $error_end_length = strlen($error_end_tag);
    // Find what we're looking for
    $error_start_pos = strpos($tmpl, $error_start_tag);
    $error_end_pos = strpos($tmpl, $error_end_tag);
    $error_length_pos = $error_end_pos - $error_start_pos;
    // Grab what we're looking for
    $error_string = substr($tmpl, $error_start_pos + $error_start_length, $error_length_pos - $error_start_length);
    $replacable_string = $error_start_tag . $error_string . $error_end_tag;
    if ($error_message = $feed->error()) {
        $tmpl = str_replace($replacable_string, $error_string, $tmpl);
        $tmpl = str_replace('{ERROR_MESSAGE}', SimplePie_WordPress::post_process('ERROR_MESSAGE', $error_message), $tmpl);
    } elseif ($feed->get_item_quantity() == 0) {
        $tmpl = str_replace($replacable_string, $error_string, $tmpl);
        $tmpl = str_replace('{ERROR_MESSAGE}', SimplePie_WordPress::post_process('ERROR_MESSAGE', 'There are no items in this feed.'), $tmpl);
    } else {
        $tmpl = str_replace($replacable_string, '', $tmpl);
    }
    /**************************************************************************************************************/
    // FEED
    // FEED_AUTHOR_EMAIL
    if ($author = $feed->get_author()) {
        if ($email = $author->get_email()) {
            $tmpl = str_replace('{FEED_AUTHOR_EMAIL}', SimplePie_WordPress::post_process('FEED_AUTHOR_EMAIL', $email), $tmpl);
        } else {
            $tmpl = str_replace('{FEED_AUTHOR_EMAIL}', '', $tmpl);
        }
    } else {
        $tmpl = str_replace('{FEED_AUTHOR_EMAIL}', '', $tmpl);
    }
    // FEED_AUTHOR_LINK
    if ($author = $feed->get_author()) {
        if ($link = $author->get_link()) {
            $tmpl = str_replace('{FEED_AUTHOR_LINK}', SimplePie_WordPress::post_process('FEED_AUTHOR_LINK', $link), $tmpl);
        } else {
            $tmpl = str_replace('{FEED_AUTHOR_LINK}', '', $tmpl);
        }
    } else {
        $tmpl = str_replace('{FEED_AUTHOR_LINK}', '', $tmpl);
    }
    // FEED_AUTHOR_NAME
    if ($author = $feed->get_author()) {
        if ($name = $author->get_name()) {
            $tmpl = str_replace('{FEED_AUTHOR_NAME}', SimplePie_WordPress::post_process('FEED_AUTHOR_NAME', $name), $tmpl);
        } else {
            $tmpl = str_replace('{FEED_AUTHOR_NAME}', '', $tmpl);
        }
    } else {
        $tmpl = str_replace('{FEED_AUTHOR_NAME}', '', $tmpl);
    }
    // FEED_CONTRIBUTOR_EMAIL
    if ($contributor = $feed->get_contributor()) {
        if ($email = $contributor->get_email()) {
            $tmpl = str_replace('{FEED_CONTRIBUTOR_EMAIL}', SimplePie_WordPress::post_process('FEED_CONTRIBUTOR_EMAIL', $email), $tmpl);
        } else {
            $tmpl = str_replace('{FEED_CONTRIBUTOR_EMAIL}', '', $tmpl);
        }
    } else {
        $tmpl = str_replace('{FEED_CONTRIBUTOR_EMAIL}', '', $tmpl);
    }
    // FEED_CONTRIBUTOR_LINK
    if ($contributor = $feed->get_contributor()) {
        if ($link = $contributor->get_link()) {
            $tmpl = str_replace('{FEED_CONTRIBUTOR_LINK}', SimplePie_WordPress::post_process('FEED_CONTRIBUTOR_LINK', $link), $tmpl);
        } else {
            $tmpl = str_replace('{FEED_CONTRIBUTOR_LINK}', '', $tmpl);
        }
    } else {
        $tmpl = str_replace('{FEED_CONTRIBUTOR_LINK}', '', $tmpl);
    }
    // FEED_CONTRIBUTOR_NAME
    if ($contributor = $feed->get_contributor()) {
        if ($name = $contributor->get_name()) {
            $tmpl = str_replace('{FEED_CONTRIBUTOR_NAME}', SimplePie_WordPress::post_process('FEED_CONTRIBUTOR_NAME', $name), $tmpl);
        } else {
            $tmpl = str_replace('{FEED_CONTRIBUTOR_NAME}', '', $tmpl);
        }
    } else {
        $tmpl = str_replace('{FEED_CONTRIBUTOR_NAME}', '', $tmpl);
    }
    // FEED_COPYRIGHT
    if ($copyright = $feed->get_copyright()) {
        $tmpl = str_replace('{FEED_COPYRIGHT}', SimplePie_WordPress::post_process('FEED_COPYRIGHT', $copyright), $tmpl);
    } else {
        $tmpl = str_replace('{FEED_COPYRIGHT}', '', $tmpl);
    }
    // FEED_DESCRIPTION
    if ($description = $feed->get_description()) {
        $tmpl = str_replace('{FEED_DESCRIPTION}', SimplePie_WordPress::post_process('FEED_DESCRIPTION', $description), $tmpl);
    } else {
        $tmpl = str_replace('{FEED_DESCRIPTION}', '', $tmpl);
    }
    // FEED_ENCODING
    if ($encoding = $feed->get_encoding()) {
        $tmpl = str_replace('{FEED_ENCODING}', SimplePie_WordPress::post_process('FEED_ENCODING', $encoding), $tmpl);
    } else {
        $tmpl = str_replace('{FEED_ENCODING}', '', $tmpl);
    }
    // FEED_FAVICON
    if ($favicon = $feed->get_favicon()) {
        $tmpl = str_replace('{FEED_FAVICON}', SimplePie_WordPress::post_process('FEED_FAVICON', $favicon), $tmpl);
    } else {
        $tmpl = str_replace('{FEED_FAVICON}', '', $tmpl);
    }
    // FEED_IMAGE_HEIGHT
    if ($image_height = $feed->get_image_height()) {
        $tmpl = str_replace('{FEED_IMAGE_HEIGHT}', SimplePie_WordPress::post_process('FEED_IMAGE_HEIGHT', $image_height), $tmpl);
    } else {
        $tmpl = str_replace('{FEED_IMAGE_HEIGHT}', '', $tmpl);
    }
    // FEED_IMAGE_LINK
    if ($image_link = $feed->get_image_link()) {
        $tmpl = str_replace('{FEED_IMAGE_LINK}', SimplePie_WordPress::post_process('FEED_IMAGE_LINK', $image_link), $tmpl);
    } else {
        $tmpl = str_replace('{FEED_IMAGE_LINK}', '', $tmpl);
    }
    // FEED_IMAGE_TITLE
    if ($image_title = $feed->get_image_title()) {
        $tmpl = str_replace('{FEED_IMAGE_TITLE}', SimplePie_WordPress::post_process('FEED_IMAGE_TITLE', $image_title), $tmpl);
    } else {
        $tmpl = str_replace('{FEED_IMAGE_TITLE}', '', $tmpl);
    }
    // FEED_IMAGE_URL
    if ($image_url = $feed->get_image_url()) {
        $tmpl = str_replace('{FEED_IMAGE_URL}', SimplePie_WordPress::post_process('FEED_IMAGE_URL', $image_url), $tmpl);
    } else {
        $tmpl = str_replace('{FEED_IMAGE_URL}', '', $tmpl);
    }
    // FEED_IMAGE_WIDTH
    if ($image_width = $feed->get_image_width()) {
        $tmpl = str_replace('{FEED_IMAGE_WIDTH}', SimplePie_WordPress::post_process('FEED_IMAGE_WIDTH', $image_width), $tmpl);
    } else {
        $tmpl = str_replace('{FEED_IMAGE_WIDTH}', '', $tmpl);
    }
    // FEED_LANGUAGE
    if ($language = $feed->get_language()) {
        $tmpl = str_replace('{FEED_LANGUAGE}', SimplePie_WordPress::post_process('FEED_LANGUAGE', $language), $tmpl);
    } else {
        $tmpl = str_replace('{FEED_LANGUAGE}', '', $tmpl);
    }
    // FEED_LATITUDE
    if ($latitude = $feed->get_latitude()) {
        $tmpl = str_replace('{FEED_LATITUDE}', SimplePie_WordPress::post_process('FEED_LATITUDE', $latitude), $tmpl);
    } else {
        $tmpl = str_replace('{FEED_LATITUDE}', '', $tmpl);
    }
    // FEED_LONGITUDE
    if ($longitude = $feed->get_longitude()) {
        $tmpl = str_replace('{FEED_LONGITUDE}', SimplePie_WordPress::post_process('FEED_LONGITUDE', $longitude), $tmpl);
    } else {
        $tmpl = str_replace('{FEED_LONGITUDE}', '', $tmpl);
    }
    // FEED_PERMALINK
    if ($permalink = $feed->get_permalink()) {
        $tmpl = str_replace('{FEED_PERMALINK}', SimplePie_WordPress::post_process('FEED_PERMALINK', $permalink), $tmpl);
    } else {
        $tmpl = str_replace('{FEED_PERMALINK}', '', $tmpl);
    }
    // FEED_TITLE
    if ($title = $feed->get_title()) {
        $tmpl = str_replace('{FEED_TITLE}', SimplePie_WordPress::post_process('FEED_TITLE', $title), $tmpl);
    } else {
        $tmpl = str_replace('{FEED_TITLE}', '', $tmpl);
    }
    // SUBSCRIBE_URL
    if ($subscribe_url = $feed->subscribe_url()) {
        $tmpl = str_replace('{SUBSCRIBE_URL}', SimplePie_WordPress::post_process('SUBSCRIBE_URL', $subscribe_url), $tmpl);
    } else {
        $tmpl = str_replace('{SUBSCRIBE_URL}', '', $tmpl);
    }
    // TRUNCATE_FEED_DESCRIPTION
    if ($description = $feed->get_description()) {
        $tmpl = str_replace('{TRUNCATE_FEED_DESCRIPTION}', SimplePie_Truncate(SimplePie_WordPress::post_process('TRUNCATE_FEED_DESCRIPTION', $description), $truncate_feed_description), $tmpl);
    } else {
        $tmpl = str_replace('{TRUNCATE_FEED_DESCRIPTION}', '', $tmpl);
    }
    // TRUNCATE_FEED_TITLE
    if ($title = $feed->get_title()) {
        $tmpl = str_replace('{TRUNCATE_FEED_TITLE}', SimplePie_Truncate(SimplePie_WordPress::post_process('TRUNCATE_FEED_TITLE', $title), $truncate_feed_title), $tmpl);
    } else {
        $tmpl = str_replace('{TRUNCATE_FEED_TITLE}', '', $tmpl);
    }
    /**************************************************************************************************************/
    // ITEMS
    // Separate out the pre-item template
    $tmpl = explode('{ITEM_LOOP_BEGIN}', $tmpl);
    $pre_tmpl = $tmpl[0];
    // Separate out the item template
    $tmpl = explode('{ITEM_LOOP_END}', $tmpl[1]);
    $item_tmpl = $tmpl[0];
    // Separate out the post-item template
    $post_tmpl = $tmpl[1];
    // Clear out the variable
    unset($tmpl);
    // Start putting the output string together.
    $tmpl = $pre_tmpl;
    // Loop through all of the items that we're supposed to.
    foreach ($feed->get_items(0, $items) as $item) {
        // Get a reference to the parent $feed object.
        $parent = $item->get_feed();
        // Get a working copy of the item template.  We don't want to edit the original.
        $working_item = $item_tmpl;
        // ITEM_CONTRIBUTOR_EMAIL
        if ($contributor = $item->get_contributor()) {
            if ($email = $contributor->get_email()) {
                $working_item = str_replace('{ITEM_CONTRIBUTOR_EMAIL}', SimplePie_WordPress::post_process('ITEM_CONTRIBUTOR_EMAIL', $email), $working_item);
            } else {
                $working_item = str_replace('{ITEM_CONTRIBUTOR_EMAIL}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_CONTRIBUTOR_EMAIL}', '', $working_item);
        }
        // ITEM_CONTRIBUTOR_LINK
        if ($contributor = $item->get_contributor()) {
            if ($link = $contributor->get_link()) {
                $working_item = str_replace('{ITEM_CONTRIBUTOR_LINK}', SimplePie_WordPress::post_process('ITEM_CONTRIBUTOR_LINK', $link), $working_item);
            } else {
                $working_item = str_replace('{ITEM_CONTRIBUTOR_LINK}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_CONTRIBUTOR_LINK}', '', $working_item);
        }
        // ITEM_CONTRIBUTOR_NAME
        if ($contributor = $item->get_contributor()) {
            if ($name = $contributor->get_name()) {
                $working_item = str_replace('{ITEM_CONTRIBUTOR_NAME}', SimplePie_WordPress::post_process('ITEM_CONTRIBUTOR_NAME', $name), $working_item);
            } else {
                $working_item = str_replace('{ITEM_CONTRIBUTOR_NAME}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_CONTRIBUTOR_NAME}', '', $working_item);
        }
        // ITEM_COPYRIGHT
        if ($copyright = $item->get_copyright()) {
            $working_item = str_replace('{ITEM_COPYRIGHT}', SimplePie_WordPress::post_process('ITEM_COPYRIGHT', $copyright), $working_item);
        } else {
            $working_item = str_replace('{ITEM_COPYRIGHT}', '', $working_item);
        }
        // ITEM_PARENT_AUTHOR_EMAIL
        if ($author = $parent->get_author()) {
            if ($email = $author->get_email()) {
                $working_item = str_replace('{ITEM_PARENT_AUTHOR_EMAIL}', SimplePie_WordPress::post_process('ITEM_PARENT_AUTHOR_EMAIL', $email), $working_item);
            } else {
                $working_item = str_replace('{ITEM_PARENT_AUTHOR_EMAIL}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_PARENT_AUTHOR_EMAIL}', '', $working_item);
        }
        // ITEM_PARENT_AUTHOR_LINK
        if ($author = $parent->get_author()) {
            if ($link = $author->get_link()) {
                $working_item = str_replace('{ITEM_PARENT_AUTHOR_LINK}', SimplePie_WordPress::post_process('ITEM_PARENT_AUTHOR_LINK', $link), $working_item);
            } else {
                $working_item = str_replace('{ITEM_PARENT_AUTHOR_LINK}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_PARENT_AUTHOR_LINK}', '', $working_item);
        }
        // ITEM_PARENT_AUTHOR_NAME
        if ($author = $parent->get_author()) {
            if ($name = $author->get_name()) {
                $working_item = str_replace('{ITEM_PARENT_AUTHOR_NAME}', SimplePie_WordPress::post_process('ITEM_PARENT_AUTHOR_NAME', $name), $working_item);
            } else {
                $working_item = str_replace('{ITEM_PARENT_AUTHOR_NAME}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_PARENT_AUTHOR_NAME}', '', $working_item);
        }
        // ITEM_PARENT_CONTRIBUTOR_EMAIL
        if ($contributor = $parent->get_contributor()) {
            if ($email = $contributor->get_email()) {
                $working_item = str_replace('{ITEM_PARENT_CONTRIBUTOR_EMAIL}', SimplePie_WordPress::post_process('ITEM_PARENT_CONTRIBUTOR_EMAIL', $email), $working_item);
            } else {
                $working_item = str_replace('{ITEM_PARENT_CONTRIBUTOR_EMAIL}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_PARENT_CONTRIBUTOR_EMAIL}', '', $working_item);
        }
        // ITEM_PARENT_CONTRIBUTOR_LINK
        if ($contributor = $parent->get_contributor()) {
            if ($link = $contributor->get_link()) {
                $working_item = str_replace('{ITEM_PARENT_CONTRIBUTOR_LINK}', SimplePie_WordPress::post_process('ITEM_PARENT_CONTRIBUTOR_LINK', $link), $working_item);
            } else {
                $working_item = str_replace('{ITEM_PARENT_CONTRIBUTOR_LINK}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_PARENT_CONTRIBUTOR_LINK}', '', $working_item);
        }
        // ITEM_PARENT_CONTRIBUTOR_NAME
        if ($contributor = $parent->get_contributor()) {
            if ($name = $contributor->get_name()) {
                $working_item = str_replace('{ITEM_PARENT_CONTRIBUTOR_NAME}', SimplePie_WordPress::post_process('ITEM_PARENT_CONTRIBUTOR_NAME', $name), $working_item);
            } else {
                $working_item = str_replace('{ITEM_PARENT_CONTRIBUTOR_NAME}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_PARENT_CONTRIBUTOR_NAME}', '', $working_item);
        }
        // ITEM_AUTHOR_EMAIL
        if ($author = $item->get_author()) {
            if ($email = $author->get_email()) {
                $working_item = str_replace('{ITEM_AUTHOR_EMAIL}', SimplePie_WordPress::post_process('ITEM_AUTHOR_EMAIL', $email), $working_item);
            } else {
                $working_item = str_replace('{ITEM_AUTHOR_EMAIL}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_AUTHOR_EMAIL}', '', $working_item);
        }
        // ITEM_AUTHOR_LINK
        if ($author = $item->get_author()) {
            if ($link = $author->get_link()) {
                $working_item = str_replace('{ITEM_AUTHOR_LINK}', SimplePie_WordPress::post_process('ITEM_AUTHOR_LINK', $link), $working_item);
            } else {
                $working_item = str_replace('{ITEM_AUTHOR_LINK}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_AUTHOR_LINK}', '', $working_item);
        }
        // ITEM_AUTHOR_NAME
        if ($author = $item->get_author()) {
            if ($name = $author->get_name()) {
                $working_item = str_replace('{ITEM_AUTHOR_NAME}', SimplePie_WordPress::post_process('ITEM_AUTHOR_NAME', $name), $working_item);
            } else {
                $working_item = str_replace('{ITEM_AUTHOR_NAME}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_AUTHOR_NAME}', '', $working_item);
        }
        // ITEM_CATEGORY
        if ($category = $item->get_category()) {
            if ($label = $category->get_label()) {
                $working_item = str_replace('{ITEM_CATEGORY}', SimplePie_WordPress::post_process('ITEM_CATEGORY', $label), $working_item);
            } else {
                $working_item = str_replace('{ITEM_CATEGORY}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_CATEGORY}', '', $working_item);
        }
        // ITEM_CONTENT
        if ($content = $item->get_content()) {
            $working_item = str_replace('{ITEM_CONTENT}', SimplePie_WordPress::post_process('ITEM_CONTENT', $content), $working_item);
        } else {
            $working_item = str_replace('{ITEM_CONTENT}', '', $working_item);
        }
        // ITEM_DATE
        if ($date = $item->get_date($date_format)) {
            $working_item = str_replace('{ITEM_DATE}', SimplePie_WordPress::post_process('ITEM_DATE', $date), $working_item);
        } else {
            $working_item = str_replace('{ITEM_DATE}', '', $working_item);
        }
        // ITEM_DATE_UTC
        if ($date = $item->get_date('U')) {
            $date = gmdate($date_format, $date);
            $working_item = str_replace('{ITEM_DATE_UTC}', SimplePie_WordPress::post_process('ITEM_DATE_UTC', $date), $working_item);
        } else {
            $working_item = str_replace('{ITEM_DATE_UTC}', '', $working_item);
        }
        // ITEM_DESCRIPTION
        if ($description = $item->get_description()) {
            $working_item = str_replace('{ITEM_DESCRIPTION}', SimplePie_WordPress::post_process('ITEM_DESCRIPTION', $description), $working_item);
        } else {
            $working_item = str_replace('{ITEM_DESCRIPTION}', '', $working_item);
        }
        // ITEM_ENCLOSURE_EMBED
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->native_embed()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_EMBED}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_EMBED', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_EMBED}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_EMBED}', '', $working_item);
        }
        // ITEM_ENCLOSURE_EXTENSION
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_extension()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_EXTENSION}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_EXTENSION', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_EXTENSION}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_EXTENSION}', '', $working_item);
        }
        // ITEM_ENCLOSURE_HANDLER
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_handler()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_HANDLER}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_HANDLER', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_HANDLER}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_HANDLER}', '', $working_item);
        }
        // ITEM_ENCLOSURE_LENGTH
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_length()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_LENGTH}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_LENGTH', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_LENGTH}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_LENGTH}', '', $working_item);
        }
        // ITEM_ENCLOSURE_LINK
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_link()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_LINK}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_LINK', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_LINK}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_LINK}', '', $working_item);
        }
        // ITEM_ENCLOSURE_REAL_TYPE
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_real_type()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_REAL_TYPE}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_REAL_TYPE', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_REAL_TYPE}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_REAL_TYPE}', '', $working_item);
        }
        // ITEM_ENCLOSURE_SIZE
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_size()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_SIZE}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_SIZE', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_SIZE}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_SIZE}', '', $working_item);
        }
        // ITEM_ENCLOSURE_TYPE
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_type()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_TYPE}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_TYPE', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_TYPE}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_TYPE}', '', $working_item);
        }
        // ITEM_ENCLOSURE_BITRATE
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_bitrate()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_BITRATE}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_BITRATE', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_BITRATE}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_BITRATE}', '', $working_item);
        }
        // ITEM_ENCLOSURE_CHANNELS
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_channels()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_CHANNELS}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_CHANNELS', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_CHANNELS}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_CHANNELS}', '', $working_item);
        }
        // ITEM_ENCLOSURE_DESCRIPTION
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_description()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_DESCRIPTION}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_DESCRIPTION', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_DESCRIPTION}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_DESCRIPTION}', '', $working_item);
        }
        // ITEM_ENCLOSURE_DURATION
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_duration()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_DURATION}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_DURATION', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_DURATION}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_DURATION}', '', $working_item);
        }
        // ITEM_ENCLOSURE_EXPRESSION
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_expression()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_EXPRESSION}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_EXPRESSION', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_EXPRESSION}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_EXPRESSION}', '', $working_item);
        }
        // ITEM_ENCLOSURE_FRAMERATE
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_framerate()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_FRAMERATE}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_FRAMERATE', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_FRAMERATE}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_FRAMERATE}', '', $working_item);
        }
        // ITEM_ENCLOSURE_HASH
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_hash()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_HASH}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_HASH', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_HASH}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_HASH}', '', $working_item);
        }
        // ITEM_ENCLOSURE_HEIGHT
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_height()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_HEIGHT}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_HEIGHT', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_HEIGHT}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_HEIGHT}', '', $working_item);
        }
        // ITEM_ENCLOSURE_LANGUAGE
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_language()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_LANGUAGE}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_LANGUAGE', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_LANGUAGE}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_LANGUAGE}', '', $working_item);
        }
        // ITEM_ENCLOSURE_MEDIUM
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_medium()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_MEDIUM}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_MEDIUM', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_MEDIUM}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_MEDIUM}', '', $working_item);
        }
        // ITEM_ENCLOSURE_PLAYER
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_player()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_PLAYER}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_PLAYER', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_PLAYER}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_PLAYER}', '', $working_item);
        }
        // ITEM_ENCLOSURE_SAMPLINGRATE
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_sampling_rate()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_SAMPLINGRATE}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_SAMPLINGRATE', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_SAMPLINGRATE}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_SAMPLINGRATE}', '', $working_item);
        }
        // ITEM_ENCLOSURE_THUMBNAIL
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_thumbnail()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_THUMBNAIL}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_THUMBNAIL', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_THUMBNAIL}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_THUMBNAIL}', '', $working_item);
        }
        // ITEM_ENCLOSURE_TITLE
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_title()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_TITLE}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_TITLE', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_TITLE}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_TITLE}', '', $working_item);
        }
        // ITEM_ENCLOSURE_WIDTH
        if ($enclosure = $item->get_enclosure()) {
            if ($encltemp = $enclosure->get_width()) {
                $working_item = str_replace('{ITEM_ENCLOSURE_WIDTH}', SimplePie_WordPress::post_process('ITEM_ENCLOSURE_WIDTH', $encltemp), $working_item);
            } else {
                $working_item = str_replace('{ITEM_ENCLOSURE_WIDTH}', '', $working_item);
            }
        } else {
            $working_item = str_replace('{ITEM_ENCLOSURE_WIDTH}', '', $working_item);
        }
        // ITEM_ID
        if ($id = $item->get_id()) {
            $working_item = str_replace('{ITEM_ID}', SimplePie_WordPress::post_process('ITEM_ID', $id), $working_item);
        } else {
            $working_item = str_replace('{ITEM_ID}', '', $working_item);
        }
        // ITEM_ID
        if ($latitude = $item->get_latitude()) {
            $working_item = str_replace('{ITEM_LATITUDE}', SimplePie_WordPress::post_process('ITEM_LATITUDE', $latitude), $working_item);
        } else {
            $working_item = str_replace('{ITEM_LATITUDE}', '', $working_item);
        }
        // ITEM_LOCAL_DATE
        if ($local_date = $item->get_local_date($local_date_format)) {
            $working_item = str_replace('{ITEM_LOCAL_DATE}', SimplePie_WordPress::post_process('ITEM_LOCAL_DATE', $local_date), $working_item);
        } else {
            $working_item = str_replace('{ITEM_LOCAL_DATE}', '', $working_item);
        }
        // ITEM_LOCAL_DATE_UTC
        if ($local_date = $item->get_date('U')) {
            $local_date = gmdate('U', $local_date);
            $local_date = strftime($local_date_format, $local_date);
            $working_item = str_replace('{ITEM_LOCAL_DATE_UTC}', SimplePie_WordPress::post_process('ITEM_LOCAL_DATE_UTC', $local_date), $working_item);
        } else {
            $working_item = str_replace('{ITEM_LOCAL_DATE_UTC}', '', $working_item);
        }
        // ITEM_LONGITUDE
        if ($longitude = $item->get_longitude()) {
            $working_item = str_replace('{ITEM_LONGITUDE}', SimplePie_WordPress::post_process('ITEM_LONGITUDE', $longitude), $working_item);
        } else {
            $working_item = str_replace('{ITEM_LONGITUDE}', '', $working_item);
        }
        // ITEM_PERMALINK
        if ($permalink = $item->get_permalink()) {
            $working_item = str_replace('{ITEM_PERMALINK}', SimplePie_WordPress::post_process('ITEM_PERMALINK', $permalink), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PERMALINK}', '', $working_item);
        }
        // ITEM_TITLE
        if ($title = $item->get_title()) {
            $working_item = str_replace('{ITEM_TITLE}', SimplePie_WordPress::post_process('ITEM_TITLE', $title), $working_item);
        } else {
            $working_item = str_replace('{ITEM_TITLE}', '', $working_item);
        }
        // ITEM_PARENT_COPYRIGHT
        if ($copyright = $parent->get_copyright()) {
            $working_item = str_replace('{ITEM_PARENT_COPYRIGHT}', SimplePie_WordPress::post_process('ITEM_PARENT_COPYRIGHT', $copyright), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_COPYRIGHT}', '', $working_item);
        }
        // ITEM_PARENT_DESCRIPTION
        if ($description = $parent->get_description()) {
            $working_item = str_replace('{ITEM_PARENT_DESCRIPTION}', SimplePie_WordPress::post_process('ITEM_PARENT_DESCRIPTION', $description), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_DESCRIPTION}', '', $working_item);
        }
        // ITEM_PARENT_ENCODING
        if ($encoding = $parent->get_encoding()) {
            $working_item = str_replace('{ITEM_PARENT_ENCODING}', SimplePie_WordPress::post_process('ITEM_PARENT_ENCODING', $encoding), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_ENCODING}', '', $working_item);
        }
        // ITEM_PARENT_FAVICON
        if ($favicon = $parent->get_favicon()) {
            $working_item = str_replace('{ITEM_PARENT_FAVICON}', SimplePie_WordPress::post_process('ITEM_PARENT_FAVICON', $favicon), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_FAVICON}', '', $working_item);
        }
        // ITEM_PARENT_IMAGE_HEIGHT
        if ($image_height = $parent->get_image_height()) {
            $working_item = str_replace('{ITEM_PARENT_IMAGE_HEIGHT}', SimplePie_WordPress::post_process('ITEM_PARENT_IMAGE_HEIGHT', $image_height), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_IMAGE_HEIGHT}', '', $working_item);
        }
        // ITEM_PARENT_IMAGE_LINK
        if ($image_link = $parent->get_image_link()) {
            $working_item = str_replace('{ITEM_PARENT_IMAGE_LINK}', SimplePie_WordPress::post_process('ITEM_PARENT_IMAGE_LINK', $image_link), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_IMAGE_LINK}', '', $working_item);
        }
        // ITEM_PARENT_IMAGE_TITLE
        if ($image_title = $parent->get_image_title()) {
            $working_item = str_replace('{ITEM_PARENT_IMAGE_TITLE}', SimplePie_WordPress::post_process('ITEM_PARENT_IMAGE_TITLE', $image_title), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_IMAGE_TITLE}', '', $working_item);
        }
        // ITEM_PARENT_IMAGE_URL
        if ($image_url = $parent->get_image_url()) {
            $working_item = str_replace('{ITEM_PARENT_IMAGE_URL}', SimplePie_WordPress::post_process('ITEM_PARENT_IMAGE_URL', $image_url), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_IMAGE_URL}', '', $working_item);
        }
        // ITEM_PARENT_IMAGE_WIDTH
        if ($image_width = $parent->get_image_width()) {
            $working_item = str_replace('{ITEM_PARENT_IMAGE_WIDTH}', SimplePie_WordPress::post_process('ITEM_PARENT_IMAGE_WIDTH', $image_width), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_IMAGE_WIDTH}', '', $working_item);
        }
        // ITEM_PARENT_LANGUAGE
        if ($language = $parent->get_language()) {
            $working_item = str_replace('{ITEM_PARENT_LANGUAGE}', SimplePie_WordPress::post_process('ITEM_PARENT_LANGUAGE', $language), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_LANGUAGE}', '', $working_item);
        }
        // ITEM_PARENT_LATITUDE
        if ($latitude = $parent->get_latitude()) {
            $working_item = str_replace('{ITEM_PARENT_LATITUDE}', SimplePie_WordPress::post_process('ITEM_PARENT_LATITUDE', $latitude), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_LATITUDE}', '', $working_item);
        }
        // ITEM_PARENT_LONGITUDE
        if ($longitude = $parent->get_longitude()) {
            $working_item = str_replace('{ITEM_PARENT_LONGITUDE}', SimplePie_WordPress::post_process('ITEM_PARENT_LONGITUDE', $longitude), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_LONGITUDE}', '', $working_item);
        }
        // ITEM_PARENT_PERMALINK
        if ($permalink = $parent->get_permalink()) {
            $working_item = str_replace('{ITEM_PARENT_PERMALINK}', SimplePie_WordPress::post_process('ITEM_PARENT_PERMALINK', $permalink), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_PERMALINK}', '', $working_item);
        }
        // ITEM_PARENT_TITLE
        if ($title = $parent->get_title()) {
            $working_item = str_replace('{ITEM_PARENT_TITLE}', SimplePie_WordPress::post_process('ITEM_PARENT_TITLE', $title), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_TITLE}', '', $working_item);
        }
        // ITEM_PARENT_SUBSCRIBE_URL
        if ($subscribe_url = $parent->subscribe_url()) {
            $working_item = str_replace('{ITEM_PARENT_SUBSCRIBE_URL}', SimplePie_WordPress::post_process('ITEM_PARENT_SUBSCRIBE_URL', $subscribe_url), $working_item);
        } else {
            $working_item = str_replace('{ITEM_PARENT_SUBSCRIBE_URL}', '', $working_item);
        }
        // TRUNCATE_ITEM_DESCRIPTION
        if ($description = $item->get_description()) {
            $working_item = str_replace('{TRUNCATE_ITEM_DESCRIPTION}', SimplePie_Truncate(SimplePie_WordPress::post_process('TRUNCATE_ITEM_DESCRIPTION', $description), $truncate_item_description), $working_item);
        } else {
            $working_item = str_replace('{TRUNCATE_ITEM_DESCRIPTION}', '', $working_item);
        }
        // TRUNCATE_ITEM_TITLE
        if ($title = $item->get_title()) {
            $working_item = str_replace('{TRUNCATE_ITEM_TITLE}', SimplePie_Truncate(SimplePie_WordPress::post_process('TRUNCATE_ITEM_TITLE', $title), $truncate_item_title), $working_item);
        } else {
            $working_item = str_replace('{TRUNCATE_ITEM_TITLE}', '', $working_item);
        }
        // TRUNCATE_ITEM_PARENT_DESCRIPTION
        if ($description = $parent->get_description()) {
            $working_item = str_replace('{TRUNCATE_ITEM_PARENT_DESCRIPTION}', SimplePie_Truncate(SimplePie_WordPress::post_process('TRUNCATE_ITEM_PARENT_DESCRIPTION', $description), $truncate_feed_description), $working_item);
        } else {
            $working_item = str_replace('{TRUNCATE_ITEM_PARENT_DESCRIPTION}', '', $working_item);
        }
        // TRUNCATE_ITEM_PARENT_TITLE
        if ($title = $parent->get_title()) {
            $working_item = str_replace('{TRUNCATE_ITEM_PARENT_TITLE}', SimplePie_Truncate(SimplePie_WordPress::post_process('TRUNCATE_ITEM_PARENT_TITLE', $title), $truncate_feed_title), $working_item);
        } else {
            $working_item = str_replace('{TRUNCATE_ITEM_PARENT_TITLE}', '', $working_item);
        }
        $tmpl .= $working_item;
    }
    /**************************************************************************************************************/
    // LAST STUFF
    // Start by removing all line breaks and tabs.
    $tmpl = preg_replace('/(\\n|\\r|\\t)/i', "", $tmpl);
    // PLUGIN_DIR
    $tmpl = str_replace('{PLUGIN_DIR}', SIMPLEPIE_PLUGINDIR_WEB, $tmpl);
    $tmpl .= $post_tmpl;
    // Kill the object to prevent memory leaks.
    $feed->__destruct();
    unset($feed);
    unset($encltemp);
    unset($working_item);
    // Return the data back to the page.
    return $tmpl;
}
Exemple #20
0
 function parse($syncId, &$nbEvents = 0, $enableCache = true, $forceFeed = false)
 {
     $nbEvents = 0;
     assert('is_int($syncId) && $syncId>0');
     if (empty($this->id) || 0 == $this->id) {
         /* Le flux ne dispose pas pas d'id !. Ça arrive si on appelle
            parse() sans avoir appelé save() pour un nouveau flux.
            @TODO: un create() pour un nouveau flux ? */
         $msg = 'Empty or null id for a feed! ' . 'See ' . __FILE__ . ' on line ' . __LINE__;
         error_log($msg, E_USER_ERROR);
         die($msg);
         // Arrêt, sinon création événements sans flux associé.
     }
     $feed = new SimplePie();
     $feed->enable_cache($enableCache);
     $feed->force_feed($forceFeed);
     $feed->set_feed_url($this->url);
     $feed->set_useragent('Mozilla/4.0 Leed (LightFeed Aggregator) ' . VERSION_NAME . ' by idleman http://projet.idleman.fr/leed');
     if (!$feed->init()) {
         $this->error = $feed->error;
         $this->lastupdate = $_SERVER['REQUEST_TIME'];
         $this->save();
         return false;
     }
     $feed->handle_content_type();
     // UTF-8 par défaut pour SimplePie
     if ($this->name == '') {
         $this->name = $feed->get_title();
     }
     if ($this->name == '') {
         $this->name = $this->url;
     }
     $this->website = $feed->get_link();
     $this->description = $feed->get_description();
     $items = $feed->get_items();
     $eventManager = new Event();
     $events = array();
     $iEvents = 0;
     foreach ($items as $item) {
         // Ne retient que les 100 premiers éléments de flux.
         if ($iEvents++ >= 100) {
             break;
         }
         // Si le guid existe déjà, on évite de le reparcourir.
         $alreadyParsed = $eventManager->load(array('guid' => $item->get_id(), 'feed' => $this->id));
         if (isset($alreadyParsed) && $alreadyParsed != false) {
             $events[] = $alreadyParsed->getId();
             continue;
         }
         // Initialisation des informations de l'événement (élt. de flux)
         $event = new Event();
         $event->setSyncId($syncId);
         $event->setGuid($item->get_id());
         $event->setTitle($item->get_title());
         $event->setPubdate($item->get_date());
         $event->setCreator('' == $item->get_author() ? '' : $item->get_author()->name);
         $event->setLink($item->get_permalink());
         $event->setFeed($this->id);
         $event->setUnread(1);
         // inexistant, donc non-lu
         //Gestion de la balise enclosure pour les podcasts et autre cochonneries :)
         $enclosure = $item->get_enclosure();
         if ($enclosure != null && $enclosure->link != '') {
             $enclosureName = substr($enclosure->link, strrpos($enclosure->link, '/') + 1, strlen($enclosure->link));
             $enclosureArgs = strpos($enclosureName, '?');
             if ($enclosureArgs !== false) {
                 $enclosureName = substr($enclosureName, 0, $enclosureArgs);
             }
             $enclosureFormat = isset($enclosure->handler) ? $enclosure->handler : substr($enclosureName, strrpos($enclosureName, '.') + 1);
             $enclosure = '<div class="enclosure"><h1>Fichier média :</h1><a href="' . $enclosure->link . '"> ' . $enclosureName . '</a> <span>(Format ' . strtoupper($enclosureFormat) . ', ' . Functions::convertFileSize($enclosure->length) . ')</span></div>';
         } else {
             $enclosure = '';
         }
         $event->setContent($item->get_content() . $enclosure);
         $event->setDescription($item->get_description() . $enclosure);
         if (trim($event->getDescription()) == '') {
             $event->setDescription(substr($event->getContent(), 0, 300) . '…<br><a href="' . $event->getLink() . '">Lire la suite de l\'article</a>');
         }
         if (trim($event->getContent()) == '') {
             $event->setContent($event->getDescription());
         }
         $event->setCategory($item->get_category());
         $event->save();
         $nbEvents++;
     }
     $listid = "";
     foreach ($events as $item) {
         $listid .= ',' . $item;
     }
     $query = 'UPDATE `' . MYSQL_PREFIX . 'event` SET syncId=' . $syncId . ' WHERE id in (0' . $listid . ');';
     $myQuery = $this->customQuery($query);
     $this->lastupdate = $_SERVER['REQUEST_TIME'];
     $this->save();
     return true;
 }
Exemple #21
0
function probe_url($url, $mode = PROBE_NORMAL)
{
    require_once 'include/email.php';
    $result = array();
    if (!$url) {
        return $result;
    }
    $network = null;
    $diaspora = false;
    $diaspora_base = '';
    $diaspora_guid = '';
    $diaspora_key = '';
    $has_lrdd = false;
    $email_conversant = false;
    $twitter = strpos($url, 'twitter.com') !== false ? true : false;
    $at_addr = strpos($url, '@') !== false ? true : false;
    if (!$twitter) {
        if (strpos($url, 'mailto:') !== false && $at_addr) {
            $url = str_replace('mailto:', '', $url);
            $links = array();
        } else {
            $links = lrdd($url);
        }
        if (count($links)) {
            $has_lrdd = true;
            logger('probe_url: found lrdd links: ' . print_r($links, true), LOGGER_DATA);
            foreach ($links as $link) {
                if ($link['@attributes']['rel'] === NAMESPACE_ZOT) {
                    $zot = unamp($link['@attributes']['href']);
                }
                if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
                    $dfrn = unamp($link['@attributes']['href']);
                }
                if ($link['@attributes']['rel'] === 'salmon') {
                    $notify = unamp($link['@attributes']['href']);
                }
                if ($link['@attributes']['rel'] === NAMESPACE_FEED) {
                    $poll = unamp($link['@attributes']['href']);
                }
                if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
                    $hcard = unamp($link['@attributes']['href']);
                }
                if ($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page') {
                    $profile = unamp($link['@attributes']['href']);
                }
                if ($link['@attributes']['rel'] === 'http://portablecontacts.net/spec/1.0') {
                    $poco = unamp($link['@attributes']['href']);
                }
                if ($link['@attributes']['rel'] === 'http://joindiaspora.com/seed_location') {
                    $diaspora_base = unamp($link['@attributes']['href']);
                    $diaspora = true;
                }
                if ($link['@attributes']['rel'] === 'http://joindiaspora.com/guid') {
                    $diaspora_guid = unamp($link['@attributes']['href']);
                    $diaspora = true;
                }
                if ($link['@attributes']['rel'] === 'diaspora-public-key') {
                    $diaspora_key = base64_decode(unamp($link['@attributes']['href']));
                    $pubkey = rsatopem($diaspora_key);
                    $diaspora = true;
                }
            }
            // Status.Net can have more than one profile URL. We need to match the profile URL
            // to a contact on incoming messages to prevent spam, and we won't know which one
            // to match. So in case of two, one of them is stored as an alias. Only store URL's
            // and not webfinger user@host aliases. If they've got more than two non-email style
            // aliases, let's hope we're lucky and get one that matches the feed author-uri because
            // otherwise we're screwed.
            foreach ($links as $link) {
                if ($link['@attributes']['rel'] === 'alias') {
                    if (strpos($link['@attributes']['href'], '@') === false) {
                        if (isset($profile)) {
                            if ($link['@attributes']['href'] !== $profile) {
                                $alias = unamp($link['@attributes']['href']);
                            }
                        } else {
                            $profile = unamp($link['@attributes']['href']);
                        }
                    }
                }
            }
        } elseif ($mode == PROBE_NORMAL) {
            // Check email
            $orig_url = $url;
            if (strpos($orig_url, '@') && validate_email($orig_url)) {
                $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval(local_user()));
                $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval(local_user()));
                if (count($x) && count($r)) {
                    $mailbox = construct_mailbox_name($r[0]);
                    $password = '';
                    openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
                    $mbox = email_connect($mailbox, $r[0]['user'], $password);
                    if (!$mbox) {
                        logger('probe_url: email_connect failed.');
                    }
                    unset($password);
                }
                if ($mbox) {
                    $msgs = email_poll($mbox, $orig_url);
                    logger('probe_url: searching ' . $orig_url . ', ' . count($msgs) . ' messages found.', LOGGER_DEBUG);
                    if (count($msgs)) {
                        $addr = $orig_url;
                        $network = NETWORK_MAIL;
                        $name = substr($url, 0, strpos($url, '@'));
                        $phost = substr($url, strpos($url, '@') + 1);
                        $profile = 'http://' . $phost;
                        // fix nick character range
                        $vcard = array('fn' => $name, 'nick' => $name, 'photo' => avatar_img($url));
                        $notify = 'smtp ' . random_string();
                        $poll = 'email ' . random_string();
                        $priority = 0;
                        $x = email_msg_meta($mbox, $msgs[0]);
                        if (stristr($x->from, $orig_url)) {
                            $adr = imap_rfc822_parse_adrlist($x->from, '');
                        } elseif (stristr($x->to, $orig_url)) {
                            $adr = imap_rfc822_parse_adrlist($x->to, '');
                        }
                        if (isset($adr)) {
                            foreach ($adr as $feadr) {
                                if (strcasecmp($feadr->mailbox, $name) == 0 && strcasecmp($feadr->host, $phost) == 0 && strlen($feadr->personal)) {
                                    $personal = imap_mime_header_decode($feadr->personal);
                                    $vcard['fn'] = "";
                                    foreach ($personal as $perspart) {
                                        if ($perspart->charset != "default") {
                                            $vcard['fn'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
                                        } else {
                                            $vcard['fn'] .= $perspart->text;
                                        }
                                    }
                                    $vcard['fn'] = notags($vcard['fn']);
                                }
                            }
                        }
                    }
                    imap_close($mbox);
                }
            }
        }
    }
    if ($mode == PROBE_NORMAL) {
        if (strlen($zot)) {
            $s = fetch_url($zot);
            if ($s) {
                $j = json_decode($s);
                if ($j) {
                    $network = NETWORK_ZOT;
                    $vcard = array('fn' => $j->fullname, 'nick' => $j->nickname, 'photo' => $j->photo);
                    $profile = $j->url;
                    $notify = $j->post;
                    $pubkey = $j->pubkey;
                    $poll = 'N/A';
                }
            }
        }
        if (strlen($dfrn)) {
            $ret = scrape_dfrn($hcard ? $hcard : $dfrn);
            if (is_array($ret) && x($ret, 'dfrn-request')) {
                $network = NETWORK_DFRN;
                $request = $ret['dfrn-request'];
                $confirm = $ret['dfrn-confirm'];
                $notify = $ret['dfrn-notify'];
                $poll = $ret['dfrn-poll'];
                $vcard = array();
                $vcard['fn'] = $ret['fn'];
                $vcard['nick'] = $ret['nick'];
                $vcard['photo'] = $ret['photo'];
            }
        }
    }
    if ($diaspora && $diaspora_base && $diaspora_guid) {
        if ($mode == PROBE_DIASPORA || !$notify) {
            $notify = $diaspora_base . 'receive/users/' . $diaspora_guid;
            $batch = $diaspora_base . 'receive/public';
        }
        if (strpos($url, '@')) {
            $addr = str_replace('acct:', '', $url);
        }
    }
    if ($network !== NETWORK_ZOT && $network !== NETWORK_DFRN && $network !== NETWORK_MAIL) {
        if ($diaspora) {
            $network = NETWORK_DIASPORA;
        } elseif ($has_lrdd) {
            $network = NETWORK_OSTATUS;
        }
        $priority = 0;
        if ($hcard && !$vcard) {
            $vcard = scrape_vcard($hcard);
            // Google doesn't use absolute url in profile photos
            if (x($vcard, 'photo') && substr($vcard['photo'], 0, 1) == '/') {
                $h = @parse_url($hcard);
                if ($h) {
                    $vcard['photo'] = $h['scheme'] . '://' . $h['host'] . $vcard['photo'];
                }
            }
            logger('probe_url: scrape_vcard: ' . print_r($vcard, true), LOGGER_DATA);
        }
        if ($twitter) {
            logger('twitter: setup');
            $tid = basename($url);
            $tapi = 'https://api.twitter.com/1/statuses/user_timeline.rss';
            if (intval($tid)) {
                $poll = $tapi . '?user_id=' . $tid;
            } else {
                $poll = $tapi . '?screen_name=' . $tid;
            }
            $profile = 'http://twitter.com/#!/' . $tid;
            $vcard['photo'] = 'https://api.twitter.com/1/users/profile_image/' . $tid;
            $vcard['nick'] = $tid;
            $vcard['fn'] = $tid . '@twitter';
        }
        if (!x($vcard, 'fn')) {
            if (x($vcard, 'nick')) {
                $vcard['fn'] = $vcard['nick'];
            }
        }
        $check_feed = false;
        if ($twitter || !$poll) {
            $check_feed = true;
        }
        if (!isset($vcard) || !x($vcard, 'fn') || !$profile) {
            $check_feed = true;
        }
        if ($at_addr && !count($links)) {
            $check_feed = false;
        }
        if ($check_feed) {
            $feedret = scrape_feed($poll ? $poll : $url);
            logger('probe_url: scrape_feed ' . ($poll ? $poll : $url) . ' returns: ' . print_r($feedret, true), LOGGER_DATA);
            if (count($feedret) && ($feedret['feed_atom'] || $feedret['feed_rss'])) {
                $poll = x($feedret, 'feed_atom') ? unamp($feedret['feed_atom']) : unamp($feedret['feed_rss']);
                if (!x($vcard)) {
                    $vcard = array();
                }
            }
            if (x($feedret, 'photo') && !x($vcard, 'photo')) {
                $vcard['photo'] = $feedret['photo'];
            }
            require_once 'library/simplepie/simplepie.inc';
            $feed = new SimplePie();
            $xml = fetch_url($poll);
            logger('probe_url: fetch feed: ' . $poll . ' returns: ' . $xml, LOGGER_DATA);
            $a = get_app();
            logger('probe_url: scrape_feed: headers: ' . $a->get_curl_headers(), LOGGER_DATA);
            $feed->set_raw_data($xml);
            $feed->init();
            if ($feed->error()) {
                logger('probe_url: scrape_feed: Error parsing XML: ' . $feed->error());
            }
            if (!x($vcard, 'photo')) {
                $vcard['photo'] = $feed->get_image_url();
            }
            $author = $feed->get_author();
            if ($author) {
                $vcard['fn'] = unxmlify(trim($author->get_name()));
                if (!$vcard['fn']) {
                    $vcard['fn'] = trim(unxmlify($author->get_email()));
                }
                if (strpos($vcard['fn'], '@') !== false) {
                    $vcard['fn'] = substr($vcard['fn'], 0, strpos($vcard['fn'], '@'));
                }
                $email = unxmlify($author->get_email());
                if (!$profile && $author->get_link()) {
                    $profile = trim(unxmlify($author->get_link()));
                }
                if (!$vcard['photo']) {
                    $rawtags = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
                    if ($rawtags) {
                        $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
                        if (x($elems, 'link') && $elems['link'][0]['attribs']['']['rel'] === 'photo') {
                            $vcard['photo'] = $elems['link'][0]['attribs']['']['href'];
                        }
                    }
                }
            } else {
                $item = $feed->get_item(0);
                if ($item) {
                    $author = $item->get_author();
                    if ($author) {
                        $vcard['fn'] = trim(unxmlify($author->get_name()));
                        if (!$vcard['fn']) {
                            $vcard['fn'] = trim(unxmlify($author->get_email()));
                        }
                        if (strpos($vcard['fn'], '@') !== false) {
                            $vcard['fn'] = substr($vcard['fn'], 0, strpos($vcard['fn'], '@'));
                        }
                        $email = unxmlify($author->get_email());
                        if (!$profile && $author->get_link()) {
                            $profile = trim(unxmlify($author->get_link()));
                        }
                    }
                    if (!$vcard['photo']) {
                        $rawmedia = $item->get_item_tags('http://search.yahoo.com/mrss/', 'thumbnail');
                        if ($rawmedia && $rawmedia[0]['attribs']['']['url']) {
                            $vcard['photo'] = unxmlify($rawmedia[0]['attribs']['']['url']);
                        }
                    }
                    if (!$vcard['photo']) {
                        $rawtags = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
                        if ($rawtags) {
                            $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
                            if (x($elems, 'link') && $elems['link'][0]['attribs']['']['rel'] === 'photo') {
                                $vcard['photo'] = $elems['link'][0]['attribs']['']['href'];
                            }
                        }
                    }
                }
            }
            if (!$vcard['photo'] && strlen($email)) {
                $vcard['photo'] = avatar_img($email);
            }
            if ($poll === $profile) {
                $lnk = $feed->get_permalink();
            }
            if (isset($lnk) && strlen($lnk)) {
                $profile = $lnk;
            }
            if (!x($vcard, 'fn')) {
                $vcard['fn'] = notags($feed->get_title());
            }
            if (!x($vcard, 'fn')) {
                $vcard['fn'] = notags($feed->get_description());
            }
            if (strpos($vcard['fn'], 'Twitter / ') !== false) {
                $vcard['fn'] = substr($vcard['fn'], strpos($vcard['fn'], '/') + 1);
                $vcard['fn'] = trim($vcard['fn']);
            }
            if (!x($vcard, 'nick')) {
                $vcard['nick'] = strtolower(notags(unxmlify($vcard['fn'])));
                if (strpos($vcard['nick'], ' ')) {
                    $vcard['nick'] = trim(substr($vcard['nick'], 0, strpos($vcard['nick'], ' ')));
                }
            }
            if (!$network) {
                $network = NETWORK_FEED;
            }
            if (!$priority) {
                $priority = 2;
            }
        }
    }
    if (!x($vcard, 'photo')) {
        $a = get_app();
        $vcard['photo'] = $a->get_baseurl() . '/images/person-175.jpg';
    }
    if (!$profile) {
        $profile = $url;
    }
    // No human could be associated with this link, use the URL as the contact name
    if ($network === NETWORK_FEED && $poll && !x($vcard, 'fn')) {
        $vcard['fn'] = $url;
    }
    $vcard['fn'] = notags($vcard['fn']);
    $vcard['nick'] = str_replace(' ', '', notags($vcard['nick']));
    $result['name'] = $vcard['fn'];
    $result['nick'] = $vcard['nick'];
    $result['url'] = $profile;
    $result['addr'] = $addr;
    $result['batch'] = $batch;
    $result['notify'] = $notify;
    $result['poll'] = $poll;
    $result['request'] = $request;
    $result['confirm'] = $confirm;
    $result['poco'] = $poco;
    $result['photo'] = $vcard['photo'];
    $result['priority'] = $priority;
    $result['network'] = $network;
    $result['alias'] = $alias;
    $result['pubkey'] = $pubkey;
    logger('probe_url: ' . print_r($result, true), LOGGER_DEBUG);
    return $result;
}
    $feedname = NULL;
}
echo "<div style=\"padding:20px;\">";
echo "Trying to add new feed: " . "<b>" . $feedname . "</b>";
$feed = new SimplePie();
$feed->set_feed_url($feedname);
$feed->set_cache_location(CACHE_DIR);
$feed->init();
$feed->handle_content_type();
//if error found, show error message and stop parsing
if ($feed->error()) {
    echo "<strong>Error! </strong>Unable to process feed: " . $feedname . "<br><br>";
    echo $feed->error();
} else {
    $title = $feed->get_title();
    $feed_desc = $feed->get_description();
    $feedurl = $feed->get_permalink();
    //favicon has been deprecated: $feed->get_favicon();
    $favicon = NULL;
    echo "<table style=\"width: 500px; margin-top:10px;\" class=\"table table-bordered\">";
    echo "<tr><td>Feed url:</td><td>" . $feedurl . "</td></tr>";
    echo "<tr><td>Feed title:</td><td>" . $title . "</td></tr>";
    echo "<tr><td>Feed description:</td><td>" . $feed_desc . "</td></tr>";
    echo "</table>";
    if (empty($title)) {
        echo "<strong style=\"color:red;\"><br>Title is empty, rss feed seems to be invalid!</strong>";
        exit;
    }
    //check if feed_name already exists in database
    $database->query("SELECT feed_name FROM t_feeds WHERE feed_name = :feed_name OR url = :url");
    $database->bind(':feed_name', $title);
Exemple #23
0
 function getFeed(&$params)
 {
     //global $mainframe;
     $slick_rss = array();
     //init feed array
     if (!class_exists('SimplePie')) {
         //include Simple Pie processor class
         require_once JPATH_SITE . DS . 'libraries' . DS . 'simplepie' . DS . 'simplepie.php';
     }
     // check if cache directory exists and is writeable
     $cacheDir = JPATH_BASE . DS . 'cache';
     if (!is_writable($cacheDir)) {
         $slick_rss['error'][] = 'Cache folder is unwriteable. Solution: chmod 777 ' . $cacheDir;
         $cache_exists = false;
     } else {
         $cache_exists = true;
     }
     //get local module parameters from xml file module config settings
     $rssurl = $params->get('rssurl', NULL);
     $rssitems = $params->get('rssitems', 5);
     $rssdesc = $params->get('rssdesc', 1);
     $rssimage = $params->get('rssimage', 1);
     $rssitemtitle_words = $params->get('rssitemtitle_words', 0);
     $rssitemdesc = $params->get('rssitemdesc', 0);
     $rssitemdesc_images = $params->get('rssitemdesc_images', 1);
     $rssitemdesc_words = $params->get('rssitemdesc_words', 0);
     $rsstitle = $params->get('rsstitle', 1);
     $rsscache = $params->get('rsscache', 3600);
     $link_target = $params->get('link_target', 1);
     $no_follow = $params->get('no_follow', 0);
     $enable_tooltip = $params->get('enable_tooltip', 'yes');
     $tooltip_desc_words = $params->get('t_word_count_desc', 25);
     $tooltip_desc_images = $params->get('tooltip_desc_images', 1);
     $tooltip_title_words = $params->get('t_word_count_title', 25);
     if (!$rssurl) {
         $slick_rss['error'][] = 'Invalid feed url. Please enter a valid url in the module settings.';
         return $slick_rss;
         //halt if no valid feed url supplied
     }
     switch ($link_target) {
         //open links in current or new window
         case 1:
             $link_target = '_blank';
             break;
         case 0:
             $link_target = '_self';
             break;
         default:
             $link_target = '_blank';
             break;
     }
     $slick_rss['target'] = $link_target;
     if ($no_follow) {
         $slick_rss['nofollow'] = 'rel="nofollow"';
     }
     //Load and build the feed array
     $feed = new SimplePie();
     $feed->set_feed_url($rssurl);
     //check and set caching
     if ($cache_exists) {
         $feed->set_cache_location($cacheDir);
         $feed->enable_cache();
         $cache_time = intval($rsscache);
         $feed->set_cache_duration($cache_time);
     } else {
         $feed->enable_cache('false');
     }
     $feed->init();
     //process the loaded feed
     $feed->handle_content_type();
     //store any error message
     if (isset($feed->error)) {
         $slick_rss['error'][] = $feed->error;
     }
     //start building the feed meta-info (title, desc and image)
     // feed title
     if ($feed->get_title() && $rsstitle) {
         $slick_rss['title']['link'] = $feed->get_link();
         $slick_rss['title']['title'] = $feed->get_title();
     }
     // feed description
     if ($rssdesc) {
         $slick_rss['description'] = $feed->get_description();
     }
     // feed image
     if ($rssimage && $feed->get_image_url()) {
         $slick_rss['image']['url'] = $feed->get_image_url();
         $slick_rss['image']['title'] = $feed->get_image_title();
     }
     //end feed meta-info
     //start processing feed items
     //if there are items in the feed
     if ($feed->get_item_quantity()) {
         //start looping through the feed items
         $slick_rss_item = 0;
         //item counter for array indexing in the loop
         foreach ($feed->get_items(0, $rssitems) as $currItem) {
             // item title
             $item_title = trim($currItem->get_title());
             // item title word limit check
             if ($rssitemtitle_words) {
                 $item_titles = explode(' ', $item_title);
                 $count = count($item_titles);
                 if ($count > $rssitemtitle_words) {
                     $item_title = '';
                     for ($i = 0; $i < $rssitemtitle_words; $i++) {
                         $item_title .= ' ' . $item_titles[$i];
                     }
                     $item_title .= '...';
                 }
             }
             $slick_rss['items'][$slick_rss_item]['title'] = $item_title;
             // Item Title
             $slick_rss['items'][$slick_rss_item]['link'] = $currItem->get_permalink();
             // item description
             if ($rssitemdesc) {
                 $desc = trim($currItem->get_description());
                 if (!$rssitemdesc_images) {
                     $desc = preg_replace("/<img[^>]+\\>/i", "", $desc);
                     //strip image tags
                 }
                 //item description word limit check
                 if ($rssitemdesc_words) {
                     $texts = explode(' ', $desc);
                     $count = count($texts);
                     if ($count > $rssitemdesc_words) {
                         $desc = '';
                         for ($i = 0; $i < $rssitemdesc_words; $i++) {
                             $desc .= ' ' . $texts[$i];
                             //build words
                         }
                         $desc .= '...';
                     }
                 }
                 $slick_rss['items'][$slick_rss_item]['description'] = $desc;
                 //Item Description
             }
             // tooltip text
             if ($enable_tooltip == 'yes') {
                 //tooltip item title
                 $t_item_title = trim($currItem->get_title());
                 // tooltip title word limit check
                 if ($tooltip_title_words) {
                     $t_item_titles = explode(' ', $t_item_title);
                     $count = count($t_item_titles);
                     if ($count > $tooltip_title_words) {
                         $tooltip_title = '';
                         for ($i = 0; $i < $tooltip_title_words; $i++) {
                             $tooltip_title .= ' ' . $t_item_titles[$i];
                         }
                         $tooltip_title .= '...';
                     } else {
                         $tooltip_title = $t_item_title;
                     }
                 } else {
                     $tooltip_title = $t_item_title;
                 }
                 $tooltip_title = preg_replace("/(\r\n|\n|\r)/", " ", $tooltip_title);
                 //replace new line characters in tooltip title, important!
                 $tooltip_title = htmlspecialchars(html_entity_decode($tooltip_title), ENT_QUOTES);
                 //format text for tooltip
                 $slick_rss['items'][$slick_rss_item]['tooltip']['title'] = $tooltip_title;
                 //Tooltip Title
                 //tooltip item description
                 $text = trim($currItem->get_description());
                 if (!$tooltip_desc_images) {
                     $text = preg_replace("/<img[^>]+\\>/i", "", $text);
                 }
                 // tooltip desc word limit check
                 if ($tooltip_desc_words) {
                     $texts = explode(' ', $text);
                     $count = count($texts);
                     if ($count > $tooltip_desc_words) {
                         $text = '';
                         for ($i = 0; $i < $tooltip_desc_words; $i++) {
                             $text .= ' ' . $texts[$i];
                         }
                         $text .= '...';
                     }
                 }
                 $text = preg_replace("/(\r\n|\n|\r)/", " ", $text);
                 //replace new line characters in tooltip, important!
                 $text = htmlspecialchars(html_entity_decode($text), ENT_QUOTES);
                 //format text for tooltip
                 $slick_rss['items'][$slick_rss_item]['tooltip']['description'] = $text;
                 //Tooltip Body
             } else {
                 $slick_rss['items'][$slick_rss_item]['tooltip'] = array();
                 //blank
             }
             $slick_rss_item++;
             //increment item counter
         }
     }
     //end item quantity check if statement
     //return the feed data structure for the template
     return $slick_rss;
 }
Exemple #24
0
 /**
  * getFeed
  *
  * @param   array  &$params  The module options.
  *
  * @return	void
  */
 public static function getFeed(&$params)
 {
     // Global $mainframe;
     // Init feed array
     $light_rss = array();
     // Get local module parameters from xml file module config settings
     $rssurl = $params->get('rssurl', null);
     $rssitems = $params->get('rssitems', 5);
     $rssdesc = $params->get('rssdesc', 1);
     $rssimage = $params->get('rssimage', 1);
     $rssitemtitle_words = $params->get('rssitemtitle_words', 0);
     $rssitemdesc = $params->get('rssitemdesc', 0);
     $rssitemdesc_images = $params->get('rssitemdesc_images', 1);
     $rssitemdesc_words = $params->get('rssitemdesc_words', 0);
     $rsstitle = $params->get('rsstitle', 1);
     $rsscache = $params->get('rsscache', 3600);
     $link_target = $params->get('link_target', 1);
     $no_follow = $params->get('no_follow', 0);
     $enable_tooltip = $params->get('enable_tooltip', 'yes');
     $tooltip_desc_words = $params->get('t_word_count_desc', 25);
     $tooltip_desc_images = $params->get('tooltip_desc_images', 1);
     $tooltip_title_words = $params->get('t_word_count_title', 25);
     $add_dots = !EParameter::getComponentParam(CAUTOTWEETNG, 'donot_add_dots');
     if (!$rssurl) {
         $light_rss['error'][] = 'Invalid feed url. Please enter a valid url in the module settings.';
         // Halt if no valid feed url supplied
         return $light_rss;
     }
     switch ($link_target) {
         // Open links in current or new window
         case 1:
             $link_target = '_blank';
             break;
         case 0:
             $link_target = '_self';
             break;
         default:
             $link_target = '_blank';
             break;
     }
     $light_rss['target'] = $link_target;
     if ($no_follow) {
         $light_rss['nofollow'] = 'rel="nofollow"';
     }
     if (!class_exists('SimplePie')) {
         // Include Simple Pie processor class
         include_once JPATH_AUTOTWEET . '/libs/SimplePie_autoloader.php';
     }
     // Load and build the feed array
     $feed = new SimplePie();
     $use_sp_cache = EParameter::getComponentParam(CAUTOTWEETNG, 'use_sp_cache', true);
     if ($use_sp_cache && is_writable(JPATH_CACHE)) {
         $feed->set_cache_location(JPATH_CACHE);
         $feed->enable_cache(true);
         $cache_time = intval($rsscache);
         $feed->set_cache_duration($cache_time);
     } else {
         $feed->enable_cache(false);
     }
     $feed->set_feed_url($rssurl);
     // Process the loaded feed
     $feed->init();
     $feed->handle_content_type();
     // Store any error message
     if (isset($feed->error)) {
         $light_rss['error'][] = $feed->error;
     }
     // Start building the feed meta-info (title, desc and image)
     // Feed title
     if ($feed->get_title() && $rsstitle) {
         $light_rss['title']['link'] = $feed->get_link();
         $light_rss['title']['title'] = $feed->get_title();
     }
     // Feed description
     if ($rssdesc) {
         $light_rss['description'] = $feed->get_description();
     }
     // Feed image
     if ($rssimage && $feed->get_image_url()) {
         $light_rss['image']['url'] = $feed->get_image_url();
         $light_rss['image']['title'] = $feed->get_image_title();
     }
     // End feed meta-info
     // Start processing feed items
     // If there are items in the feed
     if ($feed->get_item_quantity()) {
         // Start looping through the feed items
         $light_rss_item = 0;
         // Item counter for array indexing in the loop
         foreach ($feed->get_items(0, $rssitems) as $currItem) {
             // Item title
             $item_title = trim($currItem->get_title());
             // Item title word limit check
             if ($rssitemtitle_words) {
                 $item_titles = explode(' ', $item_title);
                 $count = count($item_titles);
                 if ($count > $rssitemtitle_words) {
                     $item_title = '';
                     for ($i = 0; $i < $rssitemtitle_words; $i++) {
                         $item_title .= ' ' . $item_titles[$i];
                     }
                     if ($add_dots) {
                         $item_title .= '...';
                     }
                 }
             }
             // Item Title
             $light_rss['items'][$light_rss_item]['title'] = $item_title;
             $light_rss['items'][$light_rss_item]['link'] = $currItem->get_permalink();
             // Item description
             if ($rssitemdesc) {
                 $desc = trim($currItem->get_description());
                 if (!$rssitemdesc_images) {
                     // Strip image tags
                     $desc = preg_replace("/<img[^>]+\\>/i", "", $desc);
                 }
                 // Item description word limit check
                 if ($rssitemdesc_words) {
                     $texts = explode(' ', $desc);
                     $count = count($texts);
                     if ($count > $rssitemdesc_words) {
                         $desc = '';
                         for ($i = 0; $i < $rssitemdesc_words; $i++) {
                             // Build words
                             $desc .= ' ' . $texts[$i];
                         }
                         if ($add_dots) {
                             $desc .= '...';
                         }
                     }
                 }
                 // Item Description
                 $light_rss['items'][$light_rss_item]['description'] = $desc;
             }
             // Tooltip text
             if ($enable_tooltip == 'yes') {
                 // Tooltip item title
                 $t_item_title = trim($currItem->get_title());
                 // Tooltip title word limit check
                 if ($tooltip_title_words) {
                     $t_item_titles = explode(' ', $t_item_title);
                     $count = count($t_item_titles);
                     if ($count > $tooltip_title_words) {
                         $tooltip_title = '';
                         for ($i = 0; $i < $tooltip_title_words; $i++) {
                             $tooltip_title .= ' ' . $t_item_titles[$i];
                         }
                         if ($add_dots) {
                             $tooltip_title .= '...';
                         }
                     } else {
                         $tooltip_title = $t_item_title;
                     }
                 } else {
                     $tooltip_title = $t_item_title;
                 }
                 // Replace new line characters in tooltip title, important!
                 $tooltip_title = preg_replace("/(\r\n|\n|\r)/", " ", $tooltip_title);
                 // Format text for tooltip
                 $tooltip_title = htmlspecialchars(html_entity_decode($tooltip_title), ENT_QUOTES);
                 // Tooltip Title
                 $light_rss['items'][$light_rss_item]['tooltip']['title'] = $tooltip_title;
                 // Tooltip item description
                 $text = trim($currItem->get_description());
                 if (!$tooltip_desc_images) {
                     $text = preg_replace("/<img[^>]+\\>/i", "", $text);
                 }
                 // Tooltip desc word limit check
                 if ($tooltip_desc_words) {
                     $texts = explode(' ', $text);
                     $count = count($texts);
                     if ($count > $tooltip_desc_words) {
                         $text = '';
                         for ($i = 0; $i < $tooltip_desc_words; $i++) {
                             $text .= ' ' . $texts[$i];
                         }
                         if ($add_dots) {
                             $text .= '...';
                         }
                     }
                 }
                 // Replace new line characters in tooltip, important!
                 $text = preg_replace("/(\r\n|\n|\r)/", " ", $text);
                 // Format text for tooltip
                 $text = htmlspecialchars(html_entity_decode($text), ENT_QUOTES);
                 // Tooltip Body
                 $light_rss['items'][$light_rss_item]['tooltip']['description'] = $text;
             } else {
                 // Blank
                 $light_rss['items'][$light_rss_item]['tooltip'] = array();
             }
             // Increment item counter
             $light_rss_item++;
         }
     }
     // End item quantity check if statement
     // Return the feed data structure for the template
     return $light_rss;
 }