enable_order_by_date() public method

Set whether feed items should be sorted into reverse chronological order
public enable_order_by_date ( boolean $enable = true )
$enable boolean Sort as reverse chronological order.
function tweetimport_import_twitter_feed($twitter_account)
{
  require_once (ABSPATH . WPINC . '/class-feed.php');

  $feed = new SimplePie();

  $account_parts = explode ('/', $twitter_account['twitter_name'], 2);



  if ($twitter_account['account_type'] == 1): //Account is Favorites
    $feed->set_feed_url(str_replace('#=#USER#=#', $account_parts[0], TWEETIMPORT_API_FAVORITES_URL));
  elseif ($twitter_account['account_type'] == 0 && count($account_parts) == 1): //User timeline
      $feed->set_feed_url(str_replace('#=#USER#=#', $account_parts[0], TWEETIMPORT_API_USER_TIMELINE_URL));
  elseif ($twitter_account['account_type'] == 2 && count($account_parts) == 2): //Account is list
      $feed_url = str_replace('#=#USER#=#', $account_parts[0], TWEETIMPORT_API_LIST_URL);
      $feed_url = str_replace('#=#LIST#=#', $account_parts[1], $feed_url);
      $feed->set_feed_url($feed_url);
  else :
      return '<strong>ERROR: Account information not correct. Account type wrong?</strong>';
  endif;

  $feed->set_useragent('Tweet Import http://skinju.com/wordpress/tweetimport');
  $feed->set_cache_class('WP_Feed_Cache');
  $feed->set_file_class('WP_SimplePie_File');
  $feed->enable_cache(true);
  $feed->set_cache_duration (apply_filters('tweetimport_cache_duration', 880));
  $feed->enable_order_by_date(false);
  $feed->init();
  $feed->handle_content_type();

  if ($feed->error()):
   return '<strong>ERROR: Feed Reading Error.</strong>';
  endif;

  $rss_items = $feed->get_items();

  $imported_count = 0;
  foreach ($rss_items as $item)
  {
    $item = apply_filters ('tweetimport_tweet_before_new_post', $item); //return false to stop processing an item.
    if (!$item) continue;

    $processed_description = $item->get_description();

    //Get the twitter author from the beginning of the tweet text
    $twitter_author = trim(preg_replace("~^(\w+):(.*?)$~", "\\1", $processed_description));

    if ($twitter_account['strip_name'] == 1):
      $processed_description = preg_replace("~^(\w+):(.*?)~i", "\\2", $processed_description);
    endif;

    if ($twitter_account['names_clickable'] == 1):
      $processed_description = preg_replace("~@(\w+)~", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $processed_description);
      $processed_description = preg_replace("~^(\w+):~", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>:", $processed_description);
    endif;

    if ($twitter_account['hashtags_clickable'] == 1):
      if ($twitter_account['hashtags_clickable_twitter'] == 1):
          $processed_description = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $processed_description);
      else:
        $processed_description = preg_replace("/#(\w+)/", "<a href=\"" . skinju_get_tag_link("\\1") . "\">#\\1</a>", $processed_description);
      endif;
    endif;

  $processed_description = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $processed_description);
  $processed_description = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $processed_description);

    $new_post = array('post_title' => trim (substr (preg_replace("~{$account_parts[0]}: ~i", "", $item->get_title()), 0, 25) . '...'),
                      'post_content' => trim ($processed_description),
                      'post_date' => $item->get_date('Y-m-d H:i:s'),
                      'post_author' => $twitter_account['author'],
                      'post_category' => array($twitter_account['category']),
                      'post_status' => 'publish');

    $new_post = apply_filters('tweetimport_new_post_before_create', $new_post); // Offer the chance to manipulate new post data. return false to skip
    if (!$new_post) continue;
    $new_post_id = wp_insert_post($new_post);

    $imported_count++;

    add_post_meta ($new_post_id, 'tweetimport_twitter_author', $twitter_author, true); 
    add_post_meta ($new_post_id, 'tweetimport_date_imported', date ('Y-m-d H:i:s'), true);
    add_post_meta ($new_post_id, 'tweetimport_twitter_id', $item->get_id(), true);
    add_post_meta ($new_post_id, 'tweetimport_twitter_id', $item->get_id(), true);
    add_post_meta ($new_post_id, '_tweetimport_twitter_id_hash', $item->get_id(true), true);
    add_post_meta ($new_post_id, 'tweetimport_twitter_post_uri', $item->get_link(0));
    add_post_meta ($new_post_id, 'tweetimport_author_avatar', $item->get_link(0, 'image'));

    preg_match_all ('~#([A-Za-z0-9_]+)(?=\s|\Z)~', $item->get_description(), $out);
    if ($twitter_account['add_tag']) $out[0][] = $twitter_account['add_tag'];
    wp_set_post_tags($new_post_id, implode (',', $out[0]));
  }

  return $imported_count;
}
Beispiel #2
0
 public static function simplepie($feed_url = NULL)
 {
     if (!$feed_url) {
         return false;
     }
     $data = new SimplePie();
     //*******************************
     // Convert To GeoRSS feed
     // To Disable Uncomment these 3 lines
     //*******************************
     $geocoder = new Geocoder();
     $georss_feed = $geocoder->geocode_feed($feed_url);
     if ($georss_feed == false or empty($georss_feed)) {
         // Our RSS feed pull failed, so let's grab the original RSS feed
         $data->set_feed_url($feed_url);
     } else {
         // Converting our feed to GeoRSS was successful, use that data
         $data->set_raw_data($georss_feed);
     }
     // Uncomment Below to disable geocoding
     //$data->set_feed_url( $feed_url );
     //*******************************
     $data->enable_cache(false);
     $data->enable_order_by_date(true);
     $data->init();
     $data->handle_content_type();
     return $data;
 }
 /**
  * _createSimplePie
  *
  * @param   string  &$feed  Params
  *
  * @return	object
  */
 private function _createSimplePie(&$feed)
 {
     include_once JPATH_AUTOTWEET . '/libs/SimplePie_autoloader.php';
     // Process the feed with SimplePie
     $simplePie = new SimplePie();
     $simplePie->set_feed_url($feed->xtform->get('url'));
     $simplePie->set_stupidly_fast(true);
     $simplePie->enable_order_by_date(true);
     if ($feed->xtform->get('encoding', 'utf-8')) {
         $simplePie->set_input_encoding($feed->xtform->get('encoding'));
     }
     if ($feed->xtform->get('force_fsockopen')) {
         $simplePie->force_fsockopen(true);
     }
     $use_sp_cache = EParameter::getComponentParam(CAUTOTWEETNG, 'use_sp_cache', true);
     if ($use_sp_cache && is_writable(JPATH_CACHE)) {
         $simplePie->set_cache_location(JPATH_CACHE);
         $simplePie->enable_cache(true);
     } else {
         $simplePie->enable_cache(false);
     }
     $set_sp_timeout = EParameter::getComponentParam(CAUTOTWEETNG, 'set_sp_timeout', 10);
     if ($set_sp_timeout) {
         $simplePie->set_timeout((int) $set_sp_timeout);
     }
     $simplePie->init();
     return $simplePie;
 }
