示例#1
0
 /**
  * Render a newsletter
  * @return string the newsletter.
  */
 public function make()
 {
     $module = Yii::app()->controller->module;
     require_once 'protected/vendors/simplepie/autoloader.php';
     require_once 'protected/vendors/simplepie/idn/idna_convert.class.php';
     $timeLimit = KeyValue::model()->findByPk('newsletter_execution_time')->value;
     $simplePie = new SimplePie();
     $simplePie->set_cache_location('./protected/cache/simplepie');
     $simplePie->set_cache_duration(1);
     // 1 seconde
     // This makes sure that the content is sent to the browser as
     // text/html and the UTF-8 character set (since we didn't change it).
     $simplePie->handle_content_type();
     if ($module->multiLang) {
         if (isset($this->language)) {
             $feeds = $module->feeds[$this->language];
             $renderLanguage = $this->language;
         } else {
             $feeds = $module->feeds[Yii::app()->language];
             $renderLanguage = Yii::app()->language;
         }
     } else {
         $feeds = $module->feeds;
         $renderLanguage = Yii::app()->language;
     }
     $atLeastOne = false;
     for ($i = 0; $i < count($feeds); $i++) {
         if (isset($feeds[$i]['expression'])) {
             $feeds[$i]['content'] = $this->evaluateExpression($feeds[$i]['expression'], array('timeLimit' => $timeLimit, 'language' => $renderLanguage));
             if ($feeds[$i]['content'] != '') {
                 $atLeastOne = true;
             }
         } else {
             $simplePie->set_feed_url($feeds[$i]['url']);
             $simplePie->init();
             $feeds[$i]['link'] = $simplePie->get_permalink();
             $feeds[$i]['items'] = array();
             foreach ($simplePie->get_items(0, $feeds[$i]['limit']) as $item) {
                 if ($item->get_date('U') > strtotime($timeLimit)) {
                     $feeds[$i]['items'][] = $item;
                     $atLeastOne = true;
                 }
             }
         }
     }
     if ($atLeastOne) {
         return Yii::app()->controller->renderPartial('newsletter.components.views.newsletter', array('feeds' => $feeds, 'language' => $renderLanguage), true);
     } else {
         return false;
     }
 }
示例#2
0
 }
 if ($widget->post_date == "yes" || $widget->post_date == "friendly") {
     $post_date = "friendly";
 } elseif ($widget->post_date == "date") {
     $post_date = "date";
 } else {
     $post_date = false;
 }
 $feed = new SimplePie();
 $feed->set_feed_url($feed_url);
 $feed->set_cache_location(WIDGETS_RSS_CACHE_LOCATION);
 $feed->set_cache_duration(WIDGETS_RSS_CACHE_DURATION);
 $feed->init();
 $num_posts_in_feed = $feed->get_item_quantity($rss_count);
 if (($feed_title = $feed->get_title()) && $widget->show_feed_title == "yes") {
     echo "<h3><a href='" . $feed->get_permalink() . "' target='_blank'>" . $feed_title . "</a></h3>";
 }
 $body = "";
 if (empty($num_posts_in_feed)) {
     $body = elgg_echo('notfound');
 } else {
     foreach ($feed->get_items(0, $num_posts_in_feed) as $item) {
         if ($excerpt) {
             $body .= "<div class='widgets_rss_feed_item'>";
             $body .= "<div><a href='" . $item->get_permalink() . "' target='_blank'>" . $item->get_title() . "</a></div>";
             if ($show_item_icon) {
                 if ($enclosures = $item->get_enclosures()) {
                     foreach ($enclosures as $enclosure) {
                         if (substr($enclosure->type, 0, 6) == "image/") {
                             $body .= "<a href='" . $item->get_permalink() . "' target='_blank'><img class='widgets_rss_feed_item_image' src='" . $enclosure->link . "' /></a>";
                             break;
示例#3
0
                if (!isset($person['delete'])) {
                    $newOpml->entries[] = $person;
                }
            } else {
                $newOpml->entries[] = $person;
            }
        }
    }
    // Add feed
    if (isset($_POST['add'])) {
        if ('http://' != $_POST['url']) {
            //autodiscover feed
            $feed = new SimplePie();
            $feed->enable_cache(false);
            $feed->set_feed_url($_POST['url']);
            $feed->init();
            $feed->handle_content_type();
            $person['name'] = $feed->get_title();
            $person['website'] = $feed->get_permalink();
            $person['feed'] = $feed->feed_url;
            $oldOpml->entries[] = $person;
            $newOpml->entries = $oldOpml->entries;
        }
    }
    // Backup old OPML
    OpmlManager::backup(dirname(__FILE__) . '/../custom/people.opml');
    // Save new OPML
    OpmlManager::save($newOpml, dirname(__FILE__) . '/../custom/people.opml');
}
header("Location: index.php");
die;
示例#4
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;
 }
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);
}
示例#6
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;
}
示例#7
0
/**
 * @brief Process atom feed and update anything/everything we might need to update.
 *
 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
 *        might not) try and subscribe to it.
 * $datedir sorts in reverse order
 *
 * @param array $xml
 *   The (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
 * @param $importer
 *   The contact_record (joined to user_record) of the local user who owns this
 *   relationship. It is this person's stuff that is going to be updated.
 * @param $contact
 *   The person who is sending us stuff. If not set, we MAY be processing a "follow" activity
 *   from an external network and MAY create an appropriate contact record. Otherwise, we MUST
 *   have a contact record.
 * @param int $pass by default ($pass = 0) we cannot guarantee that a parent item has been
 *   imported prior to its children being seen in the stream unless we are certain
 *   of how the feed is arranged/ordered.
 *  * With $pass = 1, we only pull parent items out of the stream.
 *  * With $pass = 2, we only pull children (comments/likes).
 *
 * So running this twice, first with pass 1 and then with pass 2 will do the right
 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
 * model where comments can have sub-threads. That would require some massive sorting
 * to get all the feed items into a mostly linear ordering, and might still require
 * recursion.
 */
