Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-20 of 34 total

RSS mod for phpBB

// This is a mod from phpBB that creates an RSS feed for your forum. I am hoping the folks at phpbb-seo.com can help me out with making this compatible with the 'advanced mod rewrite' mod.

<?php
/***************************************************************************
 *                                rss.php
 *                            -------------------
 *   begin                : Saturday, Feb 13, 2001
 *   copyright            : (C) 2005 by Lucas van Dijk
 *   email                : lucas@aoe3capitol.nl
 *
 *   $Id: rss.php,v 1.00 2004/07/11 16:46:15 mrlucky Exp $
 *
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

define('IN_PHPBB', 1);
$phpbb_root_path = './';
include($phpbb_root_path . 'extension.inc');
include($phpbb_root_path . 'common.'.$phpEx);
include($phpbb_root_path.'includes/functions_post.php');
include($phpbb_root_path.'includes/bbcode.php');

//
// Start session management
//
$userdata = session_pagestart($user_ip, PAGE_INDEX);
init_userprefs($userdata);
//
// End session management
//

// -------
// Begin Page specific functions
//
function make_xml_compatible($text, $bbcode_uid = '', $use_bbcode = 0)
{
        global $board_config, $base_url;

        if($use_bbcode)
        {
                if($bbcode_uid != '')
                {
                        $text = ( $board_config['allow_bbcode'] ) ? bbencode_second_pass($text, $bbcode_uid) : preg_replace('/\:[0-9a-z\:]+\]/si', ']', $text);
                }
                else
                {
                        $text = preg_replace('/\:[0-9a-z\:]+\]/si', ']', $text);
                }
                $text = make_clickable($text);
                if($board_config['allow_smilies'])
                {
                        $text = smilies_pass($text);
                        $text = str_replace("./".$board_config['smilies_path'], $base_url.$board_config['smilies_path'], $text);
                }
        }
        $text = nl2br($text);

        $text = str_replace('&pound', '&amp;#163;', $text);
        $text = str_replace('&copy;', '(c)', $text);

        $text = htmlspecialchars($text);

        return $text;
}
//
// End page specific functions
// ------

//
// If running with PHP3
//
if(!is_array($_SERVER))
{
        $_SERVER = $HTTP_SERVER_VARS;
        $_GET = $HTTP_GET_VARS;
}

//
// Get Various vars
//

$base_url = ($board_config['cookie_secure'] ? "https://" : "http://").$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);

if(substr($base_url, -1) != "/")
{
        $base_url .= "/";
}

//

//
// Start RSS output
//
$rss_result = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>
<rss version=\"2.0\">
<channel>
  <title>".make_xml_compatible($board_config['sitename'])."</title>
  <link>".$base_url."index.php</link>
  <description>".make_xml_compatible($board_config['site_desc'])."</description>
  <language>".$board_config['default_lang']."</language>
  <copyright>(c) Copyright 2007 by ".make_xml_compatible($board_config['sitename'])."</copyright>
  <managingEditor>".$board_config['board_email']."</managingEditor>
  <webMaster>".$board_config['board_email']."</webMaster>
  <pubDate>".create_date($board_config['default_dateformat'], time(), $board_config['board_timezone'])."</pubDate>
  <lastBuildDate>".create_date($board_config['default_dateformat'], time(), $board_config['board_timezone'])."</lastBuildDate>
  <docs>http://backend.userland.com/rss</docs>
  <generator>phpBB2 RSS Syndication Mod by Lucas</generator>
  <ttl>1</ttl>

  <image>
    <title>".make_xml_compatible($board_config['sitename'])."</title>
    <url>".$board_config['rss_image']."</url>
    <link>".$base_url."</link>
    <description>".make_xml_compatible($board_config['site_desc'])."</description>
  </image>
";

//
// Get latest topics
//


$forum=1;


        //
        // This SQL query selects the latest topics of a specific forum
        //
        $sql = "SELECT t.topic_title, t.topic_last_post_id, p.post_time, pt.post_text, pt.bbcode_uid, pt.post_link, u.username, u.user_id
                FROM ".TOPICS_TABLE." t, ".POSTS_TABLE." p, ".POSTS_TEXT_TABLE." pt, ".USERS_TABLE." u
                WHERE t.forum_id = ".$forum."
                AND t.topic_status != 1
                AND p.post_id = t.topic_last_post_id
                AND pt.post_id = p.post_id
                AND u.user_id = p.poster_id
                ORDER BY t.topic_last_post_id DESC
                LIMIT 0, ".intval($board_config['max_rss_topics']);
        if(!$result = $db->sql_query($sql))
        {
                message_die(GENERAL_ERROR, "Could not get Latest topics", '', __LINE__, __FILE__, $sql);
        }

        $is_auth = array();
        $is_auth = auth(AUTH_ALL, $forum, $userdata);
		
		

        while($row = $db->sql_fetchrow($result))
        {
		//Read link MOD
		$post_link = ( $row['post_link'] != '' ) ? $row['post_link'] : '';
		//end read link
		
                if($is_auth['auth_view'] && $is_auth['auth_read'])
                {
                        $description = "
                                       ".$lang['Posted']." ".create_date($board_config['default_dateformat'], $row['post_time'], $board_config['board_timezone'])."<br />
                                      <br />
                                      ".$row['post_text']
									  ."<br /><br />
									  <a href=\"$post_link\">Read</a>&nbsp;|&nbsp;<a href=\"".$base_url."viewtopic.php?".POST_POST_URL."=".$row['topic_last_post_id']."\" >Permalink</a>"
									  ."<hr />";

                        $rss_result .= "
                                      <item>
                                        <title>".make_xml_compatible(strip_tags($row['topic_title']))."</title>
                                        <link>".$base_url."viewtopic.php?".POST_POST_URL."=".$row['topic_last_post_id']."</link>
                                        <description>".make_xml_compatible($description, $row['bbcode_uid'], true)."</description>
                                        <pubDate>".create_date($board_config['default_dateformat'], $row['post_time'], $board_config['board_timezone'])."</pubDate>
                                        <guid isPermaLink=\"true\">".$base_url."viewtopic.php?".POST_POST_URL."=".$row['topic_last_post_id']."#".$row['topic_last_post_id']."</guid>
                                      </item>";
                }
        }


$rss_result .= "</channel></rss>";

header("Content-type: text/xml", true);
echo $rss_result;

?>

Beefed up RSS2 template for consumption with the Google Feed API Slide Show Control

// description of your code here

xml.instruct!

# RSS2 rxml template based on: http://snippets.dzone.com/posts/show/558
xml.rss "version" => "2.0", \
        "xmlns:dc" => "http://purl.org/dc/elements/1.1/", \
        "xmlns:media" => "http://search.yahoo.com/mrss/" do

    xml.channel do

        xml.title       "foto-foo :: public timeline"
        xml.link        url_for :only_path => false, :controller => 'feeds'
        xml.pubDate     CGI.rfc1123_date(@images.first.updated_at) if @images.any?
        xml.description "foto-foo :: public timeline image feed"

        host = "AWS.S3.storage.host"
        @images.each do |img|
            img.url = "http://#{host}/#{img.name}"
            xml.item do
                xml.title       img.name
                xml.link        url_for :only_path => false, :controller => 'feeds', :action => 'show', :id => img.id
                xml.description "<a href='#{img.url}'><img src='#{img.url}'/></a>"
                xml.enclosure :url => "#{img.url}", :type => "image/jpg"

                xml.pubDate     CGI.rfc1123_date img.updated_at
                xml.guid        url_for :only_path => false, :controller => 'posts', :action => 'show', :id => img.id
                xml.author      "\"user-#{img.user_id}\" (#{img.user_id}@foto-foo.com)"

                xml.media :group do
                    xml.media :title, img.name
                    xml.media \
                        :content, :type => "#{img.mime}", :medium => "image", \
                        :url => "#{img.url}"
                        xml.media :credit, "#{img.credit.txt}", \
                                :role => "#{img.credit.role}" 
                    xml.media :description, "#{img.desc}", :type => 'plain'
                    xml.media :keywords, "#{img.tags}"
                    xml.media :thumbnail, \
                        :width => "#{img.thumbnail.widh}", \
                        :height => "#{img.thumbnail.height}", \
                        :url => "#{img.thumbnail.url}"
                end
            end
        end

    end
end

ruby Simple RSS Parsing

def fetch_rss_items(url, max_items = nil)
%w{open-uri rss/0.9 rss/1.0 rss/2.0 rss/parser}.each do |lib|
require(lib)
end
rss = RSS::Parser.parse(open(url).read)
rss.items[0...(max_items ? max_items : rss.items.length)]
end

items = fetch_rss_items('http://www.digg.com/rss/index.xml', 5)
items.collect { |item| item.title }
=> ["Understanding AJAX - A Beginner's Guide",
"Anti-cancer Compound In Beer", ...]

Broadcasting DZONE Shares

// This snippet will allow you to show your DZONE shares
// on your web page. Visit your shares page, click on the "feed" link
// to get the URL of your personal shares feed then paste it in the first line
// in the script.

var sharedURL='';  // Place your url between the quotes.

function getFeed(url, callback) {
   var newScript = document.createElement('script');
       newScript.type = 'text/javascript';
       newScript.src = 'http://pipes.yahoo.com/pipes/9oyONQzA2xGOkM4FqGIyXQ/run?&_render=JSON&_callback='+callback+'&feed=' + sharedURL;
   document.getElementsByTagName("head")[0].appendChild(newScript);
}

function dzone(feed) {
   var tmp='';
   for (var i=0; i<feed.value.items.length; i++) {
      tmp+='<a href="'+feed.value.items[i].link+'" rel="nofollow">';
      tmp+=feed.value.items[i].title+'</a><br>';
   }
   document.getElementById('dzoneLinks').innerHTML=tmp;
}

getFeed(sharedURL, 'dzone');


// Paste that code at the end of your page. In your HTML place the following two divisions
// where you would like your feed to appear. (feel free to style the divisions however you wish)
// you can add to/subtract from the outer division but the inner division will always be overwritten
// with your shares.

<div id='dzoneLayer'>
My DZONE Recommendations
   <div id='dzoneLinks'>
   </div>
</div>

RSS/Atom Autodiscovery

// description of your code here

<link rel="alternate" type="application/rss+xml" title="RSS Feed" href="rss.xml" />

<!-- or... //-->

<link rel="alternate" type="application/atom+xml" title="Atom Feed" href="Atom.xml" />

RSS Twitter Bot

Republish an RSS feed on a twitter account. This was the source I used to run the Woot Twitter Bot before they took it over.

require 'rubygems'
require 'active_record'
require 'simple-rss'
require 'open-uri'
require 'twitter'

#twitter account to post to
twitter_email = "yourtwitteremail@bla.com"
twitter_password = "secret"

#rss feed to post
rss_url = "http://yoursite.com/index.xml"
rss_user_agent = "http://twitter.com/yourbot"

#sqlite db
path_to_sqlite_db = "/PATH/TO/db.sqlite"


ActiveRecord::Base.logger = Logger.new(STDERR)
ActiveRecord::Base.colorize_logging = false

ActiveRecord::Base.establish_connection(
    :adapter => "sqlite3",
    :dbfile  => path_to_sqlite_db
)

#uncomment this section the first time to create the table
#
#ActiveRecord::Schema.define do
#    create_table :item do |table|
#        table.column :title, :string
#        table.column :link, :string
#    end
#end

class Item < ActiveRecord::Base
  def to_s
    "#{self.title[0..(130-self.link.length)]} - #{self.link}"
  end
end

#run the beast
rss_items = SimpleRSS.parse open(rss_url ,"User-Agent" => rss_user_agent)

for item in rss_items.items
  Item.transaction do
    unless existing_item = Item.find(:all, :conditions => ["link=?", item.link]).first
      twitter ||= Twitter::Base.new(twitter_email, twitter_password)
      new_item = Item.create(:title => item.title, :link => item.link) 
      twitter.post(new_item.to_s)
    end
  end
end


Run this once with the lines uncommented to create the DB, then slap it in your crontab.

Set::extract - parsing an RSS feed for all post titles

// description of your code here
http://www.thinkingphp.org/2007/02/24/cake-12s-set-class-eats-arrays-for-breakfast/

The following code will produce the result:
Array
(
[0] => How-to: Use Html 4.01 in CakePHP 1.2
[1] => Looking up foreign key values using Model::displayField
[2] => Bug-fix update for SVN/FTP Deployment Task
[3] => Access your config files rapidly (Win32 only)
[4] => Making error handling for Model::save more beautiful in CakePHP
[5] => Full content RSS feed
[6] => Visual Sorting - Some Javascript fun I had last night
)

uses('Xml');
 
$feed = xmltoArray(new XML('http://feeds.feedburner.com/thinkingphp'));
$postTitles = Set::extract($feed, 'rss.channel.item.{n}.title'); 

parsing an RSS feed for all post titles

// description of your code here
http://www.thinkingphp.org/2007/02/24/cake-12s-set-class-eats-arrays-for-breakfast/

PHP:

function xmltoArray($node)
{
    $array = array();
    
    foreach ($node->children as $child)
    {
        if (empty($child->children))
        {
            $value = $child->value;
        }
        else
        {
            $value = xmltoArray($child);
        }
        
        $key = $child->name;
        
        if (!isset($array[$key]))
        {
            $array[$key] = $value;
        }
        else 
        {
            if (!is_array($array[$key]) || !isset($array[$key][0]))
            {
                $array[$key] = array($array[$key]);
            }
            
            $array[$key][] = $value;
        }
    }
    
    return $array;
} 

Importing XML into a database with Scriptella ETL

The following Scriptella ETL simple usage example imports RSS file into a database table.
<!DOCTYPE etl SYSTEM "http://scriptella.javaforge.com/dtd/etl.dtd">
<etl>
    <connection id="in" driver="xpath" url="http://snippets.dzone.com/rss"/>
    <connection id="db" driver="hsqldb" url="jdbc:hsqldb:db/rss" user="sa" classpath="hsqldb.jar"/>
classpath="hsqldb.jar"/>
    <query connection-id="in">
        /rss/channel/item
        <script connection-id="db">
            INSERT INTO Rss (ID, Title, Description, Link) 
            VALUES (?rownum, ?title, ?description, ?link);
        </script>
    </query>
</etl>


Here is the full version of the example described above. It creates an RSS table, downloads rss file, inserts rss records into a database, converts rss.xml to a plain text file and saves it to rss.txt.
<!DOCTYPE etl SYSTEM "http://scriptella.javaforge.com/dtd/etl.dtd">
<etl>
    <connection id="in" driver="xpath" url="http://snippets.dzone.com/rss"/>
    <connection id="out" driver="text" url="rss.txt"/>
    <connection id="db" driver="hsqldb" url="jdbc:hsqldb:db/rss" user="sa" classpath="hsqldb.jar"/>
    <script connection-id="db">
       CREATE TABLE Rss (
           ID Integer,
           Title VARCHAR(255),
           Description VARCHAR(255),   
           Link VARCHAR(255)

       )
    </script>
    <query connection-id="in">
        /rss/channel/item
        <script connection-id="out">
            Title: $title
            Description: [
            ${description.substring(0, 20)}...
            ]
            Link: $link
            ----------------------------------
        </script>
        <script connection-id="db">
            INSERT INTO Rss (ID, Title, Description, Link) 
            VALUES (?rownum, ?title, ?description, ?link);
        </script>
    </query>
</etl>

RSS Reader - Reads Name and URL into HashMap

// description of your code here
// RSS reader for web reads them into HashMap



/**
 * Created by IntelliJ IDEA.
 * User: Rapid
 * Date: Oct 9, 2006
 * Time: 3:18:23 PM
 * To change this template use File | Settings | File Templates.
 */