Beispiel #4
0
 private function get_feed($feed_url)
 {
     $feed = new SimplePie();
     $feed->set_feed_url($feed_url);
     $feed->enable_order_by_date(true);
     $feed->set_item_limit(3);
     $feed->init();
     $feed->handle_content_type();
     return $feed;
 }
Beispiel #5
0
 function fetchRss($url)
 {
     $feed = new SimplePie();
     $feed->set_feed_url($url);
     $feed->set_output_encoding("UTF-8");
     $feed->enable_order_by_date(false);
     $feed->set_cache_location(Configure::read('Rss.cache_path'));
     $feed->init();
     return $feed->get_items();
 }
 public function getFeed($refresh = false)
 {
     require_once dirname(__FILE__) . "/../../autoloader.php";
     $feed = new SimplePie();
     $url = "http://www.pinterest.com/taivasogilvy/feed.rss";
     $feed->set_feed_url($url);
     if ($refresh) {
         $feed->enable_cache(false);
     } else {
         $feed->set_cache_location($this->config->cacheFolder);
         $feed->set_cache_duration($this->config->cacheTime);
     }
     $feed->enable_order_by_date(false);
     $feed->init();
     $feed->handle_content_type();
     if ($feed->error()) {
         return false;
     } else {
         return $feed;
     }
 }
Beispiel #7
0
 private function getFeedByUrl($url)
 {
     // Create a new instance of the SimplePie object
     $feed = new \SimplePie();
     // Set feed
     $feed->set_feed_url($url);
     // Allow us to change the input encoding from the URL string if we want to. (optional)
     if (!empty($_GET['input'])) {
         $feed->set_input_encoding($_GET['input']);
     }
     // Allow us to choose to not re-order the items by date. (optional)
     if (!empty($_GET['orderbydate']) && $_GET['orderbydate'] == 'false') {
         $feed->enable_order_by_date(false);
     }
     // Trigger force-feed
     if (!empty($_GET['force']) && $_GET['force'] == 'true') {
         $feed->force_feed(true);
     }
     $feed->set_cache_location(dirname(__FILE__) . '/../cache/');
     $feed->init();
     return $feed->get_items(0, 10);
 }
Beispiel #8
0
 public static function simplepie($feed_url = NULL)
 {
     if (!$feed_url) {
         return false;
     }
     $data = new SimplePie();
     //*******************************
     // Convert To GeoRSS feed
     // To Disable Uncomment these 3 lines
     //*******************************
     $geocoder = new Geocoder();
     $georss_feed = $geocoder->geocode_feed($feed_url);
     $data->set_raw_data($georss_feed);
     // Uncomment Below to disable geocoding
     //$data->set_feed_url( $feed_url );
     //*******************************
     $data->enable_cache(false);
     $data->enable_order_by_date(true);
     $data->init();
     $data->handle_content_type();
     return $data;
 }
 public function getFeed($refresh = false)
 {
     require_once dirname(__FILE__) . "/../../autoloader.php";
     $feed = new SimplePie();
     $url = "http://taivasfi.blogspot.fi/feeds/posts/default";
     $url = "http://blogi.taivas.fi/?feed=rss2";
     $feed->set_feed_url($url);
     if ($refresh) {
         $feed->enable_cache(false);
     } else {
         $feed->set_cache_location($this->config->cacheFolder);
         $feed->set_cache_duration($this->config->cacheTime);
     }
     $feed->enable_order_by_date(false);
     $feed->init();
     $feed->handle_content_type();
     if ($feed->error()) {
         return false;
     } else {
         return $feed;
     }
 }
 /**
  * Opens an RSS feed, parses and loads the contents.
  *
  * @param string $url         The URL of the RSS feed
  * @param bool   $nativeOrder If true, disable order by date to preserve native ordering
  * @param bool   $force       Force SimplePie to parse the feed despite errors
  *
  * @return object An object that encapsulates the feed contents and operations on those contents.
  * @throws FeedParserException If opening or parsing feed fails
  **/
 public function parseFeed($url, $nativeOrder = false, $force = false)
 {
     require_once PATH_SYSTEM . '/vendors/SimplePie.php';
     $feed = new SimplePie();
     $feed->set_timeout($this->timeout);
     $feed->set_feed_url($url);
     $feed->enable_order_by_date(!$nativeOrder);
     $feed->force_feed($force);
     if ($this->cacheDuration != null) {
         $feed->set_cache_duration(intval($this->cacheDuration));
     }
     if ($this->cacheDirectory != null) {
         $feed->set_cache_location($this->cacheDirectory);
     }
     if ($this->stripHtmlTags != null) {
         $feed->strip_htmltags($this->stripHtmlTags);
     }
     @$feed->init();
     if ($err = $feed->error()) {
         throw new FeedParserException($err);
     }
     return $feed;
 }