function consume_feed($xml, $importer, &$contact, $pass = 0)
{
    require_once 'library/simplepie/simplepie.inc';
    if (!strlen($xml)) {
        logger('consume_feed: empty input');
        return;
    }
    $feed = new SimplePie();
    $feed->set_raw_data($xml);
    $feed->init();
    if ($feed->error()) {
        logger('consume_feed: Error parsing XML: ' . $feed->error());
    }
    $permalink = $feed->get_permalink();
    // Check at the feed level for updated contact name and/or photo
    // process any deleted entries
    $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
    if (is_array($del_entries) && count($del_entries) && $pass != 2) {
        foreach ($del_entries as $dentry) {
            $deleted = false;
            if (isset($dentry['attribs']['']['ref'])) {
                $mid = $dentry['attribs']['']['ref'];
                $deleted = true;
                if (isset($dentry['attribs']['']['when'])) {
                    $when = $dentry['attribs']['']['when'];
                    $when = datetime_convert('UTC', 'UTC', $when, 'Y-m-d H:i:s');
                } else {
                    $when = datetime_convert('UTC', 'UTC', 'now', 'Y-m-d H:i:s');
                }
            }
            if ($deleted && is_array($contact)) {
                $r = q("SELECT * from item where mid = '%s' and author_xchan = '%s' and uid = %d limit 1", dbesc(base64url_encode($mid)), dbesc($contact['xchan_hash']), intval($importer['channel_id']));
                if ($r) {
                    $item = $r[0];
                    if (!($item['item_restrict'] & ITEM_DELETED)) {
                        logger('consume_feed: deleting item ' . $item['id'] . ' mid=' . base64url_decode($item['mid']), LOGGER_DEBUG);
                        drop_item($item['id'], false);
                    }
                }
            }
        }
    }
    // Now process the feed
    if ($feed->get_item_quantity()) {
        logger('consume_feed: feed item count = ' . $feed->get_item_quantity(), LOGGER_DEBUG);
        $items = $feed->get_items();
        foreach ($items as $item) {
            $is_reply = false;
            $item_id = base64url_encode($item->get_id());
            logger('consume_feed: processing ' . $item_id, LOGGER_DEBUG);
            $rawthread = $item->get_item_tags(NAMESPACE_THREAD, 'in-reply-to');
            if (isset($rawthread[0]['attribs']['']['ref'])) {
                $is_reply = true;
                $parent_mid = base64url_encode($rawthread[0]['attribs']['']['ref']);
            }
            if ($is_reply) {
                if ($pass == 1) {
                    continue;
                }
                // Have we seen it? If not, import it.
                $item_id = base64url_encode($item->get_id());
                $author = array();
                $datarray = get_atom_elements($feed, $item, $author);
                if (!x($author, 'author_name') || $author['author_is_feed']) {
                    $author['author_name'] = $contact['xchan_name'];
                }
                if (!x($author, 'author_link') || $author['author_is_feed']) {
                    $author['author_link'] = $contact['xchan_url'];
                }
                if (!x($author, 'author_photo') || $author['author_is_feed']) {
                    $author['author_photo'] = $contact['xchan_photo_m'];
                }
                $datarray['author_xchan'] = '';
                if ($author['author_link'] != $contact['xchan_url']) {
                    $x = import_author_unknown(array('name' => $author['author_name'], 'url' => $author['author_link'], 'photo' => array('src' => $author['author_photo'])));
                    if ($x) {
                        $datarray['author_xchan'] = $x;
                    }
                }
                if (!$datarray['author_xchan']) {
                    $datarray['author_xchan'] = $contact['xchan_hash'];
                }
                $datarray['owner_xchan'] = $contact['xchan_hash'];
                $r = q("SELECT edited FROM item WHERE mid = '%s' AND uid = %d LIMIT 1", dbesc($item_id), intval($importer['channel_id']));
                // Update content if 'updated' changes
                if ($r) {
                    if (x($datarray, 'edited') !== false && datetime_convert('UTC', 'UTC', $datarray['edited']) !== $r[0]['edited']) {
                        // do not accept (ignore) an earlier edit than one we currently have.
                        if (datetime_convert('UTC', 'UTC', $datarray['edited']) < $r[0]['edited']) {
                            continue;
                        }
                        update_feed_item($importer['channel_id'], $datarray);
                    }
                    continue;
                }
                $datarray['parent_mid'] = $parent_mid;
                $datarray['uid'] = $importer['channel_id'];
                logger('consume_feed: ' . print_r($datarray, true), LOGGER_DATA);
                $xx = item_store($datarray);
                $r = $xx['item_id'];
                continue;
            } else {
                // Head post of a conversation. Have we seen it? If not, import it.
                $item_id = base64url_encode($item->get_id());
                $author = array();
                $datarray = get_atom_elements($feed, $item, $author);
                if (is_array($contact)) {
                    if (!x($author, 'author_name') || $author['author_is_feed']) {
                        $author['author_name'] = $contact['xchan_name'];
                    }
                    if (!x($author, 'author_link') || $author['author_is_feed']) {
                        $author['author_link'] = $contact['xchan_url'];
                    }
                    if (!x($author, 'author_photo') || $author['author_is_feed']) {
                        $author['author_photo'] = $contact['xchan_photo_m'];
                    }
                }
                if (!x($author, 'author_name') || !x($author, 'author_link')) {
                    logger('consume_feed: no author information! ' . print_r($author, true));
                    continue;
                }
                $datarray['author_xchan'] = '';
                if ($author['author_link'] != $contact['xchan_url']) {
                    $x = import_author_unknown(array('name' => $author['author_name'], 'url' => $author['author_link'], 'photo' => array('src' => $author['author_photo'])));
                    if ($x) {
                        $datarray['author_xchan'] = $x;
                    }
                }
                if (!$datarray['author_xchan']) {
                    $datarray['author_xchan'] = $contact['xchan_hash'];
                }
                $datarray['owner_xchan'] = $contact['xchan_hash'];
                $r = q("SELECT edited FROM item WHERE mid = '%s' AND uid = %d LIMIT 1", dbesc($item_id), intval($importer['channel_id']));
                // Update content if 'updated' changes
                if ($r) {
                    if (x($datarray, 'edited') !== false && datetime_convert('UTC', 'UTC', $datarray['edited']) !== $r[0]['edited']) {
                        // do not accept (ignore) an earlier edit than one we currently have.
                        if (datetime_convert('UTC', 'UTC', $datarray['edited']) < $r[0]['edited']) {
                            continue;
                        }
                        update_feed_item($importer['channel_id'], $datarray);
                    }
                    continue;
                }
                $datarray['parent_mid'] = $item_id;
                $datarray['uid'] = $importer['channel_id'];
                if (!link_compare($author['owner_link'], $contact['xchan_url'])) {
                    logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
                    $author['owner_name'] = $contact['name'];
                    $author['owner_link'] = $contact['url'];
                    $author['owner_avatar'] = $contact['thumb'];
                }
                logger('consume_feed: author ' . print_r($author, true), LOGGER_DEBUG);
                logger('consume_feed: ' . print_r($datarray, true), LOGGER_DATA);
                $xx = item_store($datarray);
                $r = $xx['item_id'];
                continue;
            }
        }
    }
}
示例#8
0
}
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);
    $database->bind(':url', $feedname);