import java.net.URL;
import java.util.Iterator;
import java.util.HashMap;

import com.sun.syndication.feed.module.Module;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

/**
 * Reads and prints any RSS/Atom feed type. Adopted from the example by the
 * same name at http://wiki.java.net/bin/view/Javawsxml/Rome05TutorialFeedReader
 *
 */
public class FeedReader {


    HashMap hm = null;
    String[][] rss = null ;
    SyndFeedInput input ;
    URL feedUrl;
    SyndFeed feed ;
    int count =-1;


    public HashMap readRSS(String url) {
        boolean readOk = false;

            try {

                hm = new HashMap();

               feedUrl  = new URL(url);

                input  = new SyndFeedInput();
                 feed = input.build(new XmlReader(feedUrl));

                System.out.println("Title: " + feed.getTitle());
                System.out.println("Author: " + feed.getAuthor());
                System.out.println("Description: " + feed.getDescription());
                System.out.println("Pub date: " + feed.getPublishedDate());
                System.out.println("Copyright: " + feed.getCopyright());
                System.out.println("Modules used:");



                String metaRSS = "Title: " + feed.getTitle() + "\n" +
                "Author: " + feed.getAuthor()  + "\n" +
                 "Description: " + feed.getDescription()  + "\n" +
                 "Pub date: " + feed.getPublishedDate()  + "\n" +
                 "Copyright: " + feed.getCopyright() ;




                rss = new String[ feed.getEntries().size()][2];


                System.out.println("Titles of the " + feed.getEntries().size() +
                                   " entries:");
                for (final Iterator iter = feed.getEntries().iterator();
                     iter.hasNext();)
                {






                    rss[++count][0] =      ((SyndEntry)iter.next()).getTitle().toString();




                }
                count = -1 ;
                for (final Iterator iter = feed.getEntries().iterator();
                     iter.hasNext();)
                {

                   rss[++count][1] =      ((SyndEntry)iter.next()).getUri().toString();
                }


                if (feed.getImage() != null)
                {
                    System.out.println("Feed image URL: " +
                                       feed.getImage().getUrl());
                }

                readOk = true;
                hm.put( feed.getTitle(), rss);
            }
            catch (Exception ex) {
                ex.printStackTrace();
                System.out.println("ERROR: " + ex.getMessage());
            }


        String[][] rs = (String[][])hm.get("LinuxInsider");

          System.out.println("************************");
        for( int i=0; i<rs.length; i++){

            System.out.println( rs[i][0]);
             System.out.println( rs[i][1]);
//             System.out.println( rs[i][2]);
        }
        if (! readOk) {
            System.out.println();
            System.out.println("FeedReader reads and prints info on any RSS/Atom feed.");
            System.out.println("The first parameter must be the URL of the feed to read.");
            System.out.println();
        }

        return hm;
    }

}
« Newer Snippets
Older Snippets »
Showing 11-20 of 34 total