Beispiel #11
0
 function getEvents(&$params)
 {
     jimport('simplepie.simplepie');
     $id = $params->get('google_gid', '');
     $starttime = $params->get('google_orderby', 'starttime');
     $query = '?singleevents=true&orderby=' . $starttime . '&sortorder=a&max-results=' . $params->get('google_maxresults', 25);
     if ($params->get('time_range') != 'time_span' && $params->get('rangespan') == 'all_events') {
         $query .= '&futureevents=true';
     } else {
         $startMin = $params->get('startmin');
         $query .= "&start-min=" . $startMin;
         $startMax = $params->get('startmax', false);
         if ($startMax !== false) {
             $query .= "&start-max=" . $startMax;
         }
     }
     $rss = new SimplePie('http://www.google.com/calendar/feeds/' . $id . '/public/full' . $query, JPATH_CACHE, $params->get('google_gcache', 3600));
     $rss->enable_order_by_date(false);
     $events = array();
     if ($rss->error) {
         return $events['error'] = $rss->error;
     }
     $items = $rss->get_items();
     foreach ($items as $item) {
         $when = $item->get_item_tags('http://schemas.google.com/g/2005', 'when');
         $link = $params->get('google_links') != 'link_no' ? array('internal' => $params->get('google_links') == 'link_internal' ? true : false, 'link' => $item->get_link()) : false;
         $event = new RokMiniEvents_Event($when[0]['attribs']['']['startTime'], $when[0]['attribs']['']['endTime'], $item->get_title(), $item->get_content(), $link);
         $startTime = $when[0]['attribs']['']['startTime'];
         $endTime = $when[0]['attribs']['']['endTime'];
         if (preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $startTime)) {
             $event->setAllDay(true);
         }
         $events[] = $event;
     }
     return $events;
 }
Beispiel #12
0
The next generation plug-ins now available for testing offer higher performance 
data export. In contrast to the existing COLLADA exporters, these new plug-ins 
do not store the COLLADA document into an intermediate data model but write it 
directly to file. This leads to a dramatic reduction of memory consumption and 
to much better performance.
</p>
<p>
If you find any bugs or experience any problem please write a bug report on
the source forge bug tracker.
</p>
							
							<?php 
$projsummary = new SimplePie();
$projsummary->enable_cache(false);
$projsummary->set_feed_url('http://sourceforge.net/export/rss2_projsummary.php?group_id=136478');
$projsummary->enable_order_by_date(false);
$projsummary->init();
$projsummary->handle_content_type();
if ($projsummary->data) {
    ?>
							
							<div class="psum">
							<p>
							    <?php 
    foreach ($projsummary->get_items() as $item) {
        ?>
								   <?php 
        list($eins, $zwei) = split(':', $item->get_title());
        echo '<strong>' . $eins . ': </strong>';
        echo '<a href="' . $item->get_permalink() . '">' . $zwei . '</a>';
        ?>
Beispiel #13
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);
 }
 /**
  * Parses a feed with SimplePie
  *
  * @param   boolean     $stupidly_fast    Set fast mode. Best for checks
  * @param   integer     $max              Limit of items to fetch
  * @return  SimplePie_Item    Feed object
  **/
 function fetchFeed($url, $stupidly_fast = false, $max = 0)
 {
     # SimplePie
     if (!class_exists('SimplePie')) {
         require_once WPOINC . 'simplepie/simplepie.class.php';
     }
     $feed = new SimplePie();
     $feed->enable_order_by_date(false);
     // thanks Julian Popov
     $feed->set_feed_url($url);
     $feed->set_item_limit($max);
     $feed->set_stupidly_fast($stupidly_fast);
     $feed->enable_cache(false);
     $feed->init();
     $feed->handle_content_type();
     return $feed;
 }