示例#9
0
    $show_author = true;
}
if ($feed_url) {
    $rss_cachetimeout = 3600;
    if (!empty($widget->rss_cachetimeout)) {
        $rss_cachetimeout = sanitise_int($widget->rss_cachetimeout, false);
    }
    elgg_load_library("simplepie");
    $feed = new SimplePie();
    $feed->set_feed_url($feed_url);
    $feed->set_cache_location($cache_location);
    $feed->set_cache_duration($rss_cachetimeout);
    $feed->init();
    if ($show_feed_title) {
        echo "<h3>";
        echo elgg_view("output/url", array("text" => $feed->get_title(), "href" => $feed->get_permalink(), "target" => "_blank"));
        echo "</h3>";
    }
    echo "<ul class='widget-manager-rss-server-result elgg-list'>";
    foreach ($feed->get_items(0, $limit) as $index => $item) {
        echo "<li class='elgg-item'>";
        $title = "";
        $title_text = "";
        $content = "";
        $icon = "";
        if ($show_item_icon) {
            $enclosures = $item->get_enclosures();
            if (!empty($enclosures)) {
                foreach ($enclosures as $enclosure) {
                    if (strpos($enclosure->type, "image/") !== false) {
                        $icon .= elgg_view("output/url", array("text" => elgg_view("output/img", array("src" => $enclosure->link, "alt" => $item->get_title(), "class" => "widgets-rss-server-feed-item-image")), "href" => $item->get_permalink(), "target" => "_blank"));
示例#10
0
     $rss_obj->enable_cache(false);
 }
 // Remove surrounding DIV
 $rss_obj->remove_div(true);
 // Strip all HTML Tags
 $rss_obj->strip_htmltags(true);
 // Limit items
 if ($rssfeed["item"]) {
     $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());
示例#11
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;
}
示例#12
0
文件: content.php 项目: n8b/VMN
    elgg_log("Reading RSS server widget content from cache", "NOTICE");
    $feed_data = @json_decode($raw_feed_data, true);
}
// did we have cached data
if (empty($feed_data)) {
    $limit = (int) $widget->rss_count;
    if ($limit < 1) {
        $limit = 4;
    }
    // read the rss from the source
    $feed = new SimplePie();
    $feed->set_feed_url($feed_url);
    $feed->set_cache_location($cache_location);
    $feed->set_cache_duration($rss_cachetimeout);
    $feed->init();
    $feed_data = array("title_text" => $feed->get_title(), "title_href" => $feed->get_permalink(), "items" => array());
    foreach ($feed->get_items(0, $limit) as $index => $item) {
        $feed_item = array("title" => $item->get_title(), "href" => $item->get_permalink(), "icon" => "", "author" => "", "content" => $item->get_content(), "excerpt" => $item->get_description(), "timestamp" => $item->get_date("U"));
        $enclosures = $item->get_enclosures();
        if (!empty($enclosures)) {
            foreach ($enclosures as $enclosure) {
                if (strpos($enclosure->type, "image/") !== false) {
                    $feed_item["icon_url"] = $enclosure->link;
                    break;
                }
            }
        }
        $authors = $item->get_authors();
        if (!empty($authors)) {
            $author = $authors[0]->name;
            if (empty($author)) {
        echo "</div>";
    }
    echo "</div>\n";
}
?>
		  
    </div>
  </div>
  <div class="c50r">
    <div class="subcr">
<?php 
$feed = new SimplePie();
$feed->set_feed_url('http://www.bewelcome.org/rss/blog/tags/Community%20News%20for%20the%20frontpage');
$feed->init();
$feed->handle_content_type();
$flink = $feed->get_permalink();
echo "<h3><a href=\"", $flink, "\">", $words->get('CommunityNews'), "</a></h3>";
foreach ($feed->get_items(0, 2) as $item) {
    $title = $item->get_title();
    $url = $item->get_permalink();
    $description = $item->get_description();
    $date = $item->get_date('j F Y');
    echo "<h4><a href=\"", $url, "\">", $title, "</a></h4>\n        <p>", $date, "</p>\n        <p>", $description, "</p>\n        \n    ";
}
echo "<a href=\"http://www.bewelcome.org/blog/tags/Community%20News%20for%20the%20frontpage\">", $words->get("getMoreEntriesandComments"), "</a>\n";
?>
	



	 
/**
 * 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;
}
示例#15
0
/**
 * @brief Process atom feed and return the first post and structure
 *
 * @param array $xml
 *   The (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
 * @param $importer
 *   The contact_record (joined to user_record) of the local user who owns this
 *   relationship. It is this person's stuff that is going to be updated.
 */
function process_salmon_feed($xml, $importer)
{
    $ret = array();
    require_once 'library/simplepie/simplepie.inc';
    if (!strlen($xml)) {
        logger('process_feed: empty input');
        return;
    }
    $feed = new SimplePie();
    $feed->set_raw_data($xml);
    $feed->init();
    if ($feed->error()) {
        logger('Error parsing XML: ' . $feed->error());
    }
    $permalink = $feed->get_permalink();
    if ($feed->get_item_quantity()) {
        // this should be exactly one
        logger('feed item count = ' . $feed->get_item_quantity(), LOGGER_DEBUG);
        $items = $feed->get_items();
        foreach ($items as $item) {
            $item_id = base64url_encode($item->get_id());
            logger('processing ' . $item_id, LOGGER_DEBUG);
            $rawthread = $item->get_item_tags(NAMESPACE_THREAD, 'in-reply-to');
            if (isset($rawthread[0]['attribs']['']['ref'])) {
                $is_reply = true;
                $parent_mid = base64url_encode($rawthread[0]['attribs']['']['ref']);
            }
            if ($is_reply) {
                $ret['parent_mid'] = $parent_mid;
            }
            $ret['author'] = array();
            $datarray = get_atom_elements($feed, $item, $ret['author']);
            // reset policies which are restricted by default for RSS connections
            // This item is likely coming from GNU-social via salmon and allows public interaction
            $datarray['public_policy'] = '';
            $datarray['comment_policy'] = '';
            $ret['item'] = $datarray;
        }
    }
    return $ret;
}
示例#16
0
 /**
  * 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);
 }
示例#17
0
/**
 *
 * consume_feed - process atom feed and update anything/everything we might need to update
 *
 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
 *
 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
 *             It is this person's stuff that is going to be updated.
 * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
 *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST
 *             have a contact record.
 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
 *        might not) try and subscribe to it.
 * $datedir sorts in reverse order
 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
 *      imported prior to its children being seen in the stream unless we are certain
 *      of how the feed is arranged/ordered.
 * With $pass = 1, we only pull parent items out of the stream.
 * With $pass = 2, we only pull children (comments/likes).
 *
 * So running this twice, first with pass 1 and then with pass 2 will do the right
 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
 * model where comments can have sub-threads. That would require some massive sorting
 * to get all the feed items into a mostly linear ordering, and might still require
 * recursion.
 */
function consume_feed($xml, $importer, &$contact, &$hub, $datedir = 0, $pass = 0)
{
    if ($contact['network'] === NETWORK_OSTATUS) {
        if ($pass < 2) {
            // Test - remove before flight
            //$tempfile = tempnam(get_temppath(), "ostatus2");
            //file_put_contents($tempfile, $xml);
            logger("Consume OStatus messages ", LOGGER_DEBUG);
            ostatus_import($xml, $importer, $contact, $hub);
        }
        return;
    }
    if ($contact['network'] === NETWORK_FEED) {
        if ($pass < 2) {
            logger("Consume feeds", LOGGER_DEBUG);
            feed_import($xml, $importer, $contact, $hub);
        }
        return;
    }
    require_once 'library/simplepie/simplepie.inc';
    require_once 'include/contact_selectors.php';
    if (!strlen($xml)) {
        logger('consume_feed: empty input');
        return;
    }
    $feed = new SimplePie();
    $feed->set_raw_data($xml);
    if ($datedir) {
        $feed->enable_order_by_date(true);
    } else {
        $feed->enable_order_by_date(false);
    }
    $feed->init();
    if ($feed->error()) {
        logger('consume_feed: Error parsing XML: ' . $feed->error());
    }
    $permalink = $feed->get_permalink();
    // Check at the feed level for updated contact name and/or photo
    $name_updated = '';
    $new_name = '';
    $photo_timestamp = '';
    $photo_url = '';
    $birthday = '';
    $contact_updated = '';
    $hubs = $feed->get_links('hub');
    logger('consume_feed: hubs: ' . print_r($hubs, true), LOGGER_DATA);
    if (count($hubs)) {
        $hub = implode(',', $hubs);
    }
    $rawtags = $feed->get_feed_tags(NAMESPACE_DFRN, 'owner');
    if (!$rawtags) {
        $rawtags = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
    }
    if ($rawtags) {
        $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
        if ($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
            $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
            $new_name = $elems['name'][0]['data'];
            // Manually checking for changed contact names
            if ($new_name != $contact['name'] and $new_name != "" and $name_updated <= $contact['name-date']) {
                $name_updated = date("c");
                $photo_timestamp = date("c");
            }
        }
        if (x($elems, 'link') && $elems['link'][0]['attribs']['']['rel'] === 'photo' && $elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
            if ($photo_timestamp == "") {
                $photo_timestamp = datetime_convert('UTC', 'UTC', $elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
            }
            $photo_url = $elems['link'][0]['attribs']['']['href'];
        }
        if (x($rawtags[0]['child'], NAMESPACE_DFRN) && x($rawtags[0]['child'][NAMESPACE_DFRN], 'birthday')) {
            $birthday = datetime_convert('UTC', 'UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
        }
    }
    if (is_array($contact) && $photo_timestamp && strlen($photo_url) && $photo_timestamp > $contact['avatar-date']) {
        logger('consume_feed: Updating photo for ' . $contact['name'] . ' from ' . $photo_url . ' uid: ' . $contact['uid']);
        $contact_updated = $photo_timestamp;
        require_once "include/Photo.php";
        $photos = import_profile_photo($photo_url, $contact['uid'], $contact['id']);
        q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'\n\t\t\tWHERE `uid` = %d AND `id` = %d AND NOT `self`", dbesc(datetime_convert()), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), intval($contact['uid']), intval($contact['id']));
    }
    if (is_array($contact) && $name_updated && strlen($new_name) && $name_updated > $contact['name-date']) {
        if ($name_updated > $contact_updated) {
            $contact_updated = $name_updated;
        }
        $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1", intval($contact['uid']), intval($contact['id']));
        $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d AND `name` != '%s' AND NOT `self`", dbesc(notags(trim($new_name))), dbesc(datetime_convert()), intval($contact['uid']), intval($contact['id']), dbesc(notags(trim($new_name))));
        // do our best to update the name on content items
        if (count($r) and notags(trim($new_name)) != $r[0]['name']) {
            q("UPDATE `item` SET `author-name` = '%s' WHERE `author-name` = '%s' AND `author-link` = '%s' AND `uid` = %d AND `author-name` != '%s'", dbesc(notags(trim($new_name))), dbesc($r[0]['name']), dbesc($r[0]['url']), intval($contact['uid']), dbesc(notags(trim($new_name))));
        }
    }
    if ($contact_updated and $new_name and $photo_url) {
        poco_check($contact['url'], $new_name, NETWORK_DFRN, $photo_url, "", "", "", "", "", $contact_updated, 2, $contact['id'], $contact['uid']);
    }
    if (strlen($birthday)) {
        if (substr($birthday, 0, 4) != $contact['bdyear']) {
            logger('consume_feed: updating birthday: ' . $birthday);
            /**
             *
             * Add new birthday event for this person
             *
             * $bdtext is just a readable placeholder in case the event is shared
             * with others. We will replace it during presentation to our $importer
             * to contain a sparkle link and perhaps a photo.
             *
             */
            $bdtext = sprintf(t('%s\'s birthday'), $contact['name']);
            $bdtext2 = sprintf(t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
            $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)\n\t\t\t\tVALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ", intval($contact['uid']), intval($contact['id']), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc(datetime_convert('UTC', 'UTC', $birthday)), dbesc(datetime_convert('UTC', 'UTC', $birthday . ' + 1 day ')), dbesc($bdtext), dbesc($bdtext2), dbesc('birthday'));
            // update bdyear
            q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d", dbesc(substr($birthday, 0, 4)), intval($contact['uid']), intval($contact['id']));
            // This function is called twice without reloading the contact
            // Make sure we only create one event. This is why &$contact
            // is a reference var in this function
            $contact['bdyear'] = substr($birthday, 0, 4);
        }
    }
    $community_page = 0;
    $rawtags = $feed->get_feed_tags(NAMESPACE_DFRN, 'community');
    if ($rawtags) {
        $community_page = intval($rawtags[0]['data']);
    }
    if (is_array($contact) && intval($contact['forum']) != $community_page) {
        q("update contact set forum = %d where id = %d", intval($community_page), intval($contact['id']));
        $contact['forum'] = (string) $community_page;
    }
    // process any deleted entries
    $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
    if (is_array($del_entries) && count($del_entries) && $pass != 2) {
        foreach ($del_entries as $dentry) {
            $deleted = false;
            if (isset($dentry['attribs']['']['ref'])) {
                $uri = $dentry['attribs']['']['ref'];
                $deleted = true;
                if (isset($dentry['attribs']['']['when'])) {
                    $when = $dentry['attribs']['']['when'];
                    $when = datetime_convert('UTC', 'UTC', $when, 'Y-m-d H:i:s');
                } else {
                    $when = datetime_convert('UTC', 'UTC', 'now', 'Y-m-d H:i:s');
                }
            }
            if ($deleted && is_array($contact)) {
                $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`\n\t\t\t\t\tWHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1", dbesc($uri), intval($importer['uid']), intval($contact['id']));
                if (count($r)) {
                    $item = $r[0];
                    if (!$item['deleted']) {
                        logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
                    }
                    if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
                        logger("Deleting event " . $item['event-id'], LOGGER_DEBUG);
                        event_delete($item['event-id']);
                    }
                    if ($item['verb'] === ACTIVITY_TAG && $item['object-type'] === ACTIVITY_OBJ_TAGTERM) {
                        $xo = parse_xml_string($item['object'], false);
                        $xt = parse_xml_string($item['target'], false);
                        if ($xt->type === ACTIVITY_OBJ_NOTE) {
                            $i = q("select * from `item` where uri = '%s' and uid = %d limit 1", dbesc($xt->id), intval($importer['importer_uid']));
                            if (count($i)) {
                                // For tags, the owner cannot remove the tag on the author's copy of the post.
                                $owner_remove = $item['contact-id'] == $i[0]['contact-id'] ? true : false;
                                $author_remove = $item['origin'] && $item['self'] ? true : false;
                                $author_copy = $item['origin'] ? true : false;
                                if ($owner_remove && $author_copy) {
                                    continue;
                                }
                                if ($author_remove || $owner_remove) {
                                    $tags = explode(',', $i[0]['tag']);
                                    $newtags = array();
                                    if (count($tags)) {
                                        foreach ($tags as $tag) {
                                            if (trim($tag) !== trim($xo->body)) {
                                                $newtags[] = trim($tag);
                                            }
                                        }
                                    }
                                    q("update item set tag = '%s' where id = %d", dbesc(implode(',', $newtags)), intval($i[0]['id']));
                                    create_tags_from_item($i[0]['id']);
                                }
                            }
                        }
                    }
                    if ($item['uri'] == $item['parent-uri']) {
                        $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',\n\t\t\t\t\t\t\t`body` = '', `title` = ''\n\t\t\t\t\t\t\tWHERE `parent-uri` = '%s' AND `uid` = %d", dbesc($when), dbesc(datetime_convert()), dbesc($item['uri']), intval($importer['uid']));
                        create_tags_from_itemuri($item['uri'], $importer['uid']);
                        create_files_from_itemuri($item['uri'], $importer['uid']);
                        update_thread_uri($item['uri'], $importer['uid']);
                    } else {
                        $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',\n\t\t\t\t\t\t\t`body` = '', `title` = ''\n\t\t\t\t\t\t\tWHERE `uri` = '%s' AND `uid` = %d", dbesc($when), dbesc(datetime_convert()), dbesc($uri), intval($importer['uid']));
                        create_tags_from_itemuri($uri, $importer['uid']);
                        create_files_from_itemuri($uri, $importer['uid']);
                        if ($item['last-child']) {
                            // ensure that last-child is set in case the comment that had it just got wiped.
                            q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ", dbesc(datetime_convert()), dbesc($item['parent-uri']), intval($item['uid']));
                            // who is the last child now?
                            $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d\n\t\t\t\t\t\t\t\tORDER BY `created` DESC LIMIT 1", dbesc($item['parent-uri']), intval($importer['uid']));
                            if (count($r)) {
                                q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d", intval($r[0]['id']));
                            }
                        }
                    }
                }
            }
        }
    }
    // Now process the feed
    if ($feed->get_item_quantity()) {
        logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
        // in inverse date order
        if ($datedir) {
            $items = array_reverse($feed->get_items());
        } else {
            $items = $feed->get_items();
        }
        foreach ($items as $item) {
            $is_reply = false;
            $item_id = $item->get_id();
            $rawthread = $item->get_item_tags(NAMESPACE_THREAD, 'in-reply-to');
            if (isset($rawthread[0]['attribs']['']['ref'])) {
                $is_reply = true;
                $parent_uri = $rawthread[0]['attribs']['']['ref'];
            }
            if ($is_reply && is_array($contact)) {
                if ($pass == 1) {
                    continue;
                }
                // not allowed to post
                if ($contact['rel'] == CONTACT_IS_FOLLOWER) {
                    continue;
                }
                // Have we seen it? If not, import it.
                $item_id = $item->get_id();
                $datarray = get_atom_elements($feed, $item, $contact);
                if (!x($datarray, 'author-name') && $contact['network'] != NETWORK_DFRN) {
                    $datarray['author-name'] = $contact['name'];
                }
                if (!x($datarray, 'author-link') && $contact['network'] != NETWORK_DFRN) {
                    $datarray['author-link'] = $contact['url'];
                }
                if (!x($datarray, 'author-avatar') && $contact['network'] != NETWORK_DFRN) {
                    $datarray['author-avatar'] = $contact['thumb'];
                }
                if (!x($datarray, 'author-name') || !x($datarray, 'author-link')) {
                    logger('consume_feed: no author information! ' . print_r($datarray, true));
                    continue;
                }
                $force_parent = false;
                if ($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'], 'twitter.com')) {
                    if ($contact['network'] === NETWORK_OSTATUS) {
                        $force_parent = true;
                    }
                    if (strlen($datarray['title'])) {
                        unset($datarray['title']);
                    }
                    $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d", dbesc(datetime_convert()), dbesc($parent_uri), intval($importer['uid']));
                    $datarray['last-child'] = 1;
                    update_thread_uri($parent_uri, $importer['uid']);
                }
                $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['uid']));
                // Update content if 'updated' changes
                if (count($r)) {
                    if (edited_timestamp_is_newer($r[0], $datarray)) {
                        // do not accept (ignore) an earlier edit than one we currently have.
                        if (datetime_convert('UTC', 'UTC', $datarray['edited']) < $r[0]['edited']) {
                            continue;
                        }
                        $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d", dbesc($datarray['title']), dbesc($datarray['body']), dbesc($datarray['tag']), dbesc(datetime_convert('UTC', 'UTC', $datarray['edited'])), dbesc(datetime_convert()), dbesc($item_id), intval($importer['uid']));
                        create_tags_from_itemuri($item_id, $importer['uid']);
                        update_thread_uri($item_id, $importer['uid']);
                    }
                    // update last-child if it changes
                    $allow = $item->get_item_tags(NAMESPACE_DFRN, 'comment-allow');
                    if ($allow && $allow[0]['data'] != $r[0]['last-child']) {
                        $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d", dbesc(datetime_convert()), dbesc($parent_uri), intval($importer['uid']));
                        $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d", intval($allow[0]['data']), dbesc(datetime_convert()), dbesc($item_id), intval($importer['uid']));
                        update_thread_uri($item_id, $importer['uid']);
                    }
                    continue;
                }
                if ($contact['network'] === NETWORK_FEED || !strlen($contact['notify'])) {
                    // one way feed - no remote comment ability
                    $datarray['last-child'] = 0;
                }
                $datarray['parent-uri'] = $parent_uri;
                $datarray['uid'] = $importer['uid'];
                $datarray['contact-id'] = $contact['id'];
                if ($datarray['verb'] === ACTIVITY_LIKE || $datarray['verb'] === ACTIVITY_DISLIKE || $datarray['verb'] === ACTIVITY_ATTEND || $datarray['verb'] === ACTIVITY_ATTENDNO || $datarray['verb'] === ACTIVITY_ATTENDMAYBE) {
                    $datarray['type'] = 'activity';
                    $datarray['gravity'] = GRAVITY_LIKE;
                    // only one like or dislike per person
                    // splitted into two queries for performance issues
                    $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`parent-uri` = '%s') limit 1", intval($datarray['uid']), intval($datarray['contact-id']), dbesc($datarray['verb']), dbesc($parent_uri));
                    if ($r && count($r)) {
                        continue;
                    }
                    $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`thr-parent` = '%s') limit 1", intval($datarray['uid']), intval($datarray['contact-id']), dbesc($datarray['verb']), dbesc($parent_uri));
                    if ($r && count($r)) {
                        continue;
                    }
                }
                if ($datarray['verb'] === ACTIVITY_TAG && $datarray['object-type'] === ACTIVITY_OBJ_TAGTERM) {
                    $xo = parse_xml_string($datarray['object'], false);
                    $xt = parse_xml_string($datarray['target'], false);
                    if ($xt->type == ACTIVITY_OBJ_NOTE) {
                        $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1", dbesc($xt->id), intval($importer['importer_uid']));
                        if (!count($r)) {
                            continue;
                        }
                        // extract tag, if not duplicate, add to parent item
                        if ($xo->id && $xo->content) {
                            $newtag = '#[url=' . $xo->id . ']' . $xo->content . '[/url]';
                            if (!stristr($r[0]['tag'], $newtag)) {
                                q("UPDATE item SET tag = '%s' WHERE id = %d", dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag), intval($r[0]['id']));
                                create_tags_from_item($r[0]['id']);
                            }
                        }
                    }
                }
                $r = item_store($datarray, $force_parent);
                continue;
            } else {
                // Head post of a conversation. Have we seen it? If not, import it.
                $item_id = $item->get_id();
                $datarray = get_atom_elements($feed, $item, $contact);
                if (is_array($contact)) {
                    if (!x($datarray, 'author-name') && $contact['network'] != NETWORK_DFRN) {
                        $datarray['author-name'] = $contact['name'];
                    }
                    if (!x($datarray, 'author-link') && $contact['network'] != NETWORK_DFRN) {
                        $datarray['author-link'] = $contact['url'];
                    }
                    if (!x($datarray, 'author-avatar') && $contact['network'] != NETWORK_DFRN) {
                        $datarray['author-avatar'] = $contact['thumb'];
                    }
                }
                if (!x($datarray, 'author-name') || !x($datarray, 'author-link')) {
                    logger('consume_feed: no author information! ' . print_r($datarray, true));
                    continue;
                }
                // special handling for events
                if (x($datarray, 'object-type') && $datarray['object-type'] === ACTIVITY_OBJ_EVENT) {
                    $ev = bbtoevent($datarray['body']);
                    if ((x($ev, 'desc') || x($ev, 'summary')) && x($ev, 'start')) {
                        $ev['uid'] = $importer['uid'];
                        $ev['uri'] = $item_id;
                        $ev['edited'] = $datarray['edited'];
                        $ev['private'] = $datarray['private'];
                        $ev['guid'] = $datarray['guid'];
                        if (is_array($contact)) {
                            $ev['cid'] = $contact['id'];
                        }
                        $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['uid']));
                        if (count($r)) {
                            $ev['id'] = $r[0]['id'];
                        }
                        $xyz = event_store($ev);
                        continue;
                    }
                }
                if ($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'], 'twitter.com')) {
                    if (strlen($datarray['title'])) {
                        unset($datarray['title']);
                    }
                    $datarray['last-child'] = 1;
                }
                $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['uid']));
                // Update content if 'updated' changes
                if (count($r)) {
                    if (edited_timestamp_is_newer($r[0], $datarray)) {
                        // do not accept (ignore) an earlier edit than one we currently have.
                        if (datetime_convert('UTC', 'UTC', $datarray['edited']) < $r[0]['edited']) {
                            continue;
                        }
                        $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d", dbesc($datarray['title']), dbesc($datarray['body']), dbesc($datarray['tag']), dbesc(datetime_convert('UTC', 'UTC', $datarray['edited'])), dbesc(datetime_convert()), dbesc($item_id), intval($importer['uid']));
                        create_tags_from_itemuri($item_id, $importer['uid']);
                        update_thread_uri($item_id, $importer['uid']);
                    }
                    // update last-child if it changes
                    $allow = $item->get_item_tags(NAMESPACE_DFRN, 'comment-allow');
                    if ($allow && $allow[0]['data'] != $r[0]['last-child']) {
                        $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d", intval($allow[0]['data']), dbesc(datetime_convert()), dbesc($item_id), intval($importer['uid']));
                        update_thread_uri($item_id, $importer['uid']);
                    }
                    continue;
                }
                if (activity_match($datarray['verb'], ACTIVITY_FOLLOW)) {
                    logger('consume-feed: New follower');
                    new_follower($importer, $contact, $datarray, $item);
                    return;
                }
                if (activity_match($datarray['verb'], ACTIVITY_UNFOLLOW)) {
                    lose_follower($importer, $contact, $datarray, $item);
                    return;
                }
                if (activity_match($datarray['verb'], ACTIVITY_REQ_FRIEND)) {
                    logger('consume-feed: New friend request');
                    new_follower($importer, $contact, $datarray, $item, true);
                    return;
                }
                if (activity_match($datarray['verb'], ACTIVITY_UNFRIEND)) {
                    lose_sharer($importer, $contact, $datarray, $item);
                    return;
                }
                if (!is_array($contact)) {
                    return;
                }
                if ($contact['network'] === NETWORK_FEED || !strlen($contact['notify'])) {
                    // one way feed - no remote comment ability
                    $datarray['last-child'] = 0;
                }
                if ($contact['network'] === NETWORK_FEED) {
                    $datarray['private'] = 2;
                }
                $datarray['parent-uri'] = $item_id;
                $datarray['uid'] = $importer['uid'];
                $datarray['contact-id'] = $contact['id'];
                if (!link_compare($datarray['owner-link'], $contact['url'])) {
                    // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
                    // but otherwise there's a possible data mixup on the sender's system.
                    // the tgroup delivery code called from item_store will correct it if it's a forum,
                    // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
                    logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
                    $datarray['owner-name'] = $contact['name'];
                    $datarray['owner-link'] = $contact['url'];
                    $datarray['owner-avatar'] = $contact['thumb'];
                }
                // We've allowed "followers" to reach this point so we can decide if they are
                // posting an @-tag delivery, which followers are allowed to do for certain
                // page types. Now that we've parsed the post, let's check if it is legit. Otherwise ignore it.
                if ($contact['rel'] == CONTACT_IS_FOLLOWER && !tgroup_check($importer['uid'], $datarray)) {
                    continue;
                }
                // This is my contact on another system, but it's really me.
                // Turn this into a wall post.
                $notify = item_is_remote_self($contact, $datarray);
                $r = item_store($datarray, false, $notify);
                logger('Stored - Contact ' . $contact['url'] . ' Notify ' . $notify . ' return ' . $r . ' Item ' . print_r($datarray, true), LOGGER_DEBUG);
                continue;
            }
        }
    }
}
示例#18
0
function boucleRSS($texte, $args)
{
    @ini_set('default_socket_timeout', 5);
    // récupération des arguments
    $url = lireTag($args, "url", "string+\\/:.");
    $nb = lireTag($args, "nb", "int");
    $deb = lireTag($args, "deb", "int");
    $i = 0;
    $compt = 0;
    if ($url == "") {
        return;
    }
    $feed = new SimplePie();
    $feed->set_feed_url($url);
    $rss_cache = 'client/cache/rss';
    if (!is_dir($rss_cache)) {
        mkdir($rss_cache);
    }
    $feed->set_cache_location($rss_cache);
    $feed->init();
    $feed->handle_content_type();
    $chantitle = $feed->get_title();
    $chanlink = $feed->get_permalink();
    $res = '';
    foreach ($feed->get_items() as $item) {
        if ($compt < $deb) {
            $compt++;
            continue;
        }
        $link = $item->get_permalink();
        $title = strip_tags($item->get_title());
        $author = strip_tags($item->get_author());
        $description = strip_tags($item->get_description());
        $dateh = $item->get_date('j F Y | g:i a');
        $jour = $item->get_date('j');
        $mois = $item->get_date('F');
        $annee = $item->get_date('Y');
        $heure = $item->get_date('g');
        $minute = $item->get_date('i');
        $seconde = $item->get_date('a');
        $temp = str_replace("#SALON", "{$chantitle}", $texte);
        $temp = str_replace("#WEB", "{$chanlink}", $temp);
        $temp = str_replace("#TITRE", "{$title}", $temp);
        $temp = str_replace("#LIEN", "{$link}", $temp);
        $temp = str_replace("#DESCRIPTION", "{$description}", $temp);
        $temp = str_replace("#AUTEUR", "{$author}", $temp);
        $temp = str_replace("#DATE", "{$jour}/{$mois}/{$annee}", $temp);
        $temp = str_replace("#HEURE", "{$heure}:{$minute} {$seconde}", $temp);
        $i++;
        $res .= $temp;
        if ($i == $nb) {
            return $res;
        }
    }
    return $res;
}
示例#19
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;
}
示例#20
0
/**
 *
 * consume_feed - process atom feed and update anything/everything we might need to update
 *
 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
 *
 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
 *             It is this person's stuff that is going to be updated.
 * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
 *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
 *             have a contact record.
 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
 *        might not) try and subscribe to it.
 * $datedir sorts in reverse order
 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been 
 *      imported prior to its children being seen in the stream unless we are certain
 *      of how the feed is arranged/ordered.
 * With $pass = 1, we only pull parent items out of the stream.
 * With $pass = 2, we only pull children (comments/likes).
 *
 * So running this twice, first with pass 1 and then with pass 2 will do the right
 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
 * model where comments can have sub-threads. That would require some massive sorting
 * to get all the feed items into a mostly linear ordering, and might still require
 * recursion.  
 */
function consume_feed($xml, $importer, &$contact, &$hub, $datedir = 0, $pass = 0)
{
    require_once 'library/simplepie/simplepie.inc';
    if (!strlen($xml)) {
        logger('consume_feed: empty input');
        return;
    }
    $feed = new SimplePie();
    $feed->set_raw_data($xml);
    if ($datedir) {
        $feed->enable_order_by_date(true);
    } else {
        $feed->enable_order_by_date(false);
    }
    $feed->init();
    if ($feed->error()) {
        logger('consume_feed: Error parsing XML: ' . $feed->error());
    }
    $permalink = $feed->get_permalink();
    // Check at the feed level for updated contact name and/or photo
    $name_updated = '';
    $new_name = '';
    $photo_timestamp = '';
    $photo_url = '';
    $birthday = '';
    $hubs = $feed->get_links('hub');
    if (count($hubs)) {
        $hub = implode(',', $hubs);
    }
    $rawtags = $feed->get_feed_tags(NAMESPACE_DFRN, 'owner');
    if (!$rawtags) {
        $rawtags = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
    }
    if ($rawtags) {
        $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
        if ($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
            $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
            $new_name = $elems['name'][0]['data'];
        }
        if (x($elems, 'link') && $elems['link'][0]['attribs']['']['rel'] === 'photo' && $elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
            $photo_timestamp = datetime_convert('UTC', 'UTC', $elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
            $photo_url = $elems['link'][0]['attribs']['']['href'];
        }
        if (x($rawtags[0]['child'], NAMESPACE_DFRN) && x($rawtags[0]['child'][NAMESPACE_DFRN], 'birthday')) {
            $birthday = datetime_convert('UTC', 'UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
        }
    }
    if (is_array($contact) && $photo_timestamp && strlen($photo_url) && $photo_timestamp > $contact['avatar-date']) {
        logger('consume_feed: Updating photo for ' . $contact['name']);
        require_once "Photo.php";
        $photo_failure = false;
        $have_photo = false;
        $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1", intval($contact['id']), intval($contact['uid']));
        if (count($r)) {
            $resource_id = $r[0]['resource-id'];
            $have_photo = true;
        } else {
            $resource_id = photo_new_resource();
        }
        $img_str = fetch_url($photo_url, true);
        $img = new Photo($img_str);
        if ($img->is_valid()) {
            if ($have_photo) {
                q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d", dbesc($resource_id), intval($contact['id']), intval($contact['uid']));
            }
            $img->scaleImageSquare(175);
            $hash = $resource_id;
            $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
            $img->scaleImage(80);
            $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
            $img->scaleImage(48);
            $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
            $a = get_app();
            q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  \n\t\t\t\tWHERE `uid` = %d AND `id` = %d LIMIT 1", dbesc(datetime_convert()), dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'), dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'), dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'), intval($contact['uid']), intval($contact['id']));
        }
    }
    if (is_array($contact) && $name_updated && strlen($new_name) && $name_updated > $contact['name-date']) {
        $r = q("select * from contact where uid = %d and id = %d limit 1", intval($contact['uid']), intval($contact['id']));
        $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1", dbesc(notags(trim($new_name))), dbesc(datetime_convert()), intval($contact['uid']), intval($contact['id']));
        // do our best to update the name on content items
        if (count($r)) {
            q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d", dbesc(notags(trim($new_name))), dbesc($r[0]['name']), dbesc($r[0]['url']), intval($contact['uid']));
        }
    }
    if (strlen($birthday)) {
        if (substr($birthday, 0, 4) != $contact['bdyear']) {
            logger('consume_feed: updating birthday: ' . $birthday);
            /**
             *
             * Add new birthday event for this person
             *
             * $bdtext is just a readable placeholder in case the event is shared
             * with others. We will replace it during presentation to our $importer
             * to contain a sparkle link and perhaps a photo. 
             *
             */
            $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
            $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)\n\t\t\t\tVALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ", intval($contact['uid']), intval($contact['id']), dbesc(datetime_convert()), dbesc(datetime_convert()), dbesc(datetime_convert('UTC', 'UTC', $birthday)), dbesc(datetime_convert('UTC', 'UTC', $birthday . ' + 1 day ')), dbesc($bdtext), dbesc('birthday'));
            // update bdyear
            q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1", dbesc(substr($birthday, 0, 4)), intval($contact['uid']), intval($contact['id']));
            // This function is called twice without reloading the contact
            // Make sure we only create one event. This is why &$contact
            // is a reference var in this function
            $contact['bdyear'] = substr($birthday, 0, 4);
        }
    }
    $community_page = 0;
    $rawtags = $feed->get_feed_tags(NAMESPACE_DFRN, 'community');
    if ($rawtags) {
        $community_page = intval($rawtags[0]['data']);
    }
    if (is_array($contact) && intval($contact['forum']) != $community_page) {
        q("update contact set forum = %d where id = %d limit 1", intval($community_page), intval($contact['id']));
        $contact['forum'] = (string) $community_page;
    }
    // process any deleted entries
    $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
    if (is_array($del_entries) && count($del_entries) && $pass != 2) {
        foreach ($del_entries as $dentry) {
            $deleted = false;
            if (isset($dentry['attribs']['']['ref'])) {
                $uri = $dentry['attribs']['']['ref'];
                $deleted = true;
                if (isset($dentry['attribs']['']['when'])) {
                    $when = $dentry['attribs']['']['when'];
                    $when = datetime_convert('UTC', 'UTC', $when, 'Y-m-d H:i:s');
                } else {
                    $when = datetime_convert('UTC', 'UTC', 'now', 'Y-m-d H:i:s');
                }
            }
            if ($deleted && is_array($contact)) {
                $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id` \n\t\t\t\t\tWHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1", dbesc($uri), intval($importer['uid']), intval($contact['id']));
                if (count($r)) {
                    $item = $r[0];
                    if (!$item['deleted']) {
                        logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
                    }
                    if ($item['verb'] === ACTIVITY_TAG && $item['object-type'] === ACTIVITY_OBJ_TAGTERM) {
                        $xo = parse_xml_string($item['object'], false);
                        $xt = parse_xml_string($item['target'], false);
                        if ($xt->type === ACTIVITY_OBJ_NOTE) {
                            $i = q("select * from `item` where uri = '%s' and uid = %d limit 1", dbesc($xt->id), intval($importer['importer_uid']));
                            if (count($i)) {
                                // For tags, the owner cannot remove the tag on the author's copy of the post.
                                $owner_remove = $item['contact-id'] == $i[0]['contact-id'] ? true : false;
                                $author_remove = $item['origin'] && $item['self'] ? true : false;
                                $author_copy = $item['origin'] ? true : false;
                                if ($owner_remove && $author_copy) {
                                    continue;
                                }
                                if ($author_remove || $owner_remove) {
                                    $tags = explode(',', $i[0]['tag']);
                                    $newtags = array();
                                    if (count($tags)) {
                                        foreach ($tags as $tag) {
                                            if (trim($tag) !== trim($xo->body)) {
                                                $newtags[] = trim($tag);
                                            }
                                        }
                                    }
                                    q("update item set tag = '%s' where id = %d limit 1", dbesc(implode(',', $newtags)), intval($i[0]['id']));
                                }
                            }
                        }
                    }
                    if ($item['uri'] == $item['parent-uri']) {
                        $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',\n\t\t\t\t\t\t\t`body` = '', `title` = ''\n\t\t\t\t\t\t\tWHERE `parent-uri` = '%s' AND `uid` = %d", dbesc($when), dbesc(datetime_convert()), dbesc($item['uri']), intval($importer['uid']));
                    } else {
                        $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',\n\t\t\t\t\t\t\t`body` = '', `title` = '' \n\t\t\t\t\t\t\tWHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($when), dbesc(datetime_convert()), dbesc($uri), intval($importer['uid']));
                        if ($item['last-child']) {
                            // ensure that last-child is set in case the comment that had it just got wiped.
                            q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ", dbesc(datetime_convert()), dbesc($item['parent-uri']), intval($item['uid']));
                            // who is the last child now?
                            $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d \n\t\t\t\t\t\t\t\tORDER BY `created` DESC LIMIT 1", dbesc($item['parent-uri']), intval($importer['uid']));
                            if (count($r)) {
                                q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1", intval($r[0]['id']));
                            }
                        }
                    }
                }
            }
        }
    }
    // Now process the feed
    if ($feed->get_item_quantity()) {
        logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
        // in inverse date order
        if ($datedir) {
            $items = array_reverse($feed->get_items());
        } else {
            $items = $feed->get_items();
        }
        foreach ($items as $item) {
            $is_reply = false;
            $item_id = $item->get_id();
            $rawthread = $item->get_item_tags(NAMESPACE_THREAD, 'in-reply-to');
            if (isset($rawthread[0]['attribs']['']['ref'])) {
                $is_reply = true;
                $parent_uri = $rawthread[0]['attribs']['']['ref'];
            }
            if ($is_reply && is_array($contact)) {
                if ($pass == 1) {
                    continue;
                }
                // Have we seen it? If not, import it.
                $item_id = $item->get_id();
                $datarray = get_atom_elements($feed, $item);
                if (!x($datarray, 'author-name') && $contact['network'] != NETWORK_DFRN) {
                    $datarray['author-name'] = $contact['name'];
                }
                if (!x($datarray, 'author-link') && $contact['network'] != NETWORK_DFRN) {
                    $datarray['author-link'] = $contact['url'];
                }
                if (!x($datarray, 'author-avatar') && $contact['network'] != NETWORK_DFRN) {
                    $datarray['author-avatar'] = $contact['thumb'];
                }
                if (!x($datarray, 'author-name') || !x($datarray, 'author-link')) {
                    logger('consume_feed: no author information! ' . print_r($datarray, true));
                    continue;
                }
                $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['uid']));
                // Update content if 'updated' changes
                if (count($r)) {
                    if (x($datarray, 'edited') !== false && datetime_convert('UTC', 'UTC', $datarray['edited']) !== $r[0]['edited']) {
                        $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($datarray['title']), dbesc($datarray['body']), dbesc($datarray['tag']), dbesc(datetime_convert('UTC', 'UTC', $datarray['edited'])), dbesc($item_id), intval($importer['uid']));
                    }
                    // update last-child if it changes
                    $allow = $item->get_item_tags(NAMESPACE_DFRN, 'comment-allow');
                    if ($allow && $allow[0]['data'] != $r[0]['last-child']) {
                        $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d", dbesc(datetime_convert()), dbesc($parent_uri), intval($importer['uid']));
                        $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", intval($allow[0]['data']), dbesc(datetime_convert()), dbesc($item_id), intval($importer['uid']));
                    }
                    continue;
                }
                $force_parent = false;
                if ($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'], 'twitter.com')) {
                    if ($contact['network'] === NETWORK_OSTATUS) {
                        $force_parent = true;
                    }
                    if (strlen($datarray['title'])) {
                        unset($datarray['title']);
                    }
                    $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d", dbesc(datetime_convert()), dbesc($parent_uri), intval($importer['uid']));
                    $datarray['last-child'] = 1;
                }
                if ($contact['network'] === NETWORK_FEED || !strlen($contact['notify'])) {
                    // one way feed - no remote comment ability
                    $datarray['last-child'] = 0;
                }
                $datarray['parent-uri'] = $parent_uri;
                $datarray['uid'] = $importer['uid'];
                $datarray['contact-id'] = $contact['id'];
                if (activity_match($datarray['verb'], ACTIVITY_LIKE) || activity_match($datarray['verb'], ACTIVITY_DISLIKE)) {
                    $datarray['type'] = 'activity';
                    $datarray['gravity'] = GRAVITY_LIKE;
                    // only one like or dislike per person
                    $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1", intval($datarray['uid']), intval($datarray['contact-id']), dbesc($datarray['verb']));
                    if ($r && count($r)) {
                        continue;
                    }
                }
                if ($datarray['verb'] === ACTIVITY_TAG && $datarray['object-type'] === ACTIVITY_OBJ_TAGTERM) {
                    $xo = parse_xml_string($datarray['object'], false);
                    $xt = parse_xml_string($datarray['target'], false);
                    if ($xt->type == ACTIVITY_OBJ_NOTE) {
                        $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1", dbesc($xt->id), intval($importer['importer_uid']));
                        if (!count($r)) {
                            continue;
                        }
                        // extract tag, if not duplicate, add to parent item
                        if ($xo->id && $xo->content) {
                            $newtag = '#[url=' . $xo->id . ']' . $xo->content . '[/url]';
                            if (!stristr($r[0]['tag'], $newtag)) {
                                q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1", dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag), intval($r[0]['id']));
                            }
                        }
                    }
                }
                $r = item_store($datarray, $force_parent);
                continue;
            } else {
                // Head post of a conversation. Have we seen it? If not, import it.
                $item_id = $item->get_id();
                $datarray = get_atom_elements($feed, $item);
                if (is_array($contact)) {
                    if (!x($datarray, 'author-name') && $contact['network'] != NETWORK_DFRN) {
                        $datarray['author-name'] = $contact['name'];
                    }
                    if (!x($datarray, 'author-link') && $contact['network'] != NETWORK_DFRN) {
                        $datarray['author-link'] = $contact['url'];
                    }
                    if (!x($datarray, 'author-avatar') && $contact['network'] != NETWORK_DFRN) {
                        $datarray['author-avatar'] = $contact['thumb'];
                    }
                }
                if (!x($datarray, 'author-name') || !x($datarray, 'author-link')) {
                    logger('consume_feed: no author information! ' . print_r($datarray, true));
                    continue;
                }
                // special handling for events
                if (x($datarray, 'object-type') && $datarray['object-type'] === ACTIVITY_OBJ_EVENT) {
                    $ev = bbtoevent($datarray['body']);
                    if (x($ev, 'desc') && x($ev, 'start')) {
                        $ev['uid'] = $importer['uid'];
                        $ev['uri'] = $item_id;
                        $ev['edited'] = $datarray['edited'];
                        $ev['private'] = $datarray['private'];
                        if (is_array($contact)) {
                            $ev['cid'] = $contact['id'];
                        }
                        $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['uid']));
                        if (count($r)) {
                            $ev['id'] = $r[0]['id'];
                        }
                        $xyz = event_store($ev);
                        continue;
                    }
                }
                $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['uid']));
                // Update content if 'updated' changes
                if (count($r)) {
                    if (x($datarray, 'edited') !== false && datetime_convert('UTC', 'UTC', $datarray['edited']) !== $r[0]['edited']) {
                        $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($datarray['title']), dbesc($datarray['body']), dbesc($datarray['tag']), dbesc(datetime_convert('UTC', 'UTC', $datarray['edited'])), dbesc($item_id), intval($importer['uid']));
                    }
                    // update last-child if it changes
                    $allow = $item->get_item_tags(NAMESPACE_DFRN, 'comment-allow');
                    if ($allow && $allow[0]['data'] != $r[0]['last-child']) {
                        $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", intval($allow[0]['data']), dbesc(datetime_convert()), dbesc($item_id), intval($importer['uid']));
                    }
                    continue;
                }
                if (activity_match($datarray['verb'], ACTIVITY_FOLLOW)) {
                    logger('consume-feed: New follower');
                    new_follower($importer, $contact, $datarray, $item);
                    return;
                }
                if (activity_match($datarray['verb'], ACTIVITY_UNFOLLOW)) {
                    lose_follower($importer, $contact, $datarray, $item);
                    return;
                }
                if (activity_match($datarray['verb'], ACTIVITY_REQ_FRIEND)) {
                    logger('consume-feed: New friend request');
                    new_follower($importer, $contact, $datarray, $item, true);
                    return;
                }
                if (activity_match($datarray['verb'], ACTIVITY_UNFRIEND)) {
                    lose_sharer($importer, $contact, $datarray, $item);
                    return;
                }
                if (!is_array($contact)) {
                    return;
                }
                if ($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'], 'twitter.com')) {
                    if (strlen($datarray['title'])) {
                        unset($datarray['title']);
                    }
                    $datarray['last-child'] = 1;
                }
                if ($contact['network'] === NETWORK_FEED || !strlen($contact['notify'])) {
                    // one way feed - no remote comment ability
                    $datarray['last-child'] = 0;
                }
                // This is my contact on another system, but it's really me.
                // Turn this into a wall post.
                if ($contact['remote_self']) {
                    $datarray['wall'] = 1;
                }
                $datarray['parent-uri'] = $item_id;
                $datarray['uid'] = $importer['uid'];
                $datarray['contact-id'] = $contact['id'];
                if (!link_compare($datarray['owner-link'], $contact['url'])) {
                    // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
                    // but otherwise there's a possible data mixup on the sender's system.
                    // the tgroup delivery code called from item_store will correct it if it's a forum,
                    // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
                    logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
                    $datarray['owner-name'] = $contact['name'];
                    $datarray['owner-link'] = $contact['url'];
                    $datarray['owner-avatar'] = $contact['thumb'];
                }
                $r = item_store($datarray);
                continue;
            }
        }
    }
}
示例#21
0
    $post_date = $vars['entity']->post_date;
    $cache_loc = $CONFIG->pluginspath . '/simplepie/cache';
    $feed = new SimplePie($feed_url, $cache_loc);
    // doubles timeout if going through a proxy
    //$feed->set_timeout(20);
    $num_posts_in_feed = $feed->get_item_quantity();
    // only display errors to profile owner
    if (get_loggedin_userid() == page_owner()) {
        if (!$num_posts_in_feed) {
            echo '<p>' . elgg_echo('simplepie:notfind') . '</p>';
        }
    }
    ?>
  <div class="simplepie_blog_title">
    <h2><a href="<?php 
    echo $feed->get_permalink();
    ?>
