get_item_quantity() public method

This is well-suited for {@link http://php.net/for for()} loops with {@see \get_item()}
public get_item_quantity ( integer $max ) : integer
$max integer Maximum value to return. 0 for no limit
return integer Number of items in the feed
示例#1
0
 public function respond()
 {
     $url = trim($this->matches[1]);
     $index = 0;
     if (isset($this->matches[2])) {
         $index = intval(trim($this->matches[2]));
         $index = $index - 1;
         $index = max(0, $index);
     }
     $error_level = error_reporting();
     error_reporting($error_level ^ E_USER_NOTICE);
     $feed = new \SimplePie();
     if ($this->cacheEnabled()) {
         $feed->set_cache_location($this->config['cache_directory']);
         $feed->set_cache_duration(600);
     }
     $feed->set_feed_url($url);
     $feed->init();
     $feed->handle_content_type();
     if ($index > $feed->get_item_quantity() - 1) {
         $index = $feed->get_item_quantity() - 1;
     }
     $item = $feed->get_item($index);
     $result = null;
     if ($item) {
         $title = html_entity_decode($item->get_title());
         $link = $item->get_permalink();
         $date = $item->get_date();
         $i = $index + 1;
         $result = "[{$i}] {$date} - {$title} - {$link}";
     }
     error_reporting($error_level);
     return $result;
 }
示例#2
0
文件: cpanel.php 项目: 01J/bealtine
 function getFeeds()
 {
     $app = JFactory::getApplication();
     $params = JComponentHelper::getParams('com_jce');
     $limit = $params->get('feed_limit', 2);
     $feeds = array();
     $options = array('rssUrl' => 'http://www.joomlacontenteditor.net/news/feed/rss/latest-news?format=feed', 'cache_time' => $params->get('feed_cachetime', 86400));
     // use this directly instead of JFactory::getXMLParserto avoid the feed data error
     jimport('simplepie.simplepie');
     if (!is_writable(JPATH_BASE . '/cache')) {
         $options['cache_time'] = 0;
     }
     $rss = new SimplePie($options['rssUrl'], JPATH_BASE . '/cache', isset($options['cache_time']) ? $options['cache_time'] : 0);
     $rss->force_feed(true);
     $rss->handle_content_type();
     if ($rss->init()) {
         $count = $rss->get_item_quantity();
         if ($count) {
             $count = $count > $limit ? $limit : $count;
             for ($i = 0; $i < $count; $i++) {
                 $feed = new StdClass();
                 $item = $rss->get_item($i);
                 $feed->link = $item->get_link();
                 $feed->title = $item->get_title();
                 $feed->description = $item->get_description();
                 $feeds[] = $feed;
             }
         }
     }
     return $feeds;
 }
示例#3
0
 /**
  * @param $rssURL
  * @param $max
  * @return array|bool
  */
 public static function getRssFeed($rssURL, $max, $cache_time)
 {
     //if (JVM_VERSION < 3){
     $erRep = tsmConfig::setErrorReporting(false, true);
     jimport('simplepie.simplepie');
     $rssFeed = new SimplePie($rssURL);
     $feeds = array();
     $count = $rssFeed->get_item_quantity();
     $limit = min($max, $count);
     for ($i = 0; $i < $limit; $i++) {
         $feed = new StdClass();
         $item = $rssFeed->get_item($i);
         $feed->link = $item->get_link();
         $feed->title = $item->get_title();
         $feed->description = $item->get_description();
         $feeds[] = $feed;
     }
     if ($erRep[0]) {
         ini_set('display_errors', $erRep[0]);
     }
     if ($erRep[1]) {
         error_reporting($erRep[1]);
     }
     return $feeds;
     /*} else {
     			jimport('joomla.feed.factory');
     			$feed = new JFeedFactory;
     			$rssFeed = $feed->getFeed($rssURL,$cache_time);
     
     			if (empty($rssFeed) or !is_object($rssFeed)) return false;
     
     			for ($i = 0; $i < $max; $i++) {
     				if (!$rssFeed->offsetExists($i)) {
     					break;
     				}
     				$feed = new StdClass();
     				$uri = (!empty($rssFeed[$i]->uri) || !is_null($rssFeed[$i]->uri)) ? $rssFeed[$i]->uri : $rssFeed[$i]->guid;
     				$text = !empty($rssFeed[$i]->content) || !is_null($rssFeed[$i]->content) ? $rssFeed[$i]->content : $rssFeed[$i]->description;
     				$feed->link = $uri;
     				$feed->title = $rssFeed[$i]->title;
     				$feed->description = $text;
     				$feeds[] = $feed;
     			}
     			return $feeds;
     		}*/
 }
function powerpress_get_news($feed_url, $limit = 10)
{
    include_once ABSPATH . WPINC . '/feed.php';
    $rss = fetch_feed($feed_url);
    // If feed doesn't work...
    if (is_wp_error($rss)) {
        require_once ABSPATH . WPINC . '/class-feed.php';
        // Try fetching the feed using CURL directly...
        $content = powerpress_remote_fopen($feed_url, false, array(), 3, false, true);
        if (!$content) {
            return false;
        }
        // Load the content in a fetch_feed object...
        $rss = new SimplePie();
        $rss->set_sanitize_class('WP_SimplePie_Sanitize_KSES');
        // We must manually overwrite $feed->sanitize because SimplePie's
        // constructor sets it before we have a chance to set the sanitization class
        $rss->sanitize = new WP_SimplePie_Sanitize_KSES();
        $rss->set_cache_class('WP_Feed_Cache');
        $rss->set_file_class('WP_SimplePie_File');
        $rss->set_raw_data($content);
        $rss->set_cache_duration(apply_filters('wp_feed_cache_transient_lifetime', 12 * HOUR_IN_SECONDS, $feed_url));
        do_action_ref_array('wp_feed_options', array(&$rss, $feed_url));
        $rss->init();
        $rss->set_output_encoding(get_option('blog_charset'));
        $rss->handle_content_type();
        if ($rss->error()) {
            return false;
        }
    }
    $rss_items = $rss->get_items(0, $rss->get_item_quantity($limit));
    // If the feed was erroneously
    if (!$rss_items) {
        $md5 = md5($this->feed);
        delete_transient('feed_' . $md5);
        delete_transient('feed_mod_' . $md5);
        $rss->__destruct();
        unset($rss);
        $rss = fetch_feed($this->feed);
        $rss_items = $rss->get_items(0, $rss->get_item_quantity($num));
        $rss->__destruct();
        unset($rss);
    }
    return $rss_items;
}
示例#5
0
文件: loader.php 项目: roka371/Ego
 function feed($feed_type, $id, $init)
 {
     require_once 'inc/simplepie.inc';
     $this->load->model('loader_model');
     if ($feed_type == 'label') {
         if ($id == 'all_feeds') {
             $url = $this->loader_model->get_feeds_all($this->session->userdata('username'));
         } else {
             $label = $this->loader_model->select_label($this->session->userdata('username'), $id);
             $url = $this->loader_model->get_feeds_forLabel($this->session->userdata('username'), $label->label);
         }
     } else {
         $feed = $this->loader_model->select_feed($id);
         if ($feed->type == 'site') {
             $url = $feed->url;
         } else {
             if ($feed->type == 'keyword') {
                 $url = 'feed://news.google.com/news/feeds?gl=us&pz=1&cf=all&ned=us&hl=en&q=' . $feed->url . '&output=rss';
             }
         }
     }
     $feed = new SimplePie($url);
     $feed->enable_cache(true);
     $feed->set_cache_location('cache');
     $feed->set_cache_duration(600);
     //default: 10 minutes
     $feed->set_item_limit(11);
     $feed->init();
     $feed->handle_content_type();
     if ($init == "quantity") {
         echo $feed->get_item_quantity();
     } else {
         if ($init == "discovery") {
             if ($feed_type == 'label') {
                 $data['entries'] = $feed->get_items(0, 20);
             } else {
                 $data['entries'] = $feed->get_items();
             }
             $this->load->view('loader/discovery_viewer', $data);
         } else {
             $data['entries'] = $feed->get_items($init, $init + 10);
             $this->load->view('loader/feed_viewer', $data);
         }
     }
 }
示例#6
0
 /**
  * Method description
  *
  * @param  $service_id id of the service, we're about to use
  * @param  $service_type_id of the service, we're about to use
  * @param  $feed_url the url of the feed
  * @param  $items_per_feed maximum number of items that are fetched from the feed
  * @param  $items_max_age maximum age of any item that is fetched from feed, in days
  * @return
  * @access
  */
 function feed2array($username, $service_id, $service_type_id, $feed_url, $items_per_feed = 5, $items_max_age = '-21 days')
 {
     if (!$feed_url) {
         return false;
     }
     # get info about service type
     $max_age = $items_max_age ? date('Y-m-d H:i:s', strtotime($items_max_age)) : null;
     $items = array();
     $feed = new SimplePie();
     $feed->set_cache_location(CACHE . 'simplepie');
     $feed->set_feed_url($feed_url);
     $feed->set_autodiscovery_level(SIMPLEPIE_LOCATOR_NONE);
     $feed->init();
     if ($feed->error() || $feed->feed_url != $feed_url) {
         return false;
     }
     for ($i = 0; $i < $feed->get_item_quantity($items_per_feed); $i++) {
         $feeditem = $feed->get_item($i);
         # create a NoseRub item out of the feed item
         $item = array();
         $item['datetime'] = $feeditem->get_date('Y-m-d H:i:s');
         if ($max_age && $item['datetime'] < $max_age) {
             # we can stop here, as we do not expect any newer items
             break;
         }
         $item['title'] = $feeditem->get_title();
         $item['url'] = $feeditem->get_link();
         $item['intro'] = @$intro;
         $item['type'] = @$token;
         $item['username'] = $username;
         $service = $this->getService($service_id);
         if ($service) {
             $item['content'] = $service->getContent($feeditem);
             if ($service instanceof TwitterService) {
                 $item['title'] = $item['content'];
             }
         } else {
             $item['content'] = $feeditem->get_content();
         }
         $items[] = $item;
     }
     unset($feed);
     return $items;
 }
示例#7
0
	/**
	 * @param $rssURL
	 * @param $max
	 * @return array|bool
	 */
	static public function getRssFeed($rssURL, $max) {

		if (JVM_VERSION < 3){
			jimport('simplepie.simplepie');
			$rssFeed = new SimplePie($rssURL);

			$feeds = array();
			$count = $rssFeed->get_item_quantity();
			$limit=min($max,$count);
			for ($i = 0; $i < $limit; $i++) {
				$feed = new StdClass();
				$item = $rssFeed->get_item($i);
				$feed->link = $item->get_link();
				$feed->title = $item->get_title();
				$feed->description = $item->get_description();
				$feeds[] = $feed;
			}
			return $feeds;

		} else {
			jimport('joomla.feed.factory');
			$feed = new JFeedFactory;
			$rssFeed = $feed->getFeed($rssURL);

			if (empty($rssFeed) or !is_object($rssFeed)) return false;

			for ($i = 0; $i < $max; $i++) {
				if (!$rssFeed->offsetExists($i)) {
					break;
				}
				$feed = new StdClass();
				$uri = (!empty($rssFeed[$i]->uri) || !is_null($rssFeed[$i]->uri)) ? $rssFeed[$i]->uri : $rssFeed[$i]->guid;
				$text = !empty($rssFeed[$i]->content) || !is_null($rssFeed[$i]->content) ? $rssFeed[$i]->content : $rssFeed[$i]->description;
				$feed->link = $uri;
				$feed->title = $rssFeed[$i]->title;
				$feed->description = $text;
				$feeds[] = $feed;
			}
			return $feeds;
		}

	}
示例#8
0
文件: simplepie.php 项目: vad/taolin
 function feed_paginate($feed_url, $start = 0, $limit = 5)
 {
     //make the cache dir if it doesn't exist
     if (!file_exists($this->cache)) {
         $folder = new Folder($this->cache, true);
     }
     //include the vendor class
     App::import('Vendor', 'simplepie/simplepie');
     //setup SimplePie
     $feed = new SimplePie();
     $feed->set_feed_url($feed_url);
     $feed->set_cache_location($this->cache);
     //retrieve the feed
     $feed->init();
     //limits
     $max = $start + $limit;
     $items['title'] = $feed->get_title();
     $items['image_url'] = $feed->get_image_url();
     $items['image_height'] = $feed->get_image_height();
     $items['image_width'] = $feed->get_image_width();
     //$items['title'] = $feed->get_title();
     //get the feed items
     $items['quantity'] = $feed->get_item_quantity();
     if ($items['quantity'] < $start) {
         $items['items'] = false;
         return $items;
     } elseif ($items['quantity'] < $max) {
         $max = $items['quantity'];
     }
     for ($i = $start; $i < $max; $i++) {
         $items['items'][] = $feed->get_item($i);
     }
     //return
     if ($items) {
         return $items;
     } else {
         return false;
     }
 }
示例#9
0
 /**
  *
  *   //get all the admin feeds in database.
  */
 private function get_new_feeds($category_id)
 {
     //get all the admin feeds in database.
     $dbfeeds = ORM::factory('feed')->select('id', 'feed_url', 'category_id')->where('category_id', $category_id)->find_all();
     if ($category_id == 0) {
         $dbfeeds = ORM::factory('feed')->select('id', 'feed_url', 'category_id')->find_all();
     }
     foreach ($dbfeeds as $dbfeed) {
         //Don't do anything about twitter categories.
         if ($dbfeed->category_id != 11) {
             $url = "";
             $feed = new SimplePie();
             $feed->enable_order_by_date(true);
             if ($dbfeed->category_id == 1) {
                 $url = "http://twitter.com/statuses/user_timeline/" . $dbfeed->feed_url . ".rss";
                 $feed->set_feed_url($url);
                 //	exit(0);
             } else {
                 $url = $dbfeed->feed_url;
                 $feed->set_feed_url($dbfeed->feed_url);
             }
             $feed->set_cache_location(APPPATH . 'cache');
             $feed->set_timeout(10);
             $feed->init();
             //		$channel = $feed->get_feed_tags('', 'channel');
             //		echo " tags=> ".$channel."<br/>";
             // echo "$url :<br/>";
             //	exit(0)
             $max_items = $feed->get_item_quantity();
             $require_new_items = 20;
             $new_item_counter = 0;
             $start = 0;
             for ($i = $start; $i < $max_items && $new_item_counter < $require_new_items; $i++) {
                 $item = $feed->get_item($i);
                 /*				//getting all the feed information.								 
                 						echo "$url:  latitude => ".$item->get_latitude();
                 						echo "   longitude => ".$item->get_longitude();
                 						echo '<a href="' . $feed->get_image_link() . '" title="' . $feed->get_image_title() . '">';
                 						echo '<img src="' . $feed->get_image_url() . '" width="' . $feed->get_image_width() . '" height="' . $feed->get_image_height() . '" />';
                 						echo '</a><br/>Title:'.$item->get_title();
                 						echo '<br/>Description:'.$item->get_description();
                 						echo '<hr/>';
                 								
                 						*/
                 $itemobj = new Feed_Item_Model();
                 $itemobj->feed_id = $dbfeed->id;
                 $itemobj->item_title = $item->get_title();
                 $itemobj->item_description = $item->get_description();
                 $itemobj->item_link = $item->get_permalink();
                 $itemobj->item_date = $item->get_date('Y-m-d h:m:s');
                 if ($author = $item->get_author()) {
                     $itemobj->item_source = $item->get_author()->get_name();
                     //temporary not working.
                 }
                 //echo "in Main Controller $dbfeed->feed_url =>  latitude =".$feed->get_latitude().", longitude =".$feed->get_longitude()."<br/>";
                 //echo "in Main Controller $dbfeed->feed_url =>   get_author() => ".$feed->get_author()."<br/>";
                 $linkCount = ORM::factory('feed_item')->where('item_link', $item->get_permalink())->count_all();
                 if ($linkCount == 0) {
                     $new_item_counter++;
                     //  echo "link:=> ".$item->get_permalink()." is new and has appear ".$linkCount." times <br/>";
                     $itemobj->save();
                 } else {
                     if ($linkCount > 0) {
                         //	echo "link:=> ".$item->get_permalink()." appears ".$linkCount." times <br/>";
                     }
                 }
             }
         }
     }
     //		exit(0);
 }
示例#10
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;
}
示例#11
0
function local_delivery($importer, $data)
{
    $a = get_app();
    logger(__FUNCTION__, LOGGER_TRACE);
    if ($importer['readonly']) {
        // We aren't receiving stuff from this person. But we will quietly ignore them
        // rather than a blatant "go away" message.
        logger('local_delivery: ignoring');
        return 0;
        //NOTREACHED
    }
    // Consume notification feed. This may differ from consuming a public feed in several ways
    // - might contain email or friend suggestions
    // - might contain remote followup to our message
    //		- in which case we need to accept it and then notify other conversants
    // - we may need to send various email notifications
    $feed = new SimplePie();
    $feed->set_raw_data($data);
    $feed->enable_order_by_date(false);
    $feed->init();
    if ($feed->error()) {
        logger('local_delivery: Error parsing XML: ' . $feed->error());
    }
    // Check at the feed level for updated contact name and/or photo
    $name_updated = '';
    $new_name = '';
    $photo_timestamp = '';
    $photo_url = '';
    $contact_updated = '';
    $rawtags = $feed->get_feed_tags(NAMESPACE_DFRN, 'owner');
    // Fallback should not be needed here. If it isn't DFRN it won't have DFRN updated tags
    //	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 != $importer['name'] and $new_name != "" and $name_updated <= $importer['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 ($photo_timestamp && strlen($photo_url) && $photo_timestamp > $importer['avatar-date']) {
        $contact_updated = $photo_timestamp;
        logger('local_delivery: Updating photo for ' . $importer['name']);
        require_once "include/Photo.php";
        $photos = import_profile_photo($photo_url, $importer['importer_uid'], $importer['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($importer['importer_uid']), intval($importer['id']));
    }
    if ($name_updated && strlen($new_name) && $name_updated > $importer['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($importer['importer_uid']), intval($importer['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($importer['importer_uid']), intval($importer['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($importer['importer_uid']), dbesc(notags(trim($new_name))));
        }
    }
    if ($contact_updated and $new_name and $photo_url) {
        poco_check($importer['url'], $new_name, NETWORK_DFRN, $photo_url, "", "", "", "", "", $contact_updated, 2, $importer['id'], $importer['importer_uid']);
    }
    // Currently unsupported - needs a lot of work
    $reloc = $feed->get_feed_tags(NAMESPACE_DFRN, 'relocate');
    if (isset($reloc[0]['child'][NAMESPACE_DFRN])) {
        $base = $reloc[0]['child'][NAMESPACE_DFRN];
        $newloc = array();
        $newloc['uid'] = $importer['importer_uid'];
        $newloc['cid'] = $importer['id'];
        $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
        $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
        $newloc['thumb'] = notags(unxmlify($base['thumb'][0]['data']));
        $newloc['micro'] = notags(unxmlify($base['micro'][0]['data']));
        $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
        $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
        $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
        $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
        $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
        $newloc['sitepubkey'] = notags(unxmlify($base['sitepubkey'][0]['data']));
        /** relocated user must have original key pair */
        /*$newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
        		$newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));*/
        logger("items:relocate contact " . print_r($newloc, true) . print_r($importer, true), LOGGER_DEBUG);
        // update contact
        $r = q("SELECT photo, url FROM contact WHERE id=%d AND uid=%d;", intval($importer['id']), intval($importer['importer_uid']));
        if ($r === false) {
            return 1;
        }
        $old = $r[0];
        $x = q("UPDATE contact SET\n\t\t\t\t\tname = '%s',\n\t\t\t\t\tphoto = '%s',\n\t\t\t\t\tthumb = '%s',\n\t\t\t\t\tmicro = '%s',\n\t\t\t\t\turl = '%s',\n\t\t\t\t\tnurl = '%s',\n\t\t\t\t\trequest = '%s',\n\t\t\t\t\tconfirm = '%s',\n\t\t\t\t\tnotify = '%s',\n\t\t\t\t\tpoll = '%s',\n\t\t\t\t\t`site-pubkey` = '%s'\n\t\t\tWHERE id=%d AND uid=%d;", dbesc($newloc['name']), dbesc($newloc['photo']), dbesc($newloc['thumb']), dbesc($newloc['micro']), dbesc($newloc['url']), dbesc(normalise_link($newloc['url'])), dbesc($newloc['request']), dbesc($newloc['confirm']), dbesc($newloc['notify']), dbesc($newloc['poll']), dbesc($newloc['sitepubkey']), intval($importer['id']), intval($importer['importer_uid']));
        if ($x === false) {
            return 1;
        }
        // update items
        $fields = array('owner-link' => array($old['url'], $newloc['url']), 'author-link' => array($old['url'], $newloc['url']), 'owner-avatar' => array($old['photo'], $newloc['photo']), 'author-avatar' => array($old['photo'], $newloc['photo']));
        foreach ($fields as $n => $f) {
            $x = q("UPDATE `item` SET `%s`='%s' WHERE `%s`='%s' AND uid=%d", $n, dbesc($f[1]), $n, dbesc($f[0]), intval($importer['importer_uid']));
            if ($x === false) {
                return 1;
            }
        }
        // TODO
        // merge with current record, current contents have priority
        // update record, set url-updated
        // update profile photos
        // schedule a scan?
        return 0;
    }
    // handle friend suggestion notification
    $sugg = $feed->get_feed_tags(NAMESPACE_DFRN, 'suggest');
    if (isset($sugg[0]['child'][NAMESPACE_DFRN])) {
        $base = $sugg[0]['child'][NAMESPACE_DFRN];
        $fsugg = array();
        $fsugg['uid'] = $importer['importer_uid'];
        $fsugg['cid'] = $importer['id'];
        $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
        $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
        $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
        $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
        $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
        // Does our member already have a friend matching this description?
        $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1", dbesc($fsugg['name']), dbesc(normalise_link($fsugg['url'])), intval($fsugg['uid']));
        if (count($r)) {
            return 0;
        }
        // Do we already have an fcontact record for this person?
        $fid = 0;
        $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1", dbesc($fsugg['url']), dbesc($fsugg['name']), dbesc($fsugg['request']));
        if (count($r)) {
            $fid = $r[0]['id'];
            // OK, we do. Do we already have an introduction for this person ?
            $r = q("select id from intro where uid = %d and fid = %d limit 1", intval($fsugg['uid']), intval($fid));
            if (count($r)) {
                return 0;
            }
        }
        if (!$fid) {
            $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ", dbesc($fsugg['name']), dbesc($fsugg['url']), dbesc($fsugg['photo']), dbesc($fsugg['request']));
        }
        $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1", dbesc($fsugg['url']), dbesc($fsugg['name']), dbesc($fsugg['request']));
        if (count($r)) {
            $fid = $r[0]['id'];
        } else {
            return 0;
        }
        $hash = random_string();
        $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )\n\t\t\tVALUES( %d, %d, %d, '%s', '%s', '%s', %d )", intval($fsugg['uid']), intval($fid), intval($fsugg['cid']), dbesc($fsugg['body']), dbesc($hash), dbesc(datetime_convert()), intval(0));
        notification(array('type' => NOTIFY_SUGGEST, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $fsugg, 'link' => $a->get_baseurl() . '/notifications/intros', 'source_name' => $importer['name'], 'source_link' => $importer['url'], 'source_photo' => $importer['photo'], 'verb' => ACTIVITY_REQ_FRIEND, 'otype' => 'intro'));
        return 0;
    }
    $ismail = false;
    $rawmail = $feed->get_feed_tags(NAMESPACE_DFRN, 'mail');
    if (isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
        logger('local_delivery: private message received');
        $ismail = true;
        $base = $rawmail[0]['child'][NAMESPACE_DFRN];
        $msg = array();
        $msg['uid'] = $importer['importer_uid'];
        $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
        $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
        $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
        $msg['contact-id'] = $importer['id'];
        $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
        $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
        $msg['seen'] = 0;
        $msg['replied'] = 0;
        $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
        $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
        $msg['created'] = datetime_convert(notags(unxmlify('UTC', 'UTC', $base['sentdate'][0]['data'])));
        dbesc_array($msg);
        $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) . "`) VALUES ('" . implode("', '", array_values($msg)) . "')");
        // send notifications.
        require_once 'include/enotify.php';
        $notif_params = array('type' => NOTIFY_MAIL, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $msg, 'source_name' => $msg['from-name'], 'source_link' => $importer['url'], 'source_photo' => $importer['thumb'], 'verb' => ACTIVITY_POST, 'otype' => 'mail');
        notification($notif_params);
        return 0;
        // NOTREACHED
    }
    $community_page = 0;
    $rawtags = $feed->get_feed_tags(NAMESPACE_DFRN, 'community');
    if ($rawtags) {
        $community_page = intval($rawtags[0]['data']);
    }
    if (intval($importer['forum']) != $community_page) {
        q("update contact set forum = %d where id = %d", intval($community_page), intval($importer['id']));
        $importer['forum'] = (string) $community_page;
    }
    logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
    // process any deleted entries
    $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
    if (is_array($del_entries) && count($del_entries)) {
        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) {
                // check for relayed deletes to our conversation
                $is_reply = false;
                $r = q("select * from item where uri = '%s' and uid = %d limit 1", dbesc($uri), intval($importer['importer_uid']));
                if (count($r)) {
                    $parent_uri = $r[0]['parent-uri'];
                    if ($r[0]['id'] != $r[0]['parent']) {
                        $is_reply = true;
                    }
                }
                if ($is_reply) {
                    $community = false;
                    if ($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP) {
                        $sql_extra = '';
                        $community = true;
                        logger('local_delivery: possible community delete');
                    } else {
                        $sql_extra = " and contact.self = 1 and item.wall = 1 ";
                    }
                    // was the top-level post for this reply written by somebody on this site?
                    // Specifically, the recipient?
                    $is_a_remote_delete = false;
                    // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
                    $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,\n\t\t\t\t\t\t`contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`\n\t\t\t\t\t\tINNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\t\t\tWHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')\n\t\t\t\t\t\tAND `item`.`uid` = %d\n\t\t\t\t\t\t{$sql_extra}\n\t\t\t\t\t\tLIMIT 1", dbesc($parent_uri), dbesc($parent_uri), dbesc($parent_uri), intval($importer['importer_uid']));
                    if ($r && count($r)) {
                        $is_a_remote_delete = true;
                    }
                    // Does this have the characteristics of a community or private group comment?
                    // If it's a reply to a wall post on a community/prvgroup page it's a
                    // valid community comment. Also forum_mode makes it valid for sure.
                    // If neither, it's not.
                    if ($is_a_remote_delete && $community) {
                        if (!$r[0]['forum_mode'] && !$r[0]['wall']) {
                            $is_a_remote_delete = false;
                            logger('local_delivery: not a community delete');
                        }
                    }
                    if ($is_a_remote_delete) {
                        logger('local_delivery: received remote delete');
                    }
                }
                $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['importer_uid']), intval($importer['id']));
                if (count($r)) {
                    $item = $r[0];
                    if ($item['deleted']) {
                        continue;
                    }
                    logger('local_delivery: 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['importer_uid']));
                        create_tags_from_itemuri($item['uri'], $importer['importer_uid']);
                        create_files_from_itemuri($item['uri'], $importer['importer_uid']);
                        update_thread_uri($item['uri'], $importer['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['importer_uid']));
                        create_tags_from_itemuri($uri, $importer['importer_uid']);
                        create_files_from_itemuri($uri, $importer['importer_uid']);
                        update_thread_uri($uri, $importer['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 `uid` = %d\n\t\t\t\t\t\t\t\tORDER BY `created` DESC LIMIT 1", dbesc($item['parent-uri']), intval($importer['importer_uid']));
                            if (count($r)) {
                                q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d", intval($r[0]['id']));
                            }
                        }
                        // if this is a relayed delete, propagate it to other recipients
                        if ($is_a_remote_delete) {
                            proc_run('php', "include/notifier.php", "drop", $item['id']);
                        }
                    }
                }
            }
        }
    }
    foreach ($feed->get_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) {
            $community = false;
            if ($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP) {
                $sql_extra = '';
                $community = true;
                logger('local_delivery: possible community reply');
            } else {
                $sql_extra = " and contact.self = 1 and item.wall = 1 ";
            }
            // was the top-level post for this reply written by somebody on this site?
            // Specifically, the recipient?
            $is_a_remote_comment = false;
            $top_uri = $parent_uri;
            $r = q("select `item`.`parent-uri` from `item`\n\t\t\t\tWHERE `item`.`uri` = '%s'\n\t\t\t\tLIMIT 1", dbesc($parent_uri));
            if ($r && count($r)) {
                $top_uri = $r[0]['parent-uri'];
                // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
                $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,\n\t\t\t\t\t`contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`\n\t\t\t\t\tINNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\t\tWHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')\n\t\t\t\t\tAND `item`.`uid` = %d\n\t\t\t\t\t{$sql_extra}\n\t\t\t\t\tLIMIT 1", dbesc($top_uri), dbesc($top_uri), dbesc($top_uri), intval($importer['importer_uid']));
                if ($r && count($r)) {
                    $is_a_remote_comment = true;
                }
            }
            // Does this have the characteristics of a community or private group comment?
            // If it's a reply to a wall post on a community/prvgroup page it's a
            // valid community comment. Also forum_mode makes it valid for sure.
            // If neither, it's not.
            if ($is_a_remote_comment && $community) {
                if (!$r[0]['forum_mode'] && !$r[0]['wall']) {
                    $is_a_remote_comment = false;
                    logger('local_delivery: not a community reply');
                }
            }
            if ($is_a_remote_comment) {
                logger('local_delivery: received remote comment');
                $is_like = false;
                // remote reply to our post. Import and then notify everybody else.
                $datarray = get_atom_elements($feed, $item);
                $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body`  FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['importer_uid']));
                // Update content if 'updated' changes
                if (count($r)) {
                    $iid = $r[0]['id'];
                    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;
                        }
                        logger('received updated comment', LOGGER_DEBUG);
                        $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['importer_uid']));
                        create_tags_from_itemuri($item_id, $importer['importer_uid']);
                        proc_run('php', "include/notifier.php", "comment-import", $iid);
                    }
                    continue;
                }
                $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1", intval($importer['importer_uid']));
                $datarray['type'] = 'remote-comment';
                $datarray['wall'] = 1;
                $datarray['parent-uri'] = $parent_uri;
                $datarray['uid'] = $importer['importer_uid'];
                $datarray['owner-name'] = $own[0]['name'];
                $datarray['owner-link'] = $own[0]['url'];
                $datarray['owner-avatar'] = $own[0]['thumb'];
                $datarray['contact-id'] = $importer['id'];
                if ($datarray['verb'] === ACTIVITY_LIKE || $datarray['verb'] === ACTIVITY_DISLIKE || $datarray['verb'] === ACTIVITY_ATTEND || $datarray['verb'] === ACTIVITY_ATTENDNO || $datarray['verb'] === ACTIVITY_ATTENDMAYBE) {
                    $is_like = true;
                    $datarray['type'] = 'activity';
                    $datarray['gravity'] = GRAVITY_LIKE;
                    $datarray['last-child'] = 0;
                    // 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 (`parent-uri` = '%s') and deleted = 0 limit 1", intval($datarray['uid']), intval($datarray['contact-id']), dbesc($datarray['verb']), dbesc($datarray['parent-uri']));
                    if ($r && count($r)) {
                        continue;
                    }
                    $r = q("select id from item where uid = %d and `contact-id` = %d and verb = '%s' and (`thr-parent` = '%s') and deleted = 0 limit 1", intval($datarray['uid']), intval($datarray['contact-id']), dbesc($datarray['verb']), dbesc($datarray['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 && $xt->id) {
                        // fetch the parent item
                        $tagp = q("select * from item where uri = '%s' and uid = %d limit 1", dbesc($xt->id), intval($importer['importer_uid']));
                        if (!count($tagp)) {
                            continue;
                        }
                        // extract tag, if not duplicate, and this user allows tags, add to parent item
                        if ($xo->id && $xo->content) {
                            $newtag = '#[url=' . $xo->id . ']' . $xo->content . '[/url]';
                            if (!stristr($tagp[0]['tag'], $newtag)) {
                                $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1", intval($importer['importer_uid']));
                                if (count($i) && !intval($i[0]['blocktags'])) {
                                    q("UPDATE item SET tag = '%s', `edited` = '%s', `changed` = '%s' WHERE id = %d", dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag), intval($tagp[0]['id']), dbesc(datetime_convert()), dbesc(datetime_convert()));
                                    create_tags_from_item($tagp[0]['id']);
                                }
                            }
                        }
                    }
                }
                $posted_id = item_store($datarray);
                $parent = 0;
                if ($posted_id) {
                    $datarray["id"] = $posted_id;
                    $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($posted_id), intval($importer['importer_uid']));
                    if (count($r)) {
                        $parent = $r[0]['parent'];
                        $parent_uri = $r[0]['parent-uri'];
                    }
                    if (!$is_like) {
                        $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d", dbesc(datetime_convert()), intval($importer['importer_uid']), intval($r[0]['parent']));
                        $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d", dbesc(datetime_convert()), intval($importer['importer_uid']), intval($posted_id));
                    }
                    if ($posted_id && $parent) {
                        proc_run('php', "include/notifier.php", "comment-import", "{$posted_id}");
                        if (!$is_like && !$importer['self']) {
                            require_once 'include/enotify.php';
                            notification(array('type' => NOTIFY_COMMENT, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($posted_id)), 'source_name' => stripslashes($datarray['author-name']), 'source_link' => $datarray['author-link'], 'source_photo' => link_compare($datarray['author-link'], $importer['url']) ? $importer['thumb'] : $datarray['author-avatar'], 'verb' => ACTIVITY_POST, 'otype' => 'item', 'parent' => $parent, 'parent_uri' => $parent_uri));
                        }
                    }
                    return 0;
                    // NOTREACHED
                }
            } else {
                // regular comment that is part of this total conversation. Have we seen it? If not, import it.
                $item_id = $item->get_id();
                $datarray = get_atom_elements($feed, $item);
                if ($importer['rel'] == CONTACT_IS_FOLLOWER) {
                    continue;
                }
                $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['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['importer_uid']));
                        create_tags_from_itemuri($item_id, $importer['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['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['importer_uid']));
                    }
                    continue;
                }
                $datarray['parent-uri'] = $parent_uri;
                $datarray['uid'] = $importer['importer_uid'];
                $datarray['contact-id'] = $importer['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->content) {
                            if (!stristr($r[0]['tag'], trim($xo->content))) {
                                q("UPDATE item SET tag = '%s' WHERE id = %d", dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']' . $xo->content . '[/url]'), intval($r[0]['id']));
                                create_tags_from_item($r[0]['id']);
                            }
                        }
                    }
                }
                $posted_id = item_store($datarray);
                // find out if our user is involved in this conversation and wants to be notified.
                if (!x($datarray['type']) || $datarray['type'] != 'activity') {
                    $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0", dbesc($top_uri), intval($importer['importer_uid']));
                    if (count($myconv)) {
                        $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
                        // first make sure this isn't our own post coming back to us from a wall-to-wall event
                        if (!link_compare($datarray['author-link'], $importer_url)) {
                            foreach ($myconv as $conv) {
                                // now if we find a match, it means we're in this conversation
                                if (!link_compare($conv['author-link'], $importer_url)) {
                                    continue;
                                }
                                require_once 'include/enotify.php';
                                $conv_parent = $conv['parent'];
                                notification(array('type' => NOTIFY_COMMENT, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($posted_id)), 'source_name' => stripslashes($datarray['author-name']), 'source_link' => $datarray['author-link'], 'source_photo' => link_compare($datarray['author-link'], $importer['url']) ? $importer['thumb'] : $datarray['author-avatar'], 'verb' => ACTIVITY_POST, 'otype' => 'item', 'parent' => $conv_parent, 'parent_uri' => $parent_uri));
                                // only send one notification
                                break;
                            }
                        }
                    }
                }
                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 (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['cid'] = $importer['id'];
                    $ev['uid'] = $importer['uid'];
                    $ev['uri'] = $item_id;
                    $ev['edited'] = $datarray['edited'];
                    $ev['private'] = $datarray['private'];
                    $ev['guid'] = $datarray['guid'];
                    $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['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['importer_uid']));
                    create_tags_from_itemuri($item_id, $importer['importer_uid']);
                    update_thread_uri($item_id, $importer['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['importer_uid']));
                }
                continue;
            }
            $datarray['parent-uri'] = $item_id;
            $datarray['uid'] = $importer['importer_uid'];
            $datarray['contact-id'] = $importer['id'];
            if (!link_compare($datarray['owner-link'], $importer['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('local_delivery: Correcting item owner.', LOGGER_DEBUG);
                $datarray['owner-name'] = $importer['senderName'];
                $datarray['owner-link'] = $importer['url'];
                $datarray['owner-avatar'] = $importer['thumb'];
            }
            if ($importer['rel'] == CONTACT_IS_FOLLOWER && !tgroup_check($importer['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($importer, $datarray);
            $posted_id = item_store($datarray, false, $notify);
            if (stristr($datarray['verb'], ACTIVITY_POKE)) {
                $verb = urldecode(substr($datarray['verb'], strpos($datarray['verb'], '#') + 1));
                if (!$verb) {
                    continue;
                }
                $xo = parse_xml_string($datarray['object'], false);
                if ($xo->type == ACTIVITY_OBJ_PERSON && $xo->id) {
                    // somebody was poked/prodded. Was it me?
                    $links = parse_xml_string("<links>" . unxmlify($xo->link) . "</links>", false);
                    foreach ($links->link as $l) {
                        $atts = $l->attributes();
                        switch ($atts['rel']) {
                            case "alternate":
                                $Blink = $atts['href'];
                                break;
                            default:
                                break;
                        }
                    }
                    if ($Blink && link_compare($Blink, $a->get_baseurl() . '/profile/' . $importer['nickname'])) {
                        // send a notification
                        require_once 'include/enotify.php';
                        notification(array('type' => NOTIFY_POKE, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($posted_id)), 'source_name' => stripslashes($datarray['author-name']), 'source_link' => $datarray['author-link'], 'source_photo' => link_compare($datarray['author-link'], $importer['url']) ? $importer['thumb'] : $datarray['author-avatar'], 'verb' => $datarray['verb'], 'otype' => 'person', 'activity' => $verb, 'parent' => $datarray['parent']));
                    }
                }
            }
            continue;
        }
    }
    return 0;
    // NOTREACHED
}
示例#12
0
文件: lib.plugin.php 项目: jacko5/bjj
 /**
  * _displayRSS
  * 
  * @param string $url
  * @param int $num_items
  */
 protected function _displayRSS($url, $num_items = -1)
 {
     $rss = new SimplePie();
     $rss->strip_htmltags(array_diff($rss->strip_htmltags, array('style')));
     $rss->strip_attributes(array_diff($rss->strip_attributes, array('style', 'class', 'id')));
     $rss->set_feed_url($url);
     $rss->set_cache_class('WP_Feed_Cache');
     $rss->set_file_class('WP_SimplePie_File');
     $rss->set_cache_duration(apply_filters('wp_feed_cache_transient_lifetime', 43200, $url));
     do_action_ref_array('wp_feed_options', array(&$rss, $url));
     $rss->init();
     $rss->handle_content_type();
     if (!$rss->error()) {
         $maxitems = $rss->get_item_quantity(25);
         $rss_items = $rss->get_items(0, $maxitems);
         echo '<ul>';
         if ($num_items !== -1) {
             $rss_items = array_slice($rss_items, 0, $num_items);
         }
         if ($rss_items) {
             foreach ((array) $rss_items as $item) {
                 printf('<li><div class="date">%4$s</div><div class="thethefly-news-item">%2$s</div></li>', esc_url($item->get_permalink()), $item->get_description(), esc_html($item->get_title()), $item->get_date('D, d M Y'));
             }
         } else {
             echo "<li>";
             _e('Unfortunately the news channel is temporarily closed', 'thethe-captcha');
             echo "</li>";
         }
         echo '</ul>';
     } else {
         _e('An error has occurred, which probably means the feed is down. Try again later.', 'thethe-captcha');
     }
 }
示例#13
0
#!/usr/bin/php
<?php 
include_once '../autoloader.php';
// Parse it
$feed = new SimplePie();
if (isset($argv[1]) && $argv[1] !== '') {
    $feed->set_feed_url($argv[1]);
    $feed->enable_cache(false);
    $feed->init();
}
$items = $feed->get_items();
foreach ($items as $item) {
    echo $item->get_title() . "\n";
}
var_dump($feed->get_item_quantity());
示例#14
0
文件: helper.php 项目: bizanto/Hooked
 function getFeed(&$params)
 {
     //global $mainframe;
     $slick_rss = array();
     //init feed array
     if (!class_exists('SimplePie')) {
         //include Simple Pie processor class
         require_once JPATH_SITE . DS . 'libraries' . DS . 'simplepie' . DS . 'simplepie.php';
     }
     // check if cache directory exists and is writeable
     $cacheDir = JPATH_BASE . DS . 'cache';
     if (!is_writable($cacheDir)) {
         $slick_rss['error'][] = 'Cache folder is unwriteable. Solution: chmod 777 ' . $cacheDir;
         $cache_exists = false;
     } else {
         $cache_exists = true;
     }
     //get local module parameters from xml file module config settings
     $rssurl = $params->get('rssurl', NULL);
     $rssitems = $params->get('rssitems', 5);
     $rssdesc = $params->get('rssdesc', 1);
     $rssimage = $params->get('rssimage', 1);
     $rssitemtitle_words = $params->get('rssitemtitle_words', 0);
     $rssitemdesc = $params->get('rssitemdesc', 0);
     $rssitemdesc_images = $params->get('rssitemdesc_images', 1);
     $rssitemdesc_words = $params->get('rssitemdesc_words', 0);
     $rsstitle = $params->get('rsstitle', 1);
     $rsscache = $params->get('rsscache', 3600);
     $link_target = $params->get('link_target', 1);
     $no_follow = $params->get('no_follow', 0);
     $enable_tooltip = $params->get('enable_tooltip', 'yes');
     $tooltip_desc_words = $params->get('t_word_count_desc', 25);
     $tooltip_desc_images = $params->get('tooltip_desc_images', 1);
     $tooltip_title_words = $params->get('t_word_count_title', 25);
     if (!$rssurl) {
         $slick_rss['error'][] = 'Invalid feed url. Please enter a valid url in the module settings.';
         return $slick_rss;
         //halt if no valid feed url supplied
     }
     switch ($link_target) {
         //open links in current or new window
         case 1:
             $link_target = '_blank';
             break;
         case 0:
             $link_target = '_self';
             break;
         default:
             $link_target = '_blank';
             break;
     }
     $slick_rss['target'] = $link_target;
     if ($no_follow) {
         $slick_rss['nofollow'] = 'rel="nofollow"';
     }
     //Load and build the feed array
     $feed = new SimplePie();
     $feed->set_feed_url($rssurl);
     //check and set caching
     if ($cache_exists) {
         $feed->set_cache_location($cacheDir);
         $feed->enable_cache();
         $cache_time = intval($rsscache);
         $feed->set_cache_duration($cache_time);
     } else {
         $feed->enable_cache('false');
     }
     $feed->init();
     //process the loaded feed
     $feed->handle_content_type();
     //store any error message
     if (isset($feed->error)) {
         $slick_rss['error'][] = $feed->error;
     }
     //start building the feed meta-info (title, desc and image)
     // feed title
     if ($feed->get_title() && $rsstitle) {
         $slick_rss['title']['link'] = $feed->get_link();
         $slick_rss['title']['title'] = $feed->get_title();
     }
     // feed description
     if ($rssdesc) {
         $slick_rss['description'] = $feed->get_description();
     }
     // feed image
     if ($rssimage && $feed->get_image_url()) {
         $slick_rss['image']['url'] = $feed->get_image_url();
         $slick_rss['image']['title'] = $feed->get_image_title();
     }
     //end feed meta-info
     //start processing feed items
     //if there are items in the feed
     if ($feed->get_item_quantity()) {
         //start looping through the feed items
         $slick_rss_item = 0;
         //item counter for array indexing in the loop
         foreach ($feed->get_items(0, $rssitems) as $currItem) {
             // item title
             $item_title = trim($currItem->get_title());
             // item title word limit check
             if ($rssitemtitle_words) {
                 $item_titles = explode(' ', $item_title);
                 $count = count($item_titles);
                 if ($count > $rssitemtitle_words) {
                     $item_title = '';
                     for ($i = 0; $i < $rssitemtitle_words; $i++) {
                         $item_title .= ' ' . $item_titles[$i];
                     }
                     $item_title .= '...';
                 }
             }
             $slick_rss['items'][$slick_rss_item]['title'] = $item_title;
             // Item Title
             $slick_rss['items'][$slick_rss_item]['link'] = $currItem->get_permalink();
             // item description
             if ($rssitemdesc) {
                 $desc = trim($currItem->get_description());
                 if (!$rssitemdesc_images) {
                     $desc = preg_replace("/<img[^>]+\\>/i", "", $desc);
                     //strip image tags
                 }
                 //item description word limit check
                 if ($rssitemdesc_words) {
                     $texts = explode(' ', $desc);
                     $count = count($texts);
                     if ($count > $rssitemdesc_words) {
                         $desc = '';
                         for ($i = 0; $i < $rssitemdesc_words; $i++) {
                             $desc .= ' ' . $texts[$i];
                             //build words
                         }
                         $desc .= '...';
                     }
                 }
                 $slick_rss['items'][$slick_rss_item]['description'] = $desc;
                 //Item Description
             }
             // tooltip text
             if ($enable_tooltip == 'yes') {
                 //tooltip item title
                 $t_item_title = trim($currItem->get_title());
                 // tooltip title word limit check
                 if ($tooltip_title_words) {
                     $t_item_titles = explode(' ', $t_item_title);
                     $count = count($t_item_titles);
                     if ($count > $tooltip_title_words) {
                         $tooltip_title = '';
                         for ($i = 0; $i < $tooltip_title_words; $i++) {
                             $tooltip_title .= ' ' . $t_item_titles[$i];
                         }
                         $tooltip_title .= '...';
                     } else {
                         $tooltip_title = $t_item_title;
                     }
                 } else {
                     $tooltip_title = $t_item_title;
                 }
                 $tooltip_title = preg_replace("/(\r\n|\n|\r)/", " ", $tooltip_title);
                 //replace new line characters in tooltip title, important!
                 $tooltip_title = htmlspecialchars(html_entity_decode($tooltip_title), ENT_QUOTES);
                 //format text for tooltip
                 $slick_rss['items'][$slick_rss_item]['tooltip']['title'] = $tooltip_title;
                 //Tooltip Title
                 //tooltip item description
                 $text = trim($currItem->get_description());
                 if (!$tooltip_desc_images) {
                     $text = preg_replace("/<img[^>]+\\>/i", "", $text);
                 }
                 // tooltip desc word limit check
                 if ($tooltip_desc_words) {
                     $texts = explode(' ', $text);
                     $count = count($texts);
                     if ($count > $tooltip_desc_words) {
                         $text = '';
                         for ($i = 0; $i < $tooltip_desc_words; $i++) {
                             $text .= ' ' . $texts[$i];
                         }
                         $text .= '...';
                     }
                 }
                 $text = preg_replace("/(\r\n|\n|\r)/", " ", $text);
                 //replace new line characters in tooltip, important!
                 $text = htmlspecialchars(html_entity_decode($text), ENT_QUOTES);
                 //format text for tooltip
                 $slick_rss['items'][$slick_rss_item]['tooltip']['description'] = $text;
                 //Tooltip Body
             } else {
                 $slick_rss['items'][$slick_rss_item]['tooltip'] = array();
                 //blank
             }
             $slick_rss_item++;
             //increment item counter
         }
     }
     //end item quantity check if statement
     //return the feed data structure for the template
     return $slick_rss;
 }
/**
 * 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;
}
示例#16
0
 function cron($verbose = false)
 {
     if ($verbose) {
         echo '<p>Starting cron...</p>';
     }
     global $wpdb;
     $options = get_option('proximusmoblog');
     if (!is_numeric($options['id'])) {
         $options['id'] = 1;
     }
     // Si l'id du prochain article est invalide, initialisé à 1
     if (is_numeric($options['blogid'])) {
         // Identifiant valide
         // Récupération du flux RSS
         require_once ABSPATH . WPINC . '/class-feed.php';
         $rss = new SimplePie();
         $rss->set_feed_url('http://payandgogeneration.proximus.be/moblogs/rss.cfm?id=' . $options['blogid']);
         // Désactiver le cache
         $rss->enable_cache(false);
         // Désactivation du tri par défaut
         $rss->enable_order_by_date(false);
         $rss->init();
         $rss->handle_content_type();
         $maxitems = $rss->get_item_quantity();
         // Nombre d'éléments du flux RSS
         $rss_items = $rss->get_items(0, $maxitems);
         // Tableau des articles récupérés
         $hackmin = 0;
         // Hack de décalage d'article pour ne pas avoir plusieurs articles publiés en même temps.
         for ($i = $maxitems - 1; $i >= 0; --$i) {
             $item = $rss->get_item($i);
             $guid = $item->get_id();
             $guid = substr($guid, strpos($guid, '=') + 1);
             $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key = 'proximusMoblog_guid' AND meta_value = '{$guid}'"));
             if ($count == 0) {
                 if ($verbose) {
                     echo '<li>' . $guid . '</li>';
                 }
                 $enclosure = $item->get_enclosure();
                 $image = $enclosure->get_link();
                 $image = $this->downloadImage($image, $options['blogid'], $options['id']);
                 $title = str_replace('[id]', $options['id'], $options['titre']);
                 $contenu = str_replace('[image]', $image, $options['article']);
                 $date = date('Y-m-d H:i:s', time() + $hackmin);
                 // Create post object
                 $my_post = array();
                 $my_post['post_title'] = $title;
                 $my_post['post_content'] = $contenu;
                 $my_post['post_status'] = 'publish';
                 $my_post['post_date'] = $date;
                 if (!empty($options['user'])) {
                     $my_post['post_author'] = $options['user'];
                 }
                 if (!empty($options['categorie'])) {
                     $my_post['post_category'] = array($options['categorie']);
                 }
                 // Insert the post into the database
                 $postid = wp_insert_post($my_post);
                 add_post_meta($postid, 'proximusMoblog_guid', $guid);
                 $options['id']++;
                 $hackmin += 5;
             }
         }
         update_option('proximusmoblog', $options);
     }
     // Fin identifiant valide
 }
示例#17
0
 public static function getFeedData($params)
 {
     $rssurl = str_replace("\n", ",", JString::trim($params->get('rssurl', '')));
     $feedTimeout = (int) $params->get('feedTimeout', 10);
     $rssdateorder = (int) $params->get('rssdateorder', 1);
     $dformat = $params->get('dformat', '%d %b %Y %H:%M %P');
     $rssperfeed = (int) $params->get('rssperfeed', 3);
     $textfilter = JString::trim($params->get('textfilter', ''));
     $pagination = (int) $params->get('pagination', 0);
     $totalfeeds = (int) $params->get('rssitems', 5);
     $filtermode = (int) $params->get('filtermode', 0);
     $showfeedinfo = (int) $params->get('showfeedinfo', 1);
     $input_encoding = JString::trim($params->get('inputencoding', ''));
     $showimage = (int) $params->get('rssimage', 1);
     $cacheTime = (int) $params->get('feedcache', 15) * 60;
     //minutes
     $orderBy = $params->get('orderby', 'date');
     $tmzone = (int) $params->get('tmzone', 0) ? true : false;
     $cachePath = JPATH_SITE . DS . 'cache' . DS . 'mod_we_ufeed_display';
     $start = $end = 0;
     if ($pagination) {
         $pagination_items = (int) $params->get('paginationitems', 5);
         $current_limit = modFeedShowHelper::getPage($params->get('mid', 0));
         $start = ($current_limit - 1) * $pagination_items;
         $end = $current_limit * $pagination_items;
     }
     #Get clean array
     $rss_urls = @array_filter(explode(",", $rssurl));
     #If only 1 link, use totalfeeds for total limit
     if (count($rss_urls) == 1) {
         $rssperfeed = $totalfeeds;
     }
     # Intilize RSS Doc
     if (!class_exists('SimplePie')) {
         jimport('simplepie.simplepie');
     }
     //Parser Code
     $simplepie = new SimplePie();
     $simplepie->set_cache_location($cachePath);
     $simplepie->set_cache_duration($cacheTime);
     $simplepie->set_stupidly_fast(true);
     $simplepie->force_feed(true);
     //$simplepie->force_fsockopen(false); //gives priority to CURL if is installed
     $simplepie->set_timeout($feedTimeout);
     $simplepie->set_item_limit($rssperfeed);
     $simplepie->enable_order_by_date(false);
     if ($input_encoding) {
         $simplepie->set_input_encoding($input_encoding);
         $simplepie->set_output_encoding('UTF-8');
     }
     $simplepie->set_feed_url($rss_urls);
     $simplepie->init();
     $rssTotalItems = (int) $simplepie->get_item_quantity($totalfeeds);
     if ((int) $params->get('debug', 0)) {
         echo "<h3>Total RSS Items:" . $rssTotalItems . "</h3>";
         echo print_r($simplepie, true);
         #debug
     }
     if (get_class($simplepie) != 'SimplePie' || !$rssTotalItems) {
         return array("rsstotalitems" => 0, 'items' => false);
     }
     $feedItems = array();
     #store all feeds items
     $counter = 1;
     foreach ($simplepie->get_items($start, $end) as $key => $feed) {
         #Word Filter
         if (!empty($textfilter) && $filtermode != 0) {
             $filter = modFeedShowHelper::filterItems($feed, $textfilter);
             #Include						#Exclude
             if ($filtermode == 1 && !$filter || $filtermode == 2 && $filter) {
                 $rssTotalItems--;
                 continue;
                 #Include
             }
         }
         $FeedValues[$key] = new stdClass();
         # channel header and link
         $channel = $feed->get_feed();
         $FeedValues[$key]->FeedTitle = $channel->get_title();
         $FeedValues[$key]->FeedLink = $channel->get_link();
         if ($showfeedinfo) {
             $FeedValues[$key]->FeedFavicon = 'http://g.etfv.co/' . urlencode($FeedValues[$key]->FeedLink);
         }
         $FeedValues[$key]->FeedDescription = $channel->get_description();
         $FeedValues[$key]->FeedLogo = $channel->get_image_url();
         #Item
         $FeedValues[$key]->ItemTitle = $feed->get_title();
         $feeDateUNIX = $feed->get_date('U');
         if ($feeDateUNIX < 1) {
             $feeDateUNIX = strtotime(trim(str_replace(",", "", $feed->get_date(''))));
         }
         $FeedValues[$key]->ItemDate = WEJM16 ? JHTML::_('date', $feeDateUNIX, $dformat, $tmzone) : JHtml::date($feeDateUNIX, $dformat, $tmzone);
         $FeedValues[$key]->ItemLink = $feed->get_link();
         //$feed->get_permalink();
         $FeedValues[$key]->ItemText = $feed->get_description();
         $FeedValues[$key]->ItemFulltext = $feed->get_content();
         $FeedValues[$key]->ItemEnclosure = $feed->get_enclosure();
         $FeedValues[$key]->ItemEnclosures = $feed->get_enclosures();
         if ($showimage) {
             $FeedValues[$key]->ItemImage = "";
         }
         //for next version
         if ($orderBy == 'title') {
             $idx = str_replace(array(':', '-', '(', ')', '+', '*', ' '), '', JString::strtolower(strip_tags($FeedValues[$key]->ItemTitle)));
             //ORDER BY TITLE
         } else {
             $idx = $feeDateUNIX;
             //Order By date
         }
         if (isset($feedItems[$idx])) {
             $idx .= $counter;
         }
         #unique idx
         $feedItems[$idx] = $FeedValues[$key];
         $counter++;
     }
     if ($rssdateorder == 1) {
         krsort($feedItems);
     } elseif ($rssdateorder == 2) {
         ksort($feedItems);
     } elseif ($rssdateorder == 3) {
         shuffle($feedItems);
     }
     if ((int) $params->get('debug', 0)) {
         echo "<p>Total RSS in Array:" . count($feedItems) . "</p>";
     }
     return array("rsstotalitems" => $rssTotalItems, 'items' => $feedItems);
 }
示例#18
0
echo $_POST['url'];
?>
" style="width:400px;"><input name="Submit" type="submit" value="Get Feed">
</form>
<?php 
if (isset($_POST['url']) && $_POST['url'] != "") {
    $url = $_POST['url'];
    include_once 'Simple/autoloader.php';
    $feed = new SimplePie();
    $feed->set_feed_url($url);
    $feed->enable_cache(false);
    $feed->set_output_encoding('Windows-1252');
    $feed->init();
    echo "<span><h1>" . $feed->get_title() . "</h1>";
    echo "<b>" . $feed->get_description() . "</b></span><hr />";
    $itemCount = $feed->get_item_quantity();
    $items = $feed->get_items();
    foreach ($items as $item) {
        ?>
<div><a href="<?php 
        echo $item->get_permalink();
        ?>
"><?php 
        echo $item->get_title();
        ?>
</a><br />
<em style="font-size:.7em;color:#666666"><?php 
        echo $item->get_date();
        ?>
</em>
<?php 
示例#19
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;
            }
        }
    }
}
示例#20
0
 if (empty($rss_count)) {
     $rss_count = 4;
 }
 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/") {
示例#21
0
 function RssFeed($link)
 {
     //process rss
     $feed_url = $link;
     $items_per_feed = 10;
     $items_max_age = '-60 days';
     $max_age = $items_max_age ? date('Y-m-d H:i:s', strtotime($items_max_age)) : null;
     $items = array();
     App::import('vendor', 'simplepie/simplepie');
     $feed = new SimplePie();
     $feed->set_cache_location(CACHE . 'simplepie');
     $feed->set_feed_url($feed_url);
     $feed->set_autodiscovery_level(SIMPLEPIE_LOCATOR_NONE);
     $feed->init();
     if ($feed->error() || $feed->feed_url != $feed_url) {
         return false;
     }
     for ($i = 0; $i < $feed->get_item_quantity($items_per_feed); $i++) {
         $feeditem = $feed->get_item($i);
         # create a NoseRub item out of the feed item
         $item = array();
         $item['datetime'] = $feeditem->get_date('Y-m-d H:i:s');
         if ($max_age && $item['datetime'] < $max_age) {
             # we can stop here, as we do not expect any newer items
             break;
         }
         $item['title'] = $feeditem->get_title();
         $item['url'] = $feeditem->get_link();
         //$item['intro']    = @$intro;
         //$item['type']     = @$token;
         //$item['username'] = $username;
         $items[] = $item;
     }
     unset($feed);
     $items;
     foreach ($items as $_item) {
         echo '<a href="' . $_item['url'] . '">' . $_item['title'] . '</a><br/>';
     }
     //end process rss
 }
示例#22
0
function local_delivery($importer, $data)
{
    $a = get_app();
    if ($importer['readonly']) {
        // We aren't receiving stuff from this person. But we will quietly ignore them
        // rather than a blatant "go away" message.
        logger('local_delivery: ignoring');
        return 0;
        //NOTREACHED
    }
    // Consume notification feed. This may differ from consuming a public feed in several ways
    // - might contain email or friend suggestions
    // - might contain remote followup to our message
    //		- in which case we need to accept it and then notify other conversants
    // - we may need to send various email notifications
    $feed = new SimplePie();
    $feed->set_raw_data($data);
    $feed->enable_order_by_date(false);
    $feed->init();
    /*
    	// Currently unsupported - needs a lot of work
    	$reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
    	if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
    		$base = $reloc[0]['child'][NAMESPACE_DFRN];
    		$newloc = array();
    		$newloc['uid'] = $importer['importer_uid'];
    		$newloc['cid'] = $importer['id'];
    		$newloc['name'] = notags(unxmlify($base['name'][0]['data']));
    		$newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
    		$newloc['url'] = notags(unxmlify($base['url'][0]['data']));
    		$newloc['request'] = notags(unxmlify($base['request'][0]['data']));
    		$newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
    		$newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
    		$newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
    		$newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
    		$newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
    		$newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
    		
    		// TODO
    		// merge with current record, current contents have priority
    		// update record, set url-updated
    		// update profile photos
    		// schedule a scan?
    
    	}
    */
    // handle friend suggestion notification
    $sugg = $feed->get_feed_tags(NAMESPACE_DFRN, 'suggest');
    if (isset($sugg[0]['child'][NAMESPACE_DFRN])) {
        $base = $sugg[0]['child'][NAMESPACE_DFRN];
        $fsugg = array();
        $fsugg['uid'] = $importer['importer_uid'];
        $fsugg['cid'] = $importer['id'];
        $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
        $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
        $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
        $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
        $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
        // Does our member already have a friend matching this description?
        $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1", dbesc($fsugg['name']), dbesc(normalise_link($fsugg['url'])), intval($fsugg['uid']));
        if (count($r)) {
            return 0;
        }
        // Do we already have an fcontact record for this person?
        $fid = 0;
        $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1", dbesc($fsugg['url']), dbesc($fsugg['name']), dbesc($fsugg['request']));
        if (count($r)) {
            $fid = $r[0]['id'];
            // OK, we do. Do we already have an introduction for this person ?
            $r = q("select id from intro where uid = %d and fid = %d limit 1", intval($fsugg['uid']), intval($fid));
            if (count($r)) {
                return 0;
            }
        }
        if (!$fid) {
            $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ", dbesc($fsugg['name']), dbesc($fsugg['url']), dbesc($fsugg['photo']), dbesc($fsugg['request']));
        }
        $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1", dbesc($fsugg['url']), dbesc($fsugg['name']), dbesc($fsugg['request']));
        if (count($r)) {
            $fid = $r[0]['id'];
        } else {
            return 0;
        }
        $hash = random_string();
        $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )\n\t\t\tVALUES( %d, %d, %d, '%s', '%s', '%s', %d )", intval($fsugg['uid']), intval($fid), intval($fsugg['cid']), dbesc($fsugg['body']), dbesc($hash), dbesc(datetime_convert()), intval(0));
        notification(array('type' => NOTIFY_SUGGEST, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $fsugg, 'link' => $a->get_baseurl() . '/notifications/intros', 'source_name' => $importer['name'], 'source_link' => $importer['url'], 'source_photo' => $importer['photo'], 'verb' => ACTIVITY_REQ_FRIEND, 'otype' => 'intro'));
        return 0;
    }
    $ismail = false;
    $rawmail = $feed->get_feed_tags(NAMESPACE_DFRN, 'mail');
    if (isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
        logger('local_delivery: private message received');
        $ismail = true;
        $base = $rawmail[0]['child'][NAMESPACE_DFRN];
        $msg = array();
        $msg['uid'] = $importer['importer_uid'];
        $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
        $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
        $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
        $msg['contact-id'] = $importer['id'];
        $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
        $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
        $msg['seen'] = 0;
        $msg['replied'] = 0;
        $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
        $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
        $msg['created'] = datetime_convert(notags(unxmlify('UTC', 'UTC', $base['sentdate'][0]['data'])));
        dbesc_array($msg);
        $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) . "`) VALUES ('" . implode("', '", array_values($msg)) . "')");
        // send notifications.
        require_once 'include/enotify.php';
        $notif_params = array('type' => NOTIFY_MAIL, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $msg, 'source_name' => $msg['from-name'], 'source_link' => $importer['url'], 'source_photo' => $importer['thumb'], 'verb' => ACTIVITY_POST, 'otype' => 'mail');
        notification($notif_params);
        return 0;
        // NOTREACHED
    }
    $community_page = 0;
    $rawtags = $feed->get_feed_tags(NAMESPACE_DFRN, 'community');
    if ($rawtags) {
        $community_page = intval($rawtags[0]['data']);
    }
    if (intval($importer['forum']) != $community_page) {
        q("update contact set forum = %d where id = %d limit 1", intval($community_page), intval($importer['id']));
        $importer['forum'] = (string) $community_page;
    }
    logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
    // process any deleted entries
    $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
    if (is_array($del_entries) && count($del_entries)) {
        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) {
                $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['importer_uid']), intval($importer['id']));
                if (count($r)) {
                    $item = $r[0];
                    if ($item['deleted']) {
                        continue;
                    }
                    logger('local_delivery: 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\tWHERE `parent-uri` = '%s' AND `uid` = %d", dbesc($when), dbesc(datetime_convert()), dbesc($item['uri']), intval($importer['importer_uid']));
                    } else {
                        $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' \n\t\t\t\t\t\t\tWHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($when), dbesc(datetime_convert()), dbesc($uri), intval($importer['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 `uid` = %d\n\t\t\t\t\t\t\t\tORDER BY `created` DESC LIMIT 1", dbesc($item['parent-uri']), intval($importer['importer_uid']));
                            if (count($r)) {
                                q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1", intval($r[0]['id']));
                            }
                        }
                    }
                }
            }
        }
    }
    foreach ($feed->get_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) {
            $community = false;
            if ($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP) {
                $sql_extra = '';
                $community = true;
                logger('local_delivery: possible community reply');
            } else {
                $sql_extra = " and contact.self = 1 and item.wall = 1 ";
            }
            // was the top-level post for this reply written by somebody on this site?
            // Specifically, the recipient?
            $is_a_remote_comment = false;
            $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`, \n\t\t\t\t`contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item` \n\t\t\t\tLEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id` \n\t\t\t\tWHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'\n\t\t\t\tAND `item`.`uid` = %d \n\t\t\t\t{$sql_extra}\n\t\t\t\tLIMIT 1", dbesc($parent_uri), dbesc($parent_uri), intval($importer['importer_uid']));
            if ($r && count($r)) {
                $is_a_remote_comment = true;
            }
            // Does this have the characteristics of a community or private group comment?
            // If it's a reply to a wall post on a community/prvgroup page it's a
            // valid community comment. Also forum_mode makes it valid for sure.
            // If neither, it's not.
            if ($is_a_remote_comment && $community) {
                if (!$r[0]['forum_mode'] && !$r[0]['wall']) {
                    $is_a_remote_comment = false;
                    logger('local_delivery: not a community reply');
                }
            }
            if ($is_a_remote_comment) {
                logger('local_delivery: received remote comment');
                $is_like = false;
                // remote reply to our post. Import and then notify everybody else.
                $datarray = get_atom_elements($feed, $item);
                $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body`  FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['importer_uid']));
                // Update content if 'updated' changes
                if (count($r)) {
                    $iid = $r[0]['id'];
                    if (x($datarray, 'edited') !== false && datetime_convert('UTC', 'UTC', $datarray['edited']) !== $r[0]['edited']) {
                        logger('received updated comment', LOGGER_DEBUG);
                        $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['importer_uid']));
                        proc_run('php', "include/notifier.php", "comment-import", $iid);
                    }
                    continue;
                }
                // TODO: make this next part work against both delivery threads of a community post
                //				if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
                //					logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
                // they won't know what to do so don't report an error. Just quietly die.
                //					return 0;
                //				}
                // our user with $importer['importer_uid'] is the owner
                $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1", intval($importer['importer_uid']));
                $datarray['type'] = 'remote-comment';
                $datarray['wall'] = 1;
                $datarray['parent-uri'] = $parent_uri;
                $datarray['uid'] = $importer['importer_uid'];
                $datarray['owner-name'] = $own[0]['name'];
                $datarray['owner-link'] = $own[0]['url'];
                $datarray['owner-avatar'] = $own[0]['thumb'];
                $datarray['contact-id'] = $importer['id'];
                if ($datarray['verb'] === ACTIVITY_LIKE || $datarray['verb'] === ACTIVITY_DISLIKE) {
                    $is_like = true;
                    $datarray['type'] = 'activity';
                    $datarray['gravity'] = GRAVITY_LIKE;
                    $datarray['last-child'] = 0;
                    // 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 && $xt->id) {
                        // fetch the parent item
                        $tagp = q("select * from item where uri = '%s' and uid = %d limit 1", dbesc($xt->id), intval($importer['importer_uid']));
                        if (!count($tagp)) {
                            continue;
                        }
                        // extract tag, if not duplicate, and this user allows tags, add to parent item
                        if ($xo->id && $xo->content) {
                            $newtag = '#[url=' . $xo->id . ']' . $xo->content . '[/url]';
                            if (!stristr($tagp[0]['tag'], $newtag)) {
                                $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1", intval($importer['importer_uid']));
                                if (count($i) && !intval($i[0]['blocktags'])) {
                                    q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1", dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag), intval($tagp[0]['id']), dbesc(datetime_convert()));
                                }
                            }
                        }
                    }
                }
                // 				if($community) {
                //					$newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
                //					if(! stristr($datarray['tag'],$newtag)) {
                //						if(strlen($datarray['tag']))
                //							$datarray['tag'] .= ',';
                //						$datarray['tag'] .= $newtag;
                //					}
                //				}
                $posted_id = item_store($datarray);
                $parent = 0;
                if ($posted_id) {
                    $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($posted_id), intval($importer['importer_uid']));
                    if (count($r)) {
                        $parent = $r[0]['parent'];
                    }
                    if (!$is_like) {
                        $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d", dbesc(datetime_convert()), intval($importer['importer_uid']), intval($r[0]['parent']));
                        $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1", dbesc(datetime_convert()), intval($importer['importer_uid']), intval($posted_id));
                    }
                    if ($posted_id && $parent) {
                        proc_run('php', "include/notifier.php", "comment-import", "{$posted_id}");
                        if (!$is_like && !$importer['self']) {
                            require_once 'include/enotify.php';
                            notification(array('type' => NOTIFY_COMMENT, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id, 'source_name' => stripslashes($datarray['author-name']), 'source_link' => $datarray['author-link'], 'source_photo' => link_compare($datarray['author-link'], $importer['url']) ? $importer['thumb'] : $datarray['author-avatar'], 'verb' => ACTIVITY_POST, 'otype' => 'item', 'parent' => $parent));
                        }
                    }
                    return 0;
                    // NOTREACHED
                }
            } else {
                // regular comment that is part of this total conversation. Have we seen it? If not, import it.
                $item_id = $item->get_id();
                $datarray = get_atom_elements($feed, $item);
                $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['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['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['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['importer_uid']));
                    }
                    continue;
                }
                $datarray['parent-uri'] = $parent_uri;
                $datarray['uid'] = $importer['importer_uid'];
                $datarray['contact-id'] = $importer['id'];
                if ($datarray['verb'] == ACTIVITY_LIKE || $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->content) {
                            if (!stristr($r[0]['tag'], trim($xo->content))) {
                                q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1", dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']' . $xo->content . '[/url]'), intval($r[0]['id']));
                            }
                        }
                    }
                }
                $posted_id = item_store($datarray);
                // find out if our user is involved in this conversation and wants to be notified.
                if (!x($datarray['type']) || $datarray['type'] != 'activity') {
                    $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0", dbesc($parent_uri), intval($importer['importer_uid']));
                    if (count($myconv)) {
                        $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
                        // first make sure this isn't our own post coming back to us from a wall-to-wall event
                        if (!link_compare($datarray['author-link'], $importer_url)) {
                            foreach ($myconv as $conv) {
                                // now if we find a match, it means we're in this conversation
                                if (!link_compare($conv['author-link'], $importer_url)) {
                                    continue;
                                }
                                require_once 'include/enotify.php';
                                $conv_parent = $conv['parent'];
                                notification(array('type' => NOTIFY_COMMENT, 'notify_flags' => $importer['notify-flags'], 'language' => $importer['language'], 'to_name' => $importer['username'], 'to_email' => $importer['email'], 'uid' => $importer['importer_uid'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id, 'source_name' => stripslashes($datarray['author-name']), 'source_link' => $datarray['author-link'], 'source_photo' => link_compare($datarray['author-link'], $importer['url']) ? $importer['thumb'] : $datarray['author-avatar'], 'verb' => ACTIVITY_POST, 'otype' => 'item', 'parent' => $conv_parent));
                                // only send one notification
                                break;
                            }
                        }
                    }
                }
                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 (x($datarray, 'object-type') && $datarray['object-type'] === ACTIVITY_OBJ_EVENT) {
                $ev = bbtoevent($datarray['body']);
                if (x($ev, 'desc') && x($ev, 'start')) {
                    $ev['cid'] = $importer['id'];
                    $ev['uid'] = $importer['uid'];
                    $ev['uri'] = $item_id;
                    $ev['edited'] = $datarray['edited'];
                    $ev['private'] = $datarray['private'];
                    $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['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['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['importer_uid']));
                }
                continue;
            }
            // This is my contact on another system, but it's really me.
            // Turn this into a wall post.
            if ($importer['remote_self']) {
                $datarray['wall'] = 1;
            }
            $datarray['parent-uri'] = $item_id;
            $datarray['uid'] = $importer['importer_uid'];
            $datarray['contact-id'] = $importer['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('local_delivery: Correcting item owner.', LOGGER_DEBUG);
                $datarray['owner-name'] = $importer['senderName'];
                $datarray['owner-link'] = $importer['url'];
                $datarray['owner-avatar'] = $importer['thumb'];
            }
            $r = item_store($datarray);
            continue;
        }
    }
    return 0;
    // NOTREACHED
}
示例#23
0
 public static function getRssFeed($rssURL, $max)
 {
     jimport('simplepie.simplepie');
     $rssFeed = new SimplePie($rssURL);
     $feeds = array();
     $count = $rssFeed->get_item_quantity();
     $limit = min($max, $count);
     for ($i = 0; $i < $limit; $i++) {
         $feed = new StdClass();
         $item = $rssFeed->get_item($i);
         $feed->link = $item->get_link();
         $feed->title = $item->get_title();
         $feed->description = $item->get_description();
         $feeds[] = $feed;
     }
     return $feeds;
 }
/** Require RSS lib */
require_once ABSPATH . WPINC . '/class-simplepie.php';
require_once ABSPATH . WPINC . '/class-feed.php';
require_once ABSPATH . WPINC . '/feed.php';
$_theme_rss_url = 'http://thethefly.com/index-themes-rss.php';
$_theme_rss_data = array();
$_theme_rss = new SimplePie();
$_theme_rss->set_feed_url($_theme_rss_url);
$_theme_rss->set_cache_class('WP_Feed_Cache');
$_theme_rss->set_file_class('WP_SimplePie_File');
$_theme_rss->set_cache_duration(apply_filters('wp_feed_cache_transient_lifetime', 43200, $_theme_rss_url));
do_action_ref_array('wp_feed_options', array(&$_theme_rss, $_theme_rss_url));
$_theme_rss->init();
$_theme_rss->handle_content_type();
if (!$_theme_rss->error()) {
    $maxitems = $_theme_rss->get_item_quantity(50);
    $rss_items = $_theme_rss->get_items(0, $maxitems);
    if ($rss_items) {
        $_theme_rss_data = (array) $rss_items;
    }
}
if (is_array($_theme_rss_data)) {
    ?>
<div class="thethe-themes postbox">
  <div class="handlediv" title="<?php 
    _e('Click to toggle');
    ?>
"><br />
  </div>
  <h3 class="hndle"><span>WP Themes by TheThe Fly</span></h3>
  <div class="inside">
示例#25
0
							<h2><a name="file">File Releases</a></h2>
							<div class="head_menu"><p><a href="#top"><img src="images/upArrow.png" alt="Top"/> Top</a> | <a href="https://sourceforge.net/export/rss2_projfiles.php?group_id=136478"><img src="images/rss.gif" title="File Releases RSS Feed" alt="rssFeed"/></a></p></div>
						</div>
						<div class="content_main">
							
							<?php 
$projfiles = new SimplePie();
$projfiles->enable_cache(false);
$projfiles->set_feed_url('http://sourceforge.net/export/rss2_projfiles.php?group_id=136478');
$projfiles->init();
$projfiles->handle_content_type();
if ($projfiles->data) {
    ?>
							
							<?php 
    $max = $projfiles->get_item_quantity(5);
    for ($x = 0; $x < $max; $x++) {
        $item = $projfiles->get_item($x);
        ?>
								<h3>
								    <a href="<?php 
        echo $item->get_permalink();
        ?>
">
									<?php 
        echo $item->get_title();
        ?>
								    </a>
								</h3>
								<div class="head3_menu">
									<p>
示例#26
0
function dfrn_notify_post(&$a)
{
    $dfrn_id = notags(trim($_POST['dfrn_id']));
    $challenge = notags(trim($_POST['challenge']));
    $data = $_POST['data'];
    $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1", dbesc($dfrn_id), dbesc($challenge));
    if (!count($r)) {
        xml_status(3);
    }
    $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1", dbesc($dfrn_id), dbesc($challenge));
    // find the local user who owns this relationship.
    $r = q("SELECT `contact`.*, `user`.* FROM `contact` LEFT JOIN `user` on `user`.`uid` = 1 \n\t\tWHERE ( `issued-id` = '%s' OR ( `duplex` = 1 AND `dfrn-id` = '%s' )) LIMIT 1", dbesc($dfrn_id), dbesc($dfrn_id));
    if (!count($r)) {
        xml_status(3);
        return;
        //NOTREACHED
    }
    $importer = $r[0];
    $feed = new SimplePie();
    $feed->set_raw_data($data);
    $feed->enable_order_by_date(false);
    $feed->init();
    $ismail = false;
    $rawmail = $feed->get_feed_tags(NAMESPACE_DFRN, 'mail');
    if (isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
        if ($importer['readonly']) {
            // We aren't receiving email from this person. But we will quietly ignore them
            // rather than a blatant "go away" message.
            xml_status(0);
            return;
            //NOTREACHED
        }
        $ismail = true;
        $base = $rawmail[0]['child'][NAMESPACE_DFRN];
        $msg = array();
        $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
        $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
        $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
        $msg['contact-id'] = $importer['id'];
        $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
        $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
        $msg['delivered'] = 1;
        $msg['seen'] = 0;
        $msg['replied'] = 0;
        $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
        $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
        $msg['created'] = datetime_convert(notags(unxmlify('UTC', 'UTC', $base['sentdate'][0]['data'])));
        dbesc_array($msg);
        $r = q("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) . "`) VALUES ('" . implode("', '", array_values($msg)) . "')");
        require_once 'bbcode.php';
        if ($importer['notify-flags'] & NOTIFY_MAIL) {
            $tpl = file_get_contents('view/mail_received_eml.tpl');
            $email_tpl = replace_macros($tpl, array('$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$username' => $importer['username'], '$email' => $importer['email'], '$from' => $msg['from-name'], '$title' => $msg['title'], '$body' => strip_tags(bbcode($msg['body']))));
            $res = mail($importer['email'], t("New mail received at ") . $a->config['sitename'], $email_tpl, t("From: Administrator@") . $a->get_hostname());
        }
        xml_status(0);
        return;
        // NOTREACHED
    }
    if ($importer['readonly'] && !x($a->config['rockstar'])) {
        // This contact is readonly and we're going to ignore him/her, except if we're in
        // RockStar configuration. Us rockstars wan't people to talk about us. We just don't
        // want to have to deal with them individually. So our "readonly" fans can post to
        // our wall and comment, but they can't send us email.
        xml_status(0);
        return;
        // NOTREACHED
    }
    foreach ($feed->get_items() as $item) {
        $deleted = false;
        $rawdelete = $item->get_item_tags("http://purl.org/atompub/tombstones/1.0", 'deleted-entry');
        if (isset($rawdelete[0]['attribs']['']['ref'])) {
            $uri = $rawthread[0]['attribs']['']['ref'];
            $deleted = true;
            if (isset($rawdelete[0]['attribs']['']['when'])) {
                $when = $rawthread[0]['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) {
            $r = q("SELECT * FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($uri));
            if (count($r)) {
                $item = $r[0];
                if ($item['uri'] == $item['parent-uri']) {
                    $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s' , `changed` = '%s'\n\t\t\t\t\t\tWHERE `parent-uri` = '%s'", dbesc($when), dbesc(datetime_convert()), dbesc($item['uri']));
                } else {
                    $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s' , `changed` = '%s' \n\t\t\t\t\t\tWHERE `uri` = '%s' LIMIT 1", dbesc($when), dbesc(datetime_convert()), dbesc($uri));
                }
                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' ", dbesc(datetime_convert()), dbesc($item['parent-uri']));
                    // who is the last child now?
                    $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 \n\t\t\t\t\t\tORDER BY `edited` DESC LIMIT 1", dbesc($item['parent-uri']));
                    if (count($r)) {
                        q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1", intval($r[0]['id']));
                    }
                }
            }
            continue;
        }
        $is_reply = false;
        $item_id = $item->get_id();
        $rawthread = $item->get_item_tags("http://purl.org/syndication/thread/1.0", 'in-reply-to');
        if (isset($rawthread[0]['attribs']['']['ref'])) {
            $is_reply = true;
            $parent_uri = $rawthread[0]['attribs']['']['ref'];
        }
        if ($is_reply) {
            if ($feed->get_item_quantity() == 1) {
                // remote reply to our post. Import and then notify everybody else.
                $datarray = get_atom_elements($item);
                $datarray['wall'] = 1;
                $datarray['type'] = 'remote-comment';
                $datarray['parent-uri'] = $parent_uri;
                $datarray['contact-id'] = $importer['id'];
                $posted_id = post_remote($a, $datarray);
                if ($posted_id) {
                    $r = q("SELECT `parent` FROM `item` WHERE `id` = %d LIMIT 1", intval($posted_id));
                    if (count($r)) {
                        $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d", dbesc(datetime_convert()), intval($r[0]['parent']));
                    }
                    $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `id` = %d LIMIT 1", dbesc(datetime_convert()), intval($posted_id));
                    $php_path = strlen($a->config['php_path']) ? $a->config['php_path'] : 'php';
                    proc_close(proc_open("\"{$php_path}\" \"include/notifier.php\" \"comment-import\" \"{$posted_id}\" &", array(), $foo));
                    if ($importer['notify-flags'] & NOTIFY_COMMENT && !$importer['self']) {
                        require_once 'bbcode.php';
                        $from = stripslashes($datarray['author-name']);
                        $tpl = file_get_contents('view/cmnt_received_eml.tpl');
                        $email_tpl = replace_macros($tpl, array('$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$username' => $importer['username'], '$email' => $importer['email'], '$from' => $from, '$body' => strip_tags(bbcode(stripslashes($datarray['body'])))));
                        $res = mail($importer['email'], $from . t(" commented on your item at ") . $a->config['sitename'], $email_tpl, t("From: Administrator@") . $a->get_hostname());
                    }
                }
                xml_status(0);
                return;
            } else {
                // regular comment that is part of this total conversation. Have we seen it? If not, import it.
                $item_id = $item->get_id();
                $r = q("SELECT `last-child`, `edited` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($item_id));
                // FIXME update content if 'updated' changes
                if (count($r)) {
                    $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' LIMIT 1", intval($allow[0]['data']), dbesc(datetime_convert()), dbesc($item_id));
                    }
                    continue;
                }
                $datarray = get_atom_elements($item);
                $datarray['parent-uri'] = $parent_uri;
                $datarray['contact-id'] = $importer['id'];
                $r = post_remote($a, $datarray);
                // find out if our user is involved in this conversation and wants to be notified.
                if ($importer['notify-flags'] & NOTIFY_COMMENT) {
                    $myconv = q("SELECT `author-link` FROM `item` WHERE `parent-uri` = '%s'", dbesc($parent_uri));
                    if (count($myconv)) {
                        foreach ($myconv as $conv) {
                            if ($conv['author-link'] != $importer['url']) {
                                continue;
                            }
                            require_once 'bbcode.php';
                            $from = stripslashes($datarray['author-name']);
                            $tpl = file_get_contents('view/cmnt_received_eml.tpl');
                            $email_tpl = replace_macros($tpl, array('$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$username' => $importer['username'], '$email' => $importer['email'], '$from' => $from, '$body' => strip_tags(bbcode(stripslashes($datarray['body'])))));
                            $res = mail($importer['email'], $from . t(" commented on an item at ") . $a->config['sitename'], $email_tpl, t("From: Administrator@") . $a->get_hostname());
                            break;
                        }
                    }
                }
                continue;
            }
        } else {
            // Head post of a conversation. Have we seen it? If not, import it.
            $item_id = $item->get_id();
            $r = q("SELECT `last-child`, `edited` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($item_id));
            if (count($r)) {
                $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' LIMIT 1", intval($allow[0]['data']), dbesc(datetime_convert()), dbesc($item_id));
                }
                continue;
            }
            $datarray = get_atom_elements($item);
            $datarray['parent-uri'] = $item_id;
            $datarray['contact-id'] = $importer['id'];
            $r = post_remote($a, $datarray);
            continue;
        }
    }
    xml_status(0);
    killme();
}
示例#27
0
function kingRssOutput($data)
{
    $feed = new SimplePie();
    $feed->feed_url($data['rss_url']);
    $path = explode($_SERVER["SERVER_NAME"], get_bloginfo('wpurl'));
    $feed->cache_location($_SERVER['DOCUMENT_ROOT'] . $path[1] . "/wp-content/cache");
    if (!empty($data['cache_time'])) {
        $feed->max_minutes = $data['cache_time'];
    }
    if (!empty($data['nosort'])) {
        $feed->order_by_date = false;
    }
    if (!empty($data['stripads'])) {
        $feed->strip_ads(1);
    }
    $feed->bypass_image_hotlink();
    $feed->bypass_image_hotlink_page($path[1] . "/index.php");
    #if images in feed are protected
    $success = $feed->init();
    if ($success && $feed->data) {
        $output = '';
        $replace_title_vars[0] = $feed->get_feed_link();
        $replace_title_vars[1] = $feed->get_feed_title();
        $replace_title_vars[2] = $feed->get_feed_description();
        $replace_title_vars[3] = $data['rss_url'];
        $replace_title_vars[4] = get_settings('siteurl') . '/wp-content/plugins/king-framework/images/rss.png';
        if ($feed->get_image_exist() == true) {
            $replace_title_vars[5] = $feed->get_image_url();
        }
        $search_title_vars = array('%link%', '%title%', '%descr%', '%rssurl%', '%rssicon%', '%feedimg%');
        #parse template placeholders
        $output .= str_replace($search_title_vars, $replace_title_vars, $data['titlehtml']);
        $max = $feed->get_item_quantity();
        if (!empty($data['max_items'])) {
            $max = min($data['max_items'], $feed->get_item_quantity());
        }
        for ($x = 0; $x < $max; $x++) {
            $item = $feed->get_item($x);
            $replace_vars[0] = stupifyEntities($item->get_title());
            $replace_vars[1] = $item->get_permalink();
            $replace_vars[2] = $item->get_date($data['showdate']);
            $replace_vars[3] = stupifyEntities($item->get_description());
            if ($item->get_categories() != false) {
                $categories = $item->get_categories();
                $replace_vars[4] = implode(" | ", $categories);
            }
            if ($item->get_author(0) != false) {
                $author = $item->get_author(0);
                $replace_vars[5] = $author->get_name();
            }
            # cut article text to length ... do the butcher
            if (!empty($data['shortdesc'])) {
                $suffix = '...';
                $short_desc = trim(str_replace("\n", ' ', str_replace("\r", ' ', strip_tags(stupifyEntities($item->get_description())))));
                $desc = substr($short_desc, 0, $data['shortdesc']);
                $lastchar = substr($desc, -1, 1);
                if ($lastchar == '.' || $lastchar == '!' || $lastchar == '?') {
                    $suffix = '';
                }
                $desc .= $suffix;
                $replace_vars[3] = $desc;
            }
            $search_vars = array('%title%', '%link%', '%date%', '%text%', '%category%', '%author%');
            #parse template placeholders
            $output .= str_replace($search_vars, $replace_vars, $data['rsshtml']);
        }
    } else {
        if (!empty($data['error'])) {
            $output = $data['error'];
        } else {
            if (isset($feed->error)) {
                $output = $feed->error;
            }
        }
    }
    return $output;
}
示例#28
0
function local_delivery($importer, $data)
{
    $a = get_app();
    if ($importer['readonly']) {
        // We aren't receiving stuff from this person. But we will quietly ignore them
        // rather than a blatant "go away" message.
        logger('local_delivery: ignoring');
        return 0;
        //NOTREACHED
    }
    // Consume notification feed. This may differ from consuming a public feed in several ways
    // - might contain email or friend suggestions
    // - might contain remote followup to our message
    //		- in which case we need to accept it and then notify other conversants
    // - we may need to send various email notifications
    $feed = new SimplePie();
    $feed->set_raw_data($data);
    $feed->enable_order_by_date(false);
    $feed->init();
    $reloc = $feed->get_feed_tags(NAMESPACE_DFRN, 'relocate');
    if (isset($reloc[0]['child'][NAMESPACE_DFRN])) {
        $base = $reloc[0]['child'][NAMESPACE_DFRN];
        $newloc = array();
        $newloc['uid'] = $importer['importer_uid'];
        $newloc['cid'] = $importer['id'];
        $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
        $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
        $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
        $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
        $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
        $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
        $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
        $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
        $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
        $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
        // TODO
        // merge with current record, current contents have priority
        // update record, set url-updated
        // update profile photos
        // schedule a scan?
    }
    // handle friend suggestion notification
    $sugg = $feed->get_feed_tags(NAMESPACE_DFRN, 'suggest');
    if (isset($sugg[0]['child'][NAMESPACE_DFRN])) {
        $base = $sugg[0]['child'][NAMESPACE_DFRN];
        $fsugg = array();
        $fsugg['uid'] = $importer['importer_uid'];
        $fsugg['cid'] = $importer['id'];
        $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
        $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
        $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
        $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
        $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
        // Does our member already have a friend matching this description?
        $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1", dbesc($fsugg['name']), dbesc(normalise_link($fsugg['url'])), intval($fsugg['uid']));
        if (count($r)) {
            return 0;
        }
        // Do we already have an fcontact record for this person?
        $fid = 0;
        $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1", dbesc($fsugg['url']), dbesc($fsugg['name']), dbesc($fsugg['request']));
        if (count($r)) {
            $fid = $r[0]['id'];
        }
        if (!$fid) {
            $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ", dbesc($fsugg['name']), dbesc($fsugg['url']), dbesc($fsugg['photo']), dbesc($fsugg['request']));
        }
        $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1", dbesc($fsugg['url']), dbesc($fsugg['name']), dbesc($fsugg['request']));
        if (count($r)) {
            $fid = $r[0]['id'];
        } else {
            return 0;
        }
        $hash = random_string();
        $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )\n\t\t\tVALUES( %d, %d, %d, '%s', '%s', '%s', %d )", intval($fsugg['uid']), intval($fid), intval($fsugg['cid']), dbesc($fsugg['body']), dbesc($hash), dbesc(datetime_convert()), intval(0));
        // TODO - send email notify (which may require a new notification preference)
        return 0;
    }
    $ismail = false;
    $rawmail = $feed->get_feed_tags(NAMESPACE_DFRN, 'mail');
    if (isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
        logger('local_delivery: private message received');
        $ismail = true;
        $base = $rawmail[0]['child'][NAMESPACE_DFRN];
        $msg = array();
        $msg['uid'] = $importer['importer_uid'];
        $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
        $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
        $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
        $msg['contact-id'] = $importer['id'];
        $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
        $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
        $msg['seen'] = 0;
        $msg['replied'] = 0;
        $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
        $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
        $msg['created'] = datetime_convert(notags(unxmlify('UTC', 'UTC', $base['sentdate'][0]['data'])));
        dbesc_array($msg);
        $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) . "`) VALUES ('" . implode("', '", array_values($msg)) . "')");
        // send email notification if requested.
        require_once 'bbcode.php';
        if ($importer['notify-flags'] & NOTIFY_MAIL) {
            push_lang($importer['language']);
            // name of the automated email sender
            $msg['notificationfromname'] = t('Administrator');
            // noreply address to send from
            $msg['notificationfromemail'] = t('noreply') . '@' . $a->get_hostname();
            // text version
            // process the message body to display properly in text mode
            // 		1) substitute a \n character for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
            //		2) remove escape slashes
            //		3) decode any bbcode from the message editor
            //		4) decode any encoded html tags
            //		5) remove html tags
            $msg['textversion'] = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n", $msg['body']))), ENT_QUOTES, 'UTF-8'));
            // html version
            // process the message body to display properly in text mode
            // 		1) substitute a <br /> tag for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
            //		2) remove escape slashes
            //		3) decode any bbcode from the message editor
            //		4) decode any encoded html tags
            $msg['htmlversion'] = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"), "<br />\n", $msg['body']))));
            // load the template for private message notifications
            $tpl = get_intltext_template('mail_received_html_body_eml.tpl');
            $email_html_body_tpl = replace_macros($tpl, array('$username' => $importer['username'], '$siteName' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$thumb' => $importer['thumb'], '$email' => $importer['email'], '$url' => $importer['url'], '$from' => $msg['from-name'], '$title' => stripslashes($msg['title']), '$htmlversion' => $msg['htmlversion'], '$mimeboundary' => $msg['mimeboundary'], '$hostname' => $a->get_hostname()));
            // load the template for private message notifications
            $tpl = get_intltext_template('mail_received_text_body_eml.tpl');
            $email_text_body_tpl = replace_macros($tpl, array('$username' => $importer['username'], '$siteName' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$thumb' => $importer['thumb'], '$email' => $importer['email'], '$url' => $importer['url'], '$from' => $msg['from-name'], '$title' => stripslashes($msg['title']), '$textversion' => $msg['textversion'], '$mimeboundary' => $msg['mimeboundary'], '$hostname' => $a->get_hostname()));
            // use the EmailNotification library to send the message
            require_once "include/EmailNotification.php";
            EmailNotification::sendTextHtmlEmail($msg['notificationfromname'], $msg['notificationfromemail'], $msg['notificationfromemail'], $importer['email'], t('New mail received at ') . $a->config['sitename'], $email_html_body_tpl, $email_text_body_tpl);
            pop_lang();
        }
        return 0;
        // NOTREACHED
    }
    logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
    // process any deleted entries
    $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
    if (is_array($del_entries) && count($del_entries)) {
        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) {
                $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 LIMIT 1", dbesc($uri), intval($importer['importer_uid']), intval($importer['id']));
                if (count($r)) {
                    $item = $r[0];
                    if ($item['deleted']) {
                        continue;
                    }
                    logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
                    if ($item['verb'] === ACTIVITY_TAG && $item['object-type'] === ACTVITY_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\tWHERE `parent-uri` = '%s' AND `uid` = %d", dbesc($when), dbesc(datetime_convert()), dbesc($item['uri']), intval($importer['importer_uid']));
                    } else {
                        $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' \n\t\t\t\t\t\t\tWHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($when), dbesc(datetime_convert()), dbesc($uri), intval($importer['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 `uid` = %d\n\t\t\t\t\t\t\t\tORDER BY `created` DESC LIMIT 1", dbesc($item['parent-uri']), intval($importer['importer_uid']));
                            if (count($r)) {
                                q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1", intval($r[0]['id']));
                            }
                        }
                    }
                }
            }
        }
    }
    foreach ($feed->get_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) {
            $community = false;
            if ($importer['page-flags'] == PAGE_COMMUNITY) {
                $sql_extra = '';
                $community = true;
                logger('local_delivery: community reply');
            } else {
                $sql_extra = " and contact.self = 1 and item.wall = 1 ";
            }
            // was the top-level post for this reply written by somebody on this site?
            // Specifically, the recipient?
            $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, \n\t\t\t\t`contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item` \n\t\t\t\tLEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id` \n\t\t\t\tWHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'\n\t\t\t\tAND `item`.`uid` = %d \n\t\t\t\t{$sql_extra}\n\t\t\t\tLIMIT 1", dbesc($parent_uri), dbesc($parent_uri), intval($importer['importer_uid']));
            if ($r && count($r)) {
                logger('local_delivery: received remote comment');
                $is_like = false;
                // remote reply to our post. Import and then notify everybody else.
                $datarray = get_atom_elements($feed, $item);
                // TODO: make this next part work against both delivery threads of a community post
                //				if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
                //					logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
                // they won't know what to do so don't report an error. Just quietly die.
                //					return 0;
                //				}
                $datarray['type'] = 'remote-comment';
                $datarray['wall'] = 1;
                $datarray['parent-uri'] = $parent_uri;
                $datarray['uid'] = $importer['importer_uid'];
                $datarray['owner-name'] = $r[0]['name'];
                $datarray['owner-link'] = $r[0]['url'];
                $datarray['owner-avatar'] = $r[0]['thumb'];
                $datarray['contact-id'] = $importer['id'];
                if ($datarray['verb'] === ACTIVITY_LIKE || $datarray['verb'] === ACTIVITY_DISLIKE) {
                    $is_like = true;
                    $datarray['type'] = 'activity';
                    $datarray['gravity'] = GRAVITY_LIKE;
                    $datarray['last-child'] = 0;
                }
                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 && $xt->id == $r[0]['uri']) {
                        // extract tag, if not duplicate, and this user allows tags, add to parent item
                        if ($xo->id && $xo->content) {
                            $newtag = '#[url=' . $xo->id . ']' . $xo->content . '[/url]';
                            if (!stristr($r[0]['tag'], $newtag)) {
                                $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1", intval($importer['importer_uid']));
                                if (count($i) && !$i[0]['blocktags']) {
                                    q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1", dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag), intval($r[0]['id']));
                                }
                            }
                        }
                    }
                }
                // 				if($community) {
                //					$newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
                //					if(! stristr($datarray['tag'],$newtag)) {
                //						if(strlen($datarray['tag']))
                //							$datarray['tag'] .= ',';
                //						$datarray['tag'] .= $newtag;
                //					}
                //				}
                $posted_id = item_store($datarray);
                $parent = 0;
                if ($posted_id) {
                    $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($posted_id), intval($importer['importer_uid']));
                    if (count($r)) {
                        $parent = $r[0]['parent'];
                    }
                    if (!$is_like) {
                        $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d", dbesc(datetime_convert()), intval($importer['importer_uid']), intval($r[0]['parent']));
                        $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1", dbesc(datetime_convert()), intval($importer['importer_uid']), intval($posted_id));
                    }
                    if ($posted_id && $parent) {
                        proc_run('php', "include/notifier.php", "comment-import", "{$posted_id}");
                        if (!$is_like && $importer['notify-flags'] & NOTIFY_COMMENT && !$importer['self']) {
                            push_lang($importer['language']);
                            require_once 'bbcode.php';
                            $from = stripslashes($datarray['author-name']);
                            // name of the automated email sender
                            $msg['notificationfromname'] = stripslashes($datarray['author-name']);
                            // noreply address to send from
                            $msg['notificationfromemail'] = t('noreply') . '@' . $a->get_hostname();
                            // text version
                            // process the message body to display properly in text mode
                            $msg['textversion'] = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
                            // html version
                            // process the message body to display properly in text mode
                            $msg['htmlversion'] = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"), "<br />\n", $datarray['body']))));
                            $imgtouse = link_compare($datarray['author-link'], $importer['url']) ? $importer['thumb'] : $datarray['author-avatar'];
                            // load the template for private message notifications
                            $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
                            $email_html_body_tpl = replace_macros($tpl, array('$username' => $importer['username'], '$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$thumb' => $imgtouse, '$email' => $importer['email'], '$url' => $datarray['author-link'], '$from' => $from, '$body' => $msg['htmlversion'], '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id));
                            // load the template for private message notifications
                            $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
                            $email_text_body_tpl = replace_macros($tpl, array('$username' => $importer['username'], '$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$thumb' => $imgtouse, '$email' => $importer['email'], '$url' => $datarray['author-link'], '$from' => $from, '$body' => $msg['textversion'], '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id));
                            // use the EmailNotification library to send the message
                            require_once "include/EmailNotification.php";
                            EmailNotification::sendTextHtmlEmail($msg['notificationfromname'], t("Administrator") . '@' . $a->get_hostname(), t("noreply") . '@' . $a->get_hostname(), $importer['email'], sprintf(t('%s commented on an item at %s'), $from, $a->config['sitename']), $email_html_body_tpl, $email_text_body_tpl);
                            pop_lang();
                        }
                    }
                    return 0;
                    // NOTREACHED
                }
            } else {
                // regular comment that is part of this total conversation. Have we seen it? If not, import it.
                $item_id = $item->get_id();
                $datarray = get_atom_elements($feed, $item);
                $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['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 `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($datarray['body']), dbesc(datetime_convert('UTC', 'UTC', $datarray['edited'])), dbesc($item_id), intval($importer['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['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['importer_uid']));
                    }
                    continue;
                }
                $datarray['parent-uri'] = $parent_uri;
                $datarray['uid'] = $importer['importer_uid'];
                $datarray['contact-id'] = $importer['id'];
                if ($datarray['verb'] == ACTIVITY_LIKE || $datarray['verb'] == ACTIVITY_DISLIKE) {
                    $datarray['type'] = 'activity';
                    $datarray['gravity'] = GRAVITY_LIKE;
                }
                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->content) {
                            if (!stristr($r[0]['tag'], trim($xo->content))) {
                                q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1", dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']' . $xo->content . '[/url]'), intval($r[0]['id']));
                            }
                        }
                    }
                }
                $posted_id = item_store($datarray);
                // find out if our user is involved in this conversation and wants to be notified.
                if ($datarray['type'] != 'activity' && $importer['notify-flags'] & NOTIFY_COMMENT) {
                    $myconv = q("SELECT `author-link`, `author-avatar` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ", dbesc($parent_uri), intval($importer['importer_uid']));
                    if (count($myconv)) {
                        $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
                        foreach ($myconv as $conv) {
                            if (!link_compare($conv['author-link'], $importer_url)) {
                                continue;
                            }
                            push_lang($importer['language']);
                            require_once 'bbcode.php';
                            $from = stripslashes($datarray['author-name']);
                            // name of the automated email sender
                            $msg['notificationfromname'] = stripslashes($datarray['author-name']);
                            // noreply address to send from
                            $msg['notificationfromemail'] = t('noreply') . '@' . $a->get_hostname();
                            // text version
                            // process the message body to display properly in text mode
                            $msg['textversion'] = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
                            // html version
                            // process the message body to display properly in text mode
                            $msg['htmlversion'] = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n\\n", "\\n"), "<br />\n", $datarray['body']))));
                            $imgtouse = link_compare($datarray['author-link'], $importer['url']) ? $importer['thumb'] : $datarray['author-avatar'];
                            // load the template for private message notifications
                            $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
                            $email_html_body_tpl = replace_macros($tpl, array('$username' => $importer['username'], '$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$thumb' => $imgtouse, '$url' => $datarray['author-link'], '$from' => $from, '$body' => $msg['htmlversion'], '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id));
                            // load the template for private message notifications
                            $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
                            $email_text_body_tpl = replace_macros($tpl, array('$username' => $importer['username'], '$sitename' => $a->config['sitename'], '$siteurl' => $a->get_baseurl(), '$thumb' => $imgtouse, '$url' => $datarray['author-link'], '$from' => $from, '$body' => $msg['textversion'], '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id));
                            // use the EmailNotification library to send the message
                            require_once "include/EmailNotification.php";
                            EmailNotification::sendTextHtmlEmail($msg['notificationfromname'], t("Administrator@") . $a->get_hostname(), t("noreply") . '@' . $a->get_hostname(), $importer['email'], sprintf(t('%s commented on an item at %s'), $from, $a->config['sitename']), $email_html_body_tpl, $email_text_body_tpl);
                            pop_lang();
                            break;
                        }
                    }
                }
                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 (x($datarray, 'object-type') && $datarray['object-type'] === ACTIVITY_OBJ_EVENT) {
                $ev = bbtoevent($datarray['body']);
                if (x($ev, 'desc') && x($ev, 'start')) {
                    $ev['cid'] = $importer['id'];
                    $ev['uid'] = $importer['uid'];
                    $ev['uri'] = $item_id;
                    $ev['edited'] = $datarray['edited'];
                    $ev['private'] = $datarray['private'];
                    $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['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 `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($datarray['body']), dbesc(datetime_convert('UTC', 'UTC', $datarray['edited'])), dbesc($item_id), intval($importer['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['importer_uid']));
                }
                continue;
            }
            // 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['importer_uid'];
            $datarray['contact-id'] = $importer['id'];
            $r = item_store($datarray);
            continue;
        }
    }
    return 0;
    // NOTREACHED
}
示例#29
0
<?php 
global $CONFIG;
if (!class_exists('SimplePie')) {
    require_once $CONFIG->pluginspath . '/simplepie/simplepie.inc';
}
$blog_tags = '<a><p><br><b><i><em><del><pre><strong><ul><ol><li>';
$feed_url = $vars['entity']->feed_url;
if ($feed_url) {
    $excerpt = $vars['entity']->excerpt;
    $num_items = $vars['entity']->num_items;
    $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>
示例#30
0
function salmon_post(&$a)
{
    $xml = file_get_contents('php://input');
    logger('mod-salmon: new salmon ' . $xml, LOGGER_DATA);
    $nick = $a->argc > 1 ? notags(trim($a->argv[1])) : '';
    $mentions = $a->argc > 2 && $a->argv[2] === 'mention' ? true : false;
    $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' AND `account_expired` = 0 AND `account_removed` = 0 LIMIT 1", dbesc($nick));
    if (!count($r)) {
        http_status_exit(500);
    }
    $importer = $r[0];
    // parse the xml
    $dom = simplexml_load_string($xml, 'SimpleXMLElement', 0, NAMESPACE_SALMON_ME);
    // figure out where in the DOM tree our data is hiding
    if ($dom->provenance->data) {
        $base = $dom->provenance;
    } elseif ($dom->env->data) {
        $base = $dom->env;
    } elseif ($dom->data) {
        $base = $dom;
    }
    if (!$base) {
        logger('mod-salmon: unable to locate salmon data in xml ');
        http_status_exit(400);
    }
    // Stash the signature away for now. We have to find their key or it won't be good for anything.
    $signature = base64url_decode($base->sig);
    // unpack the  data
    // strip whitespace so our data element will return to one big base64 blob
    $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
    // stash away some other stuff for later
    $type = $base->data[0]->attributes()->type[0];
    $keyhash = $base->sig[0]->attributes()->keyhash[0];
    $encoding = $base->encoding;
    $alg = $base->alg;
    // Salmon magic signatures have evolved and there is no way of knowing ahead of time which
    // flavour we have. We'll try and verify it regardless.
    $stnet_signed_data = $data;
    $signed_data = $data . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
    $compliant_format = str_replace('=', '', $signed_data);
    // decode the data
    $data = base64url_decode($data);
    // Remove the xml declaration
    $data = preg_replace('/\\<\\?xml[^\\?].*\\?\\>/', '', $data);
    // Create a fake feed wrapper so simplepie doesn't choke
    $tpl = get_markup_template('fake_feed.tpl');
    $base = substr($data, strpos($data, '<entry'));
    $feedxml = $tpl . $base . '</feed>';
    logger('mod-salmon: Processed feed: ' . $feedxml);
    // Now parse it like a normal atom feed to scrape out the author URI
    $feed = new SimplePie();
    $feed->set_raw_data($feedxml);
    $feed->enable_order_by_date(false);
    $feed->init();
    logger('mod-salmon: Feed parsed.');
    if ($feed->get_item_quantity()) {
        foreach ($feed->get_items() as $item) {
            $author = $item->get_author();
            $author_link = unxmlify($author->get_link());
            break;
        }
    }
    if (!$author_link) {
        logger('mod-salmon: Could not retrieve author URI.');
        http_status_exit(400);
    }
    // Once we have the author URI, go to the web and try to find their public key
    logger('mod-salmon: Fetching key for ' . $author_link);
    $key = get_salmon_key($author_link, $keyhash);
    if (!$key) {
        logger('mod-salmon: Could not retrieve author key.');
        http_status_exit(400);
    }
    $key_info = explode('.', $key);
    $m = base64url_decode($key_info[1]);
    $e = base64url_decode($key_info[2]);
    logger('mod-salmon: key details: ' . print_r($key_info, true), LOGGER_DEBUG);
    $pubkey = metopem($m, $e);
    // We should have everything we need now. Let's see if it verifies.
    $verify = rsa_verify($compliant_format, $signature, $pubkey);
    if (!$verify) {
        logger('mod-salmon: message did not verify using protocol. Trying padding hack.');
        $verify = rsa_verify($signed_data, $signature, $pubkey);
    }
    if (!$verify) {
        logger('mod-salmon: message did not verify using padding. Trying old statusnet hack.');
        $verify = rsa_verify($stnet_signed_data, $signature, $pubkey);
    }
    if (!$verify) {
        logger('mod-salmon: Message did not verify. Discarding.');
        http_status_exit(400);
    }
    logger('mod-salmon: Message verified.');
    /*
     *
     * If we reached this point, the message is good. Now let's figure out if the author is allowed to send us stuff.
     *
     */
    $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND ( `url` = '%s' OR `alias` = '%s' ) \n\t\tAND `uid` = %d LIMIT 1", dbesc(NETWORK_OSTATUS), dbesc($author_link), dbesc($author_link), intval($importer['uid']));
    if (!count($r)) {
        logger('mod-salmon: Author unknown to us.');
        if (get_pconfig($importer['uid'], 'system', 'ostatus_autofriend')) {
            require_once 'include/follow.php';
            $result = new_contact($importer['uid'], $author_link);
            if ($result['success']) {
                $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND ( `url` = '%s' OR `alias` = '%s' ) \n\t\t\t\t\tAND `uid` = %d LIMIT 1", dbesc(NETWORK_OSTATUS), dbesc($author_link), dbesc($author_link), intval($importer['uid']));
            }
        }
    }
    // is this a follower? Or have we ignored the person?
    // If so we can not accept this post.
    if (count($r) && ($r[0]['readonly'] || $r[0]['rel'] == CONTACT_IS_FOLLOWER || $r[0]['blocked'])) {
        logger('mod-salmon: Ignoring this author.');
        http_status_exit(202);
        // NOTREACHED
    }
    require_once 'include/items.php';
    // Placeholder for hub discovery. We shouldn't find any hubs
    // since we supplied the fake feed header - and it doesn't have any.
    $hub = '';
    /**
     *
     * anti-spam measure: consume_feed will accept a follow activity from 
     * this person (and nothing else) if there is no existing contact record.
     *
     */
    $contact_rec = count($r) ? $r[0] : null;
    consume_feed($feedxml, $importer, $contact_rec, $hub);
    http_status_exit(200);
}