Beispiel #15
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
}
Beispiel #16
0
function updateRSS()
{
    $db = DBCxn::get();
    $selectRSS = $db->query("SELECT id, rssLink, updateMd5 FROM rss");
    $selectRSS->setFetchMode(PDO::FETCH_ASSOC);
    $selectRSS = $selectRSS->fetchAll();
    //构建分析
    $feed = new SimplePie();
    $feed->enable_order_by_date(false);
    $feed->enable_cache(true);
    $feed->set_useragent('Mozilla/4.0 ' . SIMPLEPIE_USERAGENT);
    $feed->set_cache_location($_SERVER['DOCUMENT_ROOT'] . '/cache');
    //拿出每个RSS调用分析函数
    foreach ($selectRSS as $rows) {
        $rssId = $rows['id'];
        //博客ID
        $updateMd5 = $rows['updateMd5'];
        //最后更新记录的md5值
        $feed->set_feed_url($rows['rssLink']);
        //feed地址做参数进行解析操作
        $feed->set_timeout(30);
        $feed->init();
        //如果feed出错,执行下一个
        if ($feed->error()) {
            continue;
        }
        readRSS($rssId, $updateMd5, $feed);
    }
    return true;
}
function feedzy_rss($atts, $content = '')
{
    global $feedzyStyle;
    $feedzyStyle = true;
    $count = 0;
    //Load SimplePie if not already
    if (!class_exists('SimplePie')) {
        require_once ABSPATH . WPINC . '/class-feed.php';
    }
    //Retrieve & extract shorcode parameters
    extract(shortcode_atts(array("feeds" => '', "max" => '5', "feed_title" => 'yes', "target" => '_blank', "title" => '', "meta" => 'yes', "summary" => 'yes', "summarylength" => '', "thumb" => 'yes', "default" => '', "size" => '', "keywords_title" => ''), $atts, 'feedzy_default'));
    //Use "shortcode_atts_feedzy_default" filter to edit shortcode parameters default values or add your owns.
    if (!empty($feeds)) {
        $feeds = rtrim($feeds, ',');
        $feeds = explode(',', $feeds);
        //Remove SSL from HTTP request to prevent fetching errors
        foreach ($feeds as $feed) {
            $feedURL[] = preg_replace("/^https:/i", "http:", $feed);
        }
        if (count($feedURL) === 1) {
            $feedURL = $feedURL[0];
        }
    }
    if ($max == '0') {
        $max = '999';
    } else {
        if (empty($max) || !ctype_digit($max)) {
            $max = '5';
        }
    }
    if (empty($size) || !ctype_digit($size)) {
        $size = '150';
    }
    $sizes = array('width' => $size, 'height' => $size);
    $sizes = apply_filters('feedzy_thumb_sizes', $sizes, $feedURL);
    if (!empty($title) && !ctype_digit($title)) {
        $title = '';
    }
    if (!empty($keywords_title)) {
        $keywords_title = rtrim($keywords_title, ',');
        $keywords_title = array_map('trim', explode(',', $keywords_title));
    }
    if (!empty($summarylength) && !ctype_digit($summarylength)) {
        $summarylength = '';
    }
    if (!empty($default)) {
        $default = $default;
    } else {
        $default = apply_filters('feedzy_default_image', $default, $feedURL);
    }
    //Load SimplePie Instance
    $feed = new SimplePie();
    $feed->set_feed_url($feedURL);
    $feed->enable_cache(true);
    $feed->enable_order_by_date(true);
    $feed->set_cache_class('WP_Feed_Cache');
    $feed->set_file_class('WP_SimplePie_File');
    $feed->set_cache_duration(apply_filters('wp_feed_cache_transient_lifetime', 7200, $feedURL));
    do_action_ref_array('wp_feed_options', array($feed, $feedURL));
    $feed->strip_comments(true);
    $feed->strip_htmltags(array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'));
    $feed->init();
    $feed->handle_content_type();
    // Display the error message
    if ($feed->error()) {
        $content .= apply_filters('feedzy_default_error', $feed->error(), $feedURL);
    }
    $content .= '<div class="feedzy-rss">';
    if ($feed_title == 'yes') {
        $content .= '<div class="rss_header">';
        $content .= '<h2><a href="' . $feed->get_permalink() . '" class="rss_title">' . html_entity_decode($feed->get_title()) . '</a> <span class="rss_description"> ' . $feed->get_description() . '</span></h2>';
        $content .= '</div>';
    }
    $content .= '<ul>';
    //Loop through RSS feed
    $items = apply_filters('feedzy_feed_items', $feed->get_items(), $feedURL);
    foreach ((array) $items as $item) {
        $continue = apply_filters('feedzy_item_keyword', true, $keywords_title, $item, $feedURL);
        if ($continue == true) {
            //Count items
            if ($count >= $max) {
                break;
            }
            $count++;
            //Fetch image thumbnail
            if ($thumb == 'yes' || $thumb == 'auto') {
                $thethumbnail = feedzy_retrieve_image($item);
            }
            $itemAttr = apply_filters('feedzy_item_attributes', $itemAttr = '', $sizes, $item, $feedURL);
            //Build element DOM
            $content .= '<li ' . $itemAttr . '>';
            if ($thumb == 'yes' || $thumb == 'auto') {
                $contentThumb = '';
                if (!empty($thethumbnail) && $thumb == 'auto' || $thumb == 'yes') {
                    $contentThumb .= '<div class="rss_image" style="width:' . $sizes['width'] . 'px; height:' . $sizes['height'] . 'px;">';
                    $contentThumb .= '<a href="' . $item->get_permalink() . '" target="' . $target . '" title="' . $item->get_title() . '" >';
                    if (!empty($thethumbnail)) {
                        $thethumbnail = feedzy_image_encode($thethumbnail);
                        $contentThumb .= '<span class="default" style="width:' . $sizes['width'] . 'px; height:' . $sizes['height'] . 'px; background-image:  url(' . $default . ');" alt="' . $item->get_title() . '"></span>';
                        $contentThumb .= '<span class="fetched" style="width:' . $sizes['width'] . 'px; height:' . $sizes['height'] . 'px; background-image:  url(' . $thethumbnail . ');" alt="' . $item->get_title() . '"></span>';
                    } else {
                        if (empty($thethumbnail) && $thumb == 'yes') {
                            $contentThumb .= '<span style="width:' . $sizes['width'] . 'px; height:' . $sizes['height'] . 'px; background-image:url(' . $default . ');" alt="' . $item->get_title() . '"></span>';
                        }
                    }
                    $contentThumb .= '</a>';
                    $contentThumb .= '</div>';
                }
                //Filter: feedzy_thumb_output
                $content .= apply_filters('feedzy_thumb_output', $contentThumb, $feedURL);
            }
            $contentTitle = '';
            $contentTitle .= '<span class="title"><a href="' . $item->get_permalink() . '" target="' . $target . '">';
            if (is_numeric($title) && strlen($item->get_title()) > $title) {
                $contentTitle .= preg_replace('/\\s+?(\\S+)?$/', '', substr($item->get_title(), 0, $title)) . '...';
            } else {
                $contentTitle .= $item->get_title();
            }
            $contentTitle .= '</a></span>';
            //Filter: feedzy_title_output
            $content .= apply_filters('feedzy_title_output', $contentTitle, $feedURL);
            $content .= '<div class="rss_content">';
            //Define Meta args
            $metaArgs = array('author' => true, 'date' => true, 'date_format' => get_option('date_format'), 'time_format' => get_option('time_format'));
            //Filter: feedzy_meta_args
            $metaArgs = apply_filters('feedzy_meta_args', $metaArgs, $feedURL);
            if ($meta == 'yes' && ($metaArgs['author'] || $metaArgs['date'])) {
                $contentMeta = '';
                $contentMeta .= '<small>' . __('Posted', 'feedzy_rss_translate') . ' ';
                if ($item->get_author() && $metaArgs['author']) {
                    $author = $item->get_author();
                    if (!($authorName = $author->get_name())) {
                        $authorName = $author->get_email();
                    }
                    if ($authorName) {
                        $domain = parse_url($item->get_permalink());
                        $contentMeta .= __('by', 'feedzy_rss_translate') . ' <a href="http://' . $domain['host'] . '" target="' . $target . '" title="' . $domain['host'] . '" >' . $authorName . '</a> ';
                    }
                }
                if ($metaArgs['date']) {
                    $contentMeta .= __('on', 'feedzy_rss_translate') . ' ' . date_i18n($metaArgs['date_format'], $item->get_date('U'));
                    $contentMeta .= ' ';
                    $contentMeta .= __('at', 'feedzy_rss_translate') . ' ' . date_i18n($metaArgs['time_format'], $item->get_date('U'));
                }
                $contentMeta .= '</small>';
                //Filter: feedzy_meta_output
                $content .= apply_filters('feedzy_meta_output', $contentMeta, $feedURL);
            }
            if ($summary == 'yes') {
                $contentSummary = '';
                $contentSummary .= '<p>';
                //Filter: feedzy_summary_input
                $description = $item->get_description();
                $description = apply_filters('feedzy_summary_input', $description, $item->get_content(), $feedURL);
                if (is_numeric($summarylength) && strlen($description) > $summarylength) {
                    $contentSummary .= preg_replace('/\\s+?(\\S+)?$/', '', substr($description, 0, $summarylength)) . ' […]';
                } else {
                    $contentSummary .= $description . ' […]';
                }
                $contentSummary .= '</p>';
                //Filter: feedzy_summary_output
                $content .= apply_filters('feedzy_summary_output', $contentSummary, $item->get_permalink(), $feedURL);
            }
            $content .= '</div>';
            $content .= '</li>';
        }
        //endContinue
    }
    //endforeach
    $content .= '</ul>';
    $content .= '</div>';
    return apply_filters('feedzy_global_output', $content, $feedURL);
}
 /**
  * Get a specific data metrics
  *
  * @param metrics - the metrics to get
  * @param startDate - the start date to get
  * @param endDate - the end date to get
  * @param dimensions - the dimensions to grab
  * @param sort - the properties to sort on
  * @param filter - the property to filter on
  * @param limit - the number of items to get
  * @return the specific metrics in array form
  **/
 function getMetrics($metric, $startDate, $endDate, $dimensions = false, $sort = false, $filter = false, $limit = false)
 {
     # Ensure the start date is after Jan 1 2005
     $startDate = $this->verifyStartDate($startDate);
     # Build the query url
     $url = $this->baseFeed . "/data?ids={$this->accountId}&start-date={$startDate}&end-date={$endDate}&metrics={$metric}";
     # Add optional dimensions
     if ($dimensions) {
         $url .= "&dimensions={$dimensions}";
     }
     # Add optional sort
     if ($sort) {
         $url .= "&sort={$sort}";
     }
     # Add optional filter
     if ($filter) {
         $url .= "&filters={$filter}";
     }
     # Add optional limit
     if ($limit) {
         $url .= "&max-results={$limit}";
     }
     # Request the metric data
     $response = $this->http($url);
     # Check if the response received exists, else stop processing now
     if ($response == '' || $this->responseCode != '200') {
         return false;
     }
     # Parse the XML using SimplePie
     $simplePie = new SimplePie();
     $simplePie->set_raw_data($response);
     $simplePie->enable_order_by_date(false);
     $simplePie->init();
     $simplePie->handle_content_type();
     $datas = $simplePie->get_items();
     $ids = array();
     # Read out the data until the metric is found
     foreach ($datas as $data) {
         $metrics = $data->get_item_tags('http://schemas.google.com/analytics/2009', 'metric');
         $dimensions = $data->get_item_tags('http://schemas.google.com/analytics/2009', 'dimension');
         $id = array();
         $id['title'] = $data->get_title();
         # Loop through the dimensions
         if (is_array($dimensions)) {
             foreach ($dimensions as $property) {
                 # Get the property information
                 $name = $property['attribs']['']['name'];
                 $value = $property['attribs']['']['value'];
                 # Add the propery data to the id array
                 $id[$name] = $value;
             }
         }
         # Loop through the metrics
         if (is_array($metrics)) {
             foreach ($metrics as $property) {
                 # Get the property information
                 $name = $property['attribs']['']['name'];
                 $value = $property['attribs']['']['value'];
                 # Add the propery data to the id array
                 $id[$name] = $value;
             }
         }
         $ids[] = $id;
     }
     return $ids;
 }
Beispiel #19
0
 /**
  * Setup simplepie
  * @param string $raw_data
  */
 private function _setup_simplepie($raw_data)
 {
     $data = new SimplePie();
     $data->set_raw_data($raw_data);
     $data->enable_cache(false);
     $data->enable_order_by_date(true);
     $data->init();
     $data->handle_content_type();
     return $data;
 }
 function rssGetTitleFromFeedUrl($url)
 {
     require_once 'feedparser/simplepie.inc';
     $criteria['feed_url'] = $url;
     if ($criteria['feed_url'] != '') {
         $link = $criteria['feed_url'];
         $linkbits = parse_url($link);
         $host = $linkbits['host'];
         //********************************************
         //So now $host = www.url.com
         //All I have to do is remove the 'www.':
         //********************************************
         // find pos of first dot
         if (stristr($host, 'www.') == true) {
             $dot_pos = strpos($host, '.', 0) + 1;
             // make a new substring
             $domain = substr($host, $dot_pos);
         } else {
             $domain = $host;
         }
         $criteria['feed_domain'] = $domain;
     }
     if (stristr($criteria['feed_url'], 'http') == true) {
         $feed = new SimplePie();
         $feed->set_feed_url($criteria['feed_url']);
         $feed->enable_order_by_date(false);
         $feed->set_cache_location(CACHEDIR);
         $feed->init();
         $criteria['feed_title'] = $feed->get_title();
     }
     return trim($criteria['feed_title']);
 }
 function lmm_dashboard_widget()
 {
     global $wpdb;
     $lmm_options = get_option('leafletmapsmarker_options');
     $table_name_markers = $wpdb->prefix . 'leafletmapsmarker_markers';
     $widgets = get_option('dashboard_widget_options');
     $widget_id = 'lmm-admin-dashboard-widget';
     $number_of_markers = isset($widgets[$widget_id]) && isset($widgets[$widget_id]['items']) ? absint($widgets[$widget_id]['items']) : 4;
     $result = $wpdb->get_results($wpdb->prepare("SELECT `id`,`markername`,`icon`,`createdon`,`createdby` FROM `{$table_name_markers}` ORDER BY `createdon` desc LIMIT %d", $number_of_markers), ARRAY_A);
     echo '<p><a style="background:#f99755;display:block;padding:5px;text-decoration:none;color:#2702c6;text-align:center;" href="' . LEAFLET_WP_ADMIN_URL . 'admin.php?page=leafletmapsmarker_pro_upgrade">' . __('Upgrade to pro version for even more features - click here to find out how you can start a free 30-day-trial easily', 'lmm') . '</a><hr style="border:0;height:1px;background-color:#d8d8d8;"/></p>';
     if ($result != NULL) {
         echo '<table style="margin-bottom:5px;"><tr>';
         foreach ($result as $row) {
             $icon = $row['icon'] == NULL ? LEAFLET_PLUGIN_URL . 'leaflet-dist/images/marker.png' : LEAFLET_PLUGIN_ICONS_URL . '/' . $row['icon'];
             echo '<td><a href="' . LEAFLET_WP_ADMIN_URL . 'admin.php?page=leafletmapsmarker_marker&id=' . $row['id'] . '" title="' . esc_attr__('edit marker', 'lmm') . '"><img src="' . $icon . '" style="width:80%;"></a>';
             echo '<td style="vertical-align:top;line-height:1.2em;">';
             echo '<a href="' . LEAFLET_WP_ADMIN_URL . 'admin.php?page=leafletmapsmarker_marker&id=' . $row['id'] . '" title="' . esc_attr__('edit marker', 'lmm') . '">' . htmlspecialchars(stripslashes($row['markername'])) . '</a><br/>' . __('created on', 'lmm') . ' ' . date("Y-m-d - h:m", strtotime($row['createdon'])) . ', ' . __('created by', 'lmm') . ' ' . $row['createdby'];
             echo '</td></tr>';
         }
         echo '</table>';
     } else {
         echo '<p style="margin-bottom:5px;">' . __('No marker created yet', 'lmm') . '</p>';
     }
     if (!isset($widgets[$widget_id]['blogposts'])) {
         $show_rss = 1;
     } else {
         if (isset($widgets[$widget_id]['blogposts']) && $widgets[$widget_id]['blogposts'] == 1) {
             $show_rss = 0;
         } else {
             $show_rss = 1;
         }
     }
     //info: use custom name to prevent false malware detection by WordFence plugin
     function lmm_spc_custom_name($string)
     {
         return 'mapsmarker-dashboard-widget-rss-item-cache';
     }
     if ($show_rss == 1) {
         require_once ABSPATH . WPINC . DIRECTORY_SEPARATOR . 'class-simplepie.php';
         $feed = new SimplePie();
         if (file_exists(LEAFLET_PLUGIN_ICONS_DIR . DIRECTORY_SEPARATOR . 'readme-icons.txt')) {
             $feed->enable_cache(true);
             $feed->set_cache_location($location = LEAFLET_PLUGIN_ICONS_DIR);
             $feed->set_cache_name_function('lmm_spc_custom_name');
             $feed->set_cache_duration(86400);
         } else {
             $feed->enable_cache(false);
         }
         $feed->set_feed_url('http://feeds.feedburner.com/MapsMarkerPro');
         $feed->set_stupidly_fast(true);
         $feed->enable_order_by_date(true);
         $feed->init();
         $feed->handle_content_type();
         echo '<hr style="border:0;height:1px;background-color:#d8d8d8;"/><strong><p>' . __('Latest blog posts from www.mapsmarker.com', 'lmm') . '</p></strong>';
         if ($feed->get_items() == NULL) {
             $blogpost_url = '<a href="https://www.mapsmarker.com/news" target="_blank">https://www.mapsmarker.com/news</a>';
             echo sprintf(__('Feed could not be retrieved, please try again later or read the latest blog posts at %s', 'lmm'), $blogpost_url);
         }
         foreach ($feed->get_items(0, 3) as $item) {
             echo '<p  style="margin:0.5em 0;">' . $item->get_date('j F Y') . ': <strong><a href="' . $item->get_permalink() . '?ref=dashboard">' . $item->get_title() . '</a></strong></p>' . PHP_EOL;
         }
         echo '<p><a style="text-decoration:none;" href="https://www.mapsmarker.com" target="_blank"><img src="' . LEAFLET_PLUGIN_URL . 'inc/img/icon-website-home.png" width="16" height="16" alt="mapsmarker.com"> MapsMarker.com</a>&nbsp;<a href="' . LEAFLET_WP_ADMIN_URL . 'admin.php?page=leafletmapsmarker_pro_upgrade' . '"><img src="' . LEAFLET_PLUGIN_URL . 'inc/img/icon-up16.png" width="16" height="16" alt="upgrade to pro"> ' . __('Upgrade to Pro', 'lmm') . '</a>&nbsp;<a style="text-decoration:none;" title="' . esc_attr__('MapsMarker affiliate program - sign up now and receive commissions up to 50%!', 'lmm') . '" href="https://www.mapsmarker.com/affiliates" target="_blank"><img src="' . LEAFLET_PLUGIN_URL . 'inc/img/icon-affiliates.png" width="16" height="16" alt="affiliates"> ' . __('Affiliates', 'lmm') . '</a>&nbsp;<a style="text-decoration:none;" title="' . esc_attr__('MapsMarker reseller program - re-sell with a 20% discount!', 'lmm') . '" href="https://www.mapsmarker.com/reseller" target="_blank"><img src="' . LEAFLET_PLUGIN_URL . 'inc/img/icon-resellers.png" width="16" height="16" alt="resellers"> ' . __('Resellers', 'lmm') . '</a>&nbsp;<a style="text-decoration:none;" href="https://www.mapsmarker.com/reviews" target="_blank" title="' . esc_attr__('please rate this plugin on wordpress.org', 'lmm') . '"><img src="' . LEAFLET_PLUGIN_URL . 'inc/img/icon-star.png" width="16" height="16" alt="ratings"> ' . __('rate plugin', 'lmm') . '</a>&nbsp;<a href="https://translate.mapsmarker.com/projects/lmm" target="_blank"><img src="' . LEAFLET_PLUGIN_URL . 'inc/img/icon-translations.png" width="16" height="16" alt="translations"> ' . __('translations', 'lmm') . '</a> <a href="https://twitter.com/mapsmarker" target="_blank"><img src="' . LEAFLET_PLUGIN_URL . 'inc/img/icon-twitter.png" width="16" height="16" alt="twitter">&nbsp;Twitter</a>&nbsp;<a href="https://facebook.com/mapsmarker" target="_blank"><img src="' . LEAFLET_PLUGIN_URL . 'inc/img/icon-facebook.png" width="16" height="16" alt="facebook"> Facebook</a>&nbsp;<a href="https://www.mapsmarker.com/+" target="_blank"><img src="' . LEAFLET_PLUGIN_URL . 'inc/img/icon-google-plus.png" width="16" height="16" alt="google+"> Google+</a>&nbsp;<a style="text-decoration:none;" href="https://www.mapsmarker.com/changelog" target="_blank"><img src="' . LEAFLET_PLUGIN_URL . 'inc/img/icon-changelog-header.png" width="16" height="16" alt="changelog"> ' . __('Changelog', 'lmm') . '</a>&nbsp;<a href="https://feeds.feedburner.com/MapsMarker" target="_blank"><img src="' . LEAFLET_PLUGIN_URL . 'inc/img/icon-rss.png" width="16" height="16" alt="rss"> RSS</a>&nbsp;<a href="http://feedburner.google.com/fb/a/mailverify?uri=MapsMarker" target="_blank"><img src="' . LEAFLET_PLUGIN_URL . 'inc/img/icon-rss-email.png" width="16" height="16" alt="rss-email"> ' . __('E-Mail', 'lmm') . '</a></p>';
     }
 }
Beispiel #22
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);
}
Beispiel #23
0
 /**
  * setup simplepie
  */
 private function _setup_simplepie($feed_url)
 {
     $data = new SimplePie();
     // Convert To GeoRSS feed
     $geocoder = new Geocoder();
     $georss_feed = $geocoder->geocode_feed($feed_url);
     $data->set_raw_data($georss_feed);
     $data->enable_cache(false);
     $data->enable_order_by_date(true);
     $data->init();
     $data->handle_content_type();
     return $data;
 }