"><?php 
    echo $feed->get_title();
    ?>
</a></h2>
  </div>
<?php 
    if ($num_items > $num_posts_in_feed) {
        $num_items = $num_posts_in_feed;
    }
    foreach ($feed->get_items(0, $num_items) as $item) {
        ?>
 
		<div class="simplepie_item">
		  <div class="simplepie_title">
 public function __construct($data, $boxname = "")
 {
     $this->spnrbData['templatename'] = "simplePieNewsreaderBox";
     $this->getBoxStatus($data);
     $this->spnrbData['boxID'] = $data['boxID'];
     if (SPNRBOX_BOXOPENED == true) {
         $this->spnrbData['Status'] = 1;
     }
     if (WBBCore::getUser()->getPermission('user.board.canViewSimplePieNewsreaderBox')) {
         require_once WBB_DIR . 'lib/data/boxes/SimplePieNewsReader/simplepie.inc';
         require_once WBB_DIR . 'lib/data/boxes/SimplePieNewsReader/idna_convert.class.php';
         // FILTER?
         if (SPNRBOX_FILTER && strlen(SPNRBOX_FILTERWORDS) >= 3) {
             require_once WBB_DIR . 'lib/data/boxes/SimplePieNewsReader/simplepie_filter.php';
             $feed = new SimplePie_Filter();
             if (!defined('SPNRBOX_FILTERCLASS')) {
                 define('SPNRBOX_FILTERCLASS', 'hightlight');
             }
             define('SPNRBOX_FILTERON', 1);
         } else {
             $feed = new SimplePie();
             define('SPNRBOX_FILTERON', 0);
         }
         // CACHE
         if (SPNRBOX_CACHEMAX != 0 && SPNRBOX_CACHEMIN != 0) {
             $feed->set_autodiscovery_cache_duration(SPNRBOX_CACHEMAX);
             $feed->set_cache_duration(SPNRBOX_CACHEMIN);
         } else {
             $feed->set_autodiscovery_cache_duration(9999999999);
             $feed->set_cache_duration(9999999999);
         }
         // CHARSET
         if (!defined('CHARSET')) {
             define('CHARSET', 'UTF-8');
         }
         if (!defined('SPNRBOX_CHARSET')) {
             define('SPNRBOX_CHARSET', 'UTF-8');
         }
         if (SPNRBOX_CHARSET == 'default') {
             $charset = CHARSET;
         } else {
             $charset = SPNRBOX_CHARSET;
         }
         $feed->set_cache_location(WBB_DIR . 'lib/data/boxes/SimplePieNewsReader/cache');
         $feed->set_favicon_handler(RELATIVE_WBB_DIR . 'lib/data/boxes/SimplePieNewsReader/handler_image.php');
         $feed->set_image_handler(RELATIVE_WBB_DIR . 'lib/data/boxes/SimplePieNewsReader/handler_image.php');
         $feed->set_output_encoding($charset);
         // BOOKMARKS
         $bookmarks = array();
         if (SPNRBOX_SHOWSOCIALBOOKMARKS) {
             $socialBookmarks = preg_split("/\r?\n/", SPNRBOX_SOCIALBOOKMARKS);
             $cntBookmark = 0;
             foreach ($socialBookmarks as $row) {
                 $row = trim($row);
                 if (preg_match("/\\|/", $row)) {
                     list($bookmarkTitle, $bookmarkUrl, $bookmarkImg, $bookmarkEncodeTitle, $bookmarkEncodeUrl) = preg_split("/\\|/", $row, 5);
                     $bookmarkTitle = trim($bookmarkTitle);
                     $bookmarkUrl = trim($bookmarkUrl);
                     $bookmarkImg = trim($bookmarkImg);
                     $bookmarkEncodeTitle = trim($bookmarkEncodeTitle);
                     $bookmarkEncodeUrl = trim($bookmarkEncodeUrl);
                     if (!empty($bookmarkTitle) && !empty($bookmarkUrl) && !empty($bookmarkImg) && isset($bookmarkEncodeTitle) && isset($bookmarkEncodeUrl)) {
                         $bookmarks[$cntBookmark]['bookmarkTitle'] = $bookmarkTitle;
                         $bookmarks[$cntBookmark]['bookmarkUrl'] = $bookmarkUrl;
                         $bookmarks[$cntBookmark]['bookmarkImg'] = $bookmarkImg;
                         $bookmarks[$cntBookmark]['bookmarkEncodeTitle'] = $bookmarkEncodeTitle == 1 ? 1 : 0;
                         $bookmarks[$cntBookmark]['bookmarkEncodeUrl'] = $bookmarkEncodeUrl == 1 ? 1 : 0;
                         $cntBookmark++;
                     }
                 }
             }
         }
         // THEMA ZUM FEED
         if (WCF::getUser()->getPermission('user.board.canViewThreadToFeed') && SPNRBOX_FEEDTOTHREAD) {
             require_once WBB_DIR . 'lib/data/board/Board.class.php';
             $accessibleBoards = explode(',', Board::getAccessibleBoards());
             $selectiveBoards = explode(',', SPNRBOX_FEEDTOTHREADBOARDID);
             $boardStructur = WCF::getCache()->get('board', 'boardStructure');
             if (count($selectiveBoards) != 0) {
                 $this->spnrbData['boardsForm'] = count($selectiveBoards) == 1 ? 'button' : 'list';
                 $cntBoards = 0;
                 $prefix = '';
                 foreach ($selectiveBoards as $k => $v) {
                     $tmp = Board::getBoard($v);
                     if ($tmp->boardType < 2 && in_array($v, $accessibleBoards)) {
                         $this->spnrbData['boards'][$cntBoards]['id'] = $tmp->boardID;
                         $this->spnrbData['boards'][$cntBoards]['type'] = $tmp->boardType;
                         $prefix = '';
                         foreach ($boardStructur as $boardDepth => $boardKey) {
                             if (in_array($this->spnrbData['boards'][$cntBoards]['id'], $boardKey)) {
                                 $prefix = str_repeat('--', $boardDepth);
                                 break;
                             }
                         }
                         $this->spnrbData['boards'][$cntBoards]['title'] = ($prefix != '' ? $prefix : '') . ' ' . $tmp->title;
                         $cntBoards++;
                     }
                 }
             } else {
                 $this->spnrbData['boardsForm'] = '';
             }
         }
         $feedUrls = preg_split('/\\r?\\n/', SPNRBOX_FEEDS);
         $cntFeedUrl = 0;
         foreach ($feedUrls as $k => $feedurl) {
             $feedurl = trim($feedurl);
             if (empty($feedurl)) {
                 continue;
             }
             $feed->set_feed_url($feedurl);
             $feed->init();
             $feed->handle_content_type();
             if (SPNRBOX_FILTERON) {
                 $feed->set_filter(SPNRBOX_FILTERWORDS, SPNRBOX_FILTERMODE);
             }
             if (!($favicon = $feed->get_favicon())) {
                 $favicon = RELATIVE_WBB_DIR . 'icon/alternate_favicon.png';
             }
             $this->spnrbData['spnrFeeds'][$cntFeedUrl]['id'] = $cntFeedUrl;
             $this->spnrbData['spnrFeeds'][$cntFeedUrl]['link'] = $feed->get_permalink();
             $this->spnrbData['spnrFeeds'][$cntFeedUrl]['title'] = $feed->get_title();
             $this->spnrbData['spnrFeeds'][$cntFeedUrl]['favicon'] = $favicon;
             $this->spnrbData['spnrFeeds'][$cntFeedUrl]['xml'] = $feedurl;
             $items = $feed->get_items();
             if (SPNRBOX_FILTERON) {
                 $items = $feed->filter($items);
             }
             $i = 0;
             foreach ($items as $item) {
                 if ($i >= SPNRBOX_NUMOFFEEDS) {
                     break;
                 }
                 $iFeed = $item->get_feed();
                 $this->spnrbData['spnrFeeds'][$cntFeedUrl]['iFeed'][$i]['id'] = $i;
                 $this->spnrbData['spnrFeeds'][$cntFeedUrl]['iFeed'][$i]['link'] = $item->get_permalink();
                 $this->spnrbData['spnrFeeds'][$cntFeedUrl]['iFeed'][$i]['title'] = html_entity_decode($item->get_title(), ENT_QUOTES, $charset);
                 $this->spnrbData['spnrFeeds'][$cntFeedUrl]['iFeed'][$i]['content'] = SPNRBOX_FILTERON ? $this->highlight(SPNRBOX_FILTERWORDS, $item->get_content(), SPNRBOX_FILTERCLASS) : $item->get_content();
                 $this->spnrbData['spnrFeeds'][$cntFeedUrl]['iFeed'][$i]['date'] = $item->get_date('d.m.Y - H:i:s');
                 $this->spnrbData['spnrFeeds'][$cntFeedUrl]['iFeed'][$i]['bookmarks'] = array();
                 if (count($bookmarks)) {
                     $x = 0;
                     foreach ($bookmarks as $bookmark) {
                         $search[0] = "/\\{TITLE\\}/";
                         $search[1] = "/\\{URL\\}/";
                         $replace[0] = $bookmark['bookmarkEncodeTitle'] == 1 ? rawurlencode(html_entity_decode($item->get_title(), ENT_QUOTES, $charset)) : html_entity_decode($item->get_title());
                         $replace[1] = $bookmark['bookmarkEncodeUrl'] == 1 ? rawurlencode(html_entity_decode($item->get_permalink(), ENT_QUOTES, $charset)) : html_entity_decode($item->get_permalink());
                         $this->spnrbData['spnrFeeds'][$cntFeedUrl]['iFeed'][$i]['bookmarks'][$x]['bookmarkTitle'] = htmlspecialchars($bookmark['bookmarkTitle']);
                         $this->spnrbData['spnrFeeds'][$cntFeedUrl]['iFeed'][$i]['bookmarks'][$x]['bookmarkUrl'] = preg_replace($search, $replace, html_entity_decode($bookmark['bookmarkUrl']));
                         $this->spnrbData['spnrFeeds'][$cntFeedUrl]['iFeed'][$i]['bookmarks'][$x]['bookmarkImg'] = RELATIVE_WBB_DIR . "icon/" . $bookmark['bookmarkImg'];
                         $x++;
                     }
                 }
                 if ($enclosure = $item->get_enclosure()) {
                     $this->spnrbData['spnrFeeds'][$cntFeedUrl]['iFeed'][$i]['enclosure'] = '<p>' . $enclosure->native_embed(array('audio' => RELATIVE_WBB_DIR . 'icon/place_audio.png', 'video' => RELATIVE_WBB_DIR . 'icon/place_video.png', 'mediaplayer' => RELATIVE_WBB_DIR . 'icon/mediaplayer.swf', 'alt' => '<img src="' . RELATIVE_WBB_DIR . 'icon/mini_podcast.png" class="download" border="0" title="Download Podcast (' . $enclosure->get_extension() . '; ' . $enclosure->get_size() . ' MB)" />', 'altclass' => 'download')) . '</p>';
                 }
                 $i++;
             }
             $cntFeedUrl++;
         }
     }
 }