Beispiel #24
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);
 }
Beispiel #25
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
}
Beispiel #26
0
 /**
  * Fetches all current events from this extension.
  * @return {Array} List of events.
  */
 function fetch($urls = null, $initial = false)
 {
     if (!$urls) {
         $urls = $this->get_url();
     }
     if (!is_array($urls)) {
         $urls = array($urls);
     }
     $items = array();
     foreach ($urls as $url_data) {
         if (is_array($url_data)) {
             // url, key
             list($url, $key) = $url_data;
         } else {
             $url = $url_data;
             $key = '';
         }
         $feed = new SimplePie();
         $feed->enable_cache(false);
         $data = $this->lifestream->file_get_contents($url);
         $feed->set_raw_data($data);
         $feed->enable_order_by_date(false);
         $feed->force_feed(true);
         $success = $feed->init();
         if (!$success) {
             $sample = substr($data, 0, 150);
             throw new Lifestream_FeedFetchError("Error fetching feed from {$url} ({$feed->error()})....\n\n{$sample}");
         }
         $feed->handle_content_type();
         foreach ($feed->get_items() as $row) {
             $rows =& $this->yield_many($row, $url, $key);
             foreach ($rows as $row) {
                 if (!$row) {
                     continue;
                 }
                 if (!$row['key']) {
                     $row['key'] = $key;
                 }
                 if (count($row)) {
                     $items[] = $row;
                 }
             }
         }
         $feed->__destruct();
         unset($feed);
     }
     return $items;
 }
Beispiel #27
0
 /**
  * Display external feed content on journal homepage.
  * @param $hookName string
  * @param $args array
  */
 function displayHomepage($hookName, $args)
 {
     $request = $this->getRequest();
     $journal = $request->getJournal();
     $journalId = $journal ? $journal->getId() : 0;
     if ($this->getEnabled()) {
         $requestedPage = $request->getRequestedPage();
         if (empty($requestedPage) || $requestedPage == 'index') {
             $externalFeedDao = DAORegistry::getDAO('ExternalFeedDAO');
             $this->import('simplepie.SimplePie');
             $feeds =& $externalFeedDao->getExternalFeedsByJournalId($journal->getId());
             $output = '<div id="externalFeedsHome">';
             while ($currentFeed = $feeds->next()) {
                 if (!$currentFeed->getDisplayHomepage()) {
                     continue;
                 }
                 $feed = new SimplePie();
                 $feed->set_feed_url($currentFeed->getUrl());
                 $feed->enable_order_by_date(false);
                 $feed->set_cache_location(CacheManager::getFileCachePath());
                 $feed->init();
                 if ($currentFeed->getLimitItems()) {
                     $recentItems = $currentFeed->getRecentItems();
                 } else {
                     $recentItems = 0;
                 }
                 $output .= '<h3>' . $currentFeed->getLocalizedTitle() . '</h3>';
                 $output .= '<table class="externalFeeds">';
                 $output .= '<tr>';
                 $output .= '<td colspan="2" class="headseparator">&nbsp;</td>';
                 $output .= '</tr>';
                 $separator = '';
                 foreach ($feed->get_items(0, $recentItems) as $item) {
                     $output .= $separator;
                     $output .= '<tr class="title">';
                     $output .= '<td colspan="2" class="title">';
                     $output .= '<h4>' . $item->get_title() . '</h4>';
                     $output .= '</td>';
                     $output .= '</tr>';
                     $output .= '<tr class="description">';
                     $output .= '<td colspan="2" class="description">';
                     $output .= $item->get_description();
                     $output .= '</td>';
                     $output .= '</tr>';
                     $output .= '<tr class="details">';
                     $output .= '<td class="posted">';
                     $output .= AppLocale::Translate('plugins.generic.externalFeed.posted') . ': ' . date('Y-m-d', strtotime($item->get_date()));
                     $output .= '</td>';
                     $output .= '<td class="more">';
                     $output .= '<a href="' . $item->get_permalink() . '" target="_blank">' . AppLocale::Translate('plugins.generic.externalFeed.more') . '</a>';
                     $output .= '</td>';
                     $output .= '</tr>';
                     $separator = '<tr><td colspan="2" class="separator">&nbsp;</td></tr>';
                 }
                 $output .= '<tr><td colspan="2" class="endseparator">&nbsp;</td></tr>';
                 $output .= '</table>';
             }
             $output .= '</div>';
             $templateManager =& $args[0];
             $additionalHomeContent = $templateManager->get_template_vars('additionalHomeContent');
             $templateManager->assign('additionalHomeContent', $additionalHomeContent . "\n\n" . $output);
         }
     }
 }
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();
}
 debug("Attempting to process URL as feed");
 // Send user agent header showing PHP (prevents a HTML response from feedburner)
 $http->userAgentDefault = HumbleHttpAgent::UA_PHP;
 // configure SimplePie HTTP extension class to use our HumbleHttpAgent instance
 SimplePie_HumbleHttpAgent::set_agent($http);
 $feed = new SimplePie();
 // some feeds use the text/html content type - force_feed tells SimplePie to process anyway
 $feed->force_feed(true);
 $feed->set_file_class('SimplePie_HumbleHttpAgent');
 //$feed->set_feed_url($url); // colons appearing in the URL's path get encoded
 $feed->feed_url = $url;
 $feed->set_autodiscovery_level(SIMPLEPIE_LOCATOR_NONE);
 $feed->set_timeout(20);
 $feed->enable_cache(false);
 $feed->set_stupidly_fast(true);
 $feed->enable_order_by_date(false);
 // we don't want to do anything to the feed
 $feed->set_url_replacements(array());
 // initialise the feed
 // the @ suppresses notices which on some servers causes a 500 internal server error
 $result = @$feed->init();
 //$feed->handle_content_type();
 //$feed->get_title();
 if ($result && (!is_array($feed->data) || count($feed->data) == 0)) {
     die('Sorry, no feed items found');
 }
 // from now on, we'll identify ourselves as a browser
 $http->userAgentDefault = HumbleHttpAgent::UA_BROWSER;
 // Enable caching for multiple downloader
 if (class_exists('HttpRequestPool')) {
     $http->method = $http::METHOD_REQUEST_POOL;
Beispiel #30
0
		}
		// limit to 10 URLs in OPML
		if (count($feed_urls) >= 10) break;
	}
	// setup SimplePie again
	if ($order == 'asc') {
		$feed = new SimplePie_Chronological();
	} else {
		$feed = new SimplePie();
	}
	$feed->set_feed_url($feed_urls);
	//$feed->force_feed(true);
	$feed->set_timeout(120);
	$feed->enable_cache(false);
	$feed->set_stupidly_fast(true);
	$feed->enable_order_by_date(true);
	$feed->set_url_replacements(array());
	$result = $feed->init();
	//$feed->handle_content_type();
	//if ($feed->error()) echo $feed->error();exit;
	if (!$result) {
		die('Sorry, no feed items found');
	}
}

/////////////////////////////////////////////////
// Create new PDF document (LETTER/A4)
/////////////////////////////////////////////////
$pdf = new NewspaperPDF('P', 'mm', 'A4', true, 'UTF-8', false);
//$pdf = new NewspaperPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);