External RSS integration tag {RSS}

Post custom hacks and enhancements for phpwcms here only. Maybe some of these things will be included in official release later.
Post Reply
User avatar
marcus@localhorst
Posts: 815
Joined: Fri 28. May 2004, 11:31
Location: localhorst
Contact:

External RSS integration tag {RSS}

Post by marcus@localhorst »

holla,
i try out the example from this post http://www.phpwcms.de/forum/viewtopic.p ... ternal+rss but it doesn't work and i thought it would be better, if i use a replacement tag.

so, i start with a RSS Parser class and my basic PHP knowlegde and here is the result. maybe i've wrote some lousy code, but it works for me and if you make correction, please tell us ;-)

This is the tag: {RSS:COUNT(0=all|n):TEASER(0=no teaser|-1 =all|n):URL}

Just upload a file to phpwcms_template/frontend_render/external_rss.php
with the following content:

Code: Select all

<?php 

/********************************************
titel:          {RSS} Replacement-Tag
description:    {RSS:COUNT(0=all|n):TEASER(0=no teaser|-1 =all|n):URL}
                (n = a number)
                COUNT - how much items should be shown 
								TEASER - if 0 there bill be show no description (if available)
								         if -1 the complete content will be shown
												 if n only n chars as teaser
example:        {RSS:5:175:http://www.disquiet.com/disquiet.rss}
                {RSS:0:-1:http://www.disquiet.com/disquiet.rss}
notice:         $show_remote_pic 1/0 if the feed contains an url of a pic
                it will be sown (1) or not (0)
author:         Marcus Obst, using the Parserclass from Vojtech Semecky
last modified:  20.01.2005 created
********************************************/
function render_external_rss($string='',$item_limit=NULL,$teaser='') {
//-- CHANGE here
$show_remote_pic = 0; // if there is a website logo, should it be shown? 
//-- /CHANGE end

$rss_all = '';
$string = preg_replace('/\{RSS:(\d+):(\-1|\d+):(.*?)\}/e', '"$3"', $string);
$item_limit = preg_replace('/\{RSS:(\d+):(\-1|\d+):(.*?)\}/e', '"$1"', $item_limit);
$teaser = preg_replace('/\{RSS:(\d+):(\-1|\d+):(.*?)\}/e', '"$1"', $teaser);

// Create lastRSS object 
$rss = new lastRSS; 
// Set cache dir and cache time limit (1200 seconds) 
// (don't forget to chmod cache dir to 777 to allow writing) 
$rss->cache_dir = './temp'; 
$rss->cache_time = 1200;
$rss->items_limit = $item_limit; 

// Try to load and parse RSS file 
// MO: $string enthält die RSS URL
if ($rs = $rss->get($string)) { 

// Here you can build your own output

// Show website logo (if presented) 
    if ($rs[image_url] != '' & $show_remote_pic != 0) { 
		 $rss_all = $rss_all."<a href=\"$rs[image_link]\"><img src=\"$rs[image_url]\" alt=\"$rs[image_title]\" vspace=\"1\" border=\"0\" /></a><br />\n"; 
        } 
		
    // Show clickable website title 
    $rss_all = $rss_all."<b><a href=\"$rs[link]\">$rs[title]</a></b><br />\n"; 
    // Show website description 
    $rss_all = $rss_all."$rs[description]<br />\n"; 
    // Show last published articles (title, link, description) 
    $rss_all = $rss_all."<ul>\n"; 
    foreach($rs['items'] as $item) { 
        $rss_all = $rss_all."\t<li><a href=\"$item[link]\">".$item['title']."</a><br />".substr($item['description'],0,$teaser)."</li>\n"; 
        } 
    $rss_all = $rss_all."</ul>\n"; 
    } 
else { 
    $rss_all= $rss_all."Error: It's not possible to reach RSS file...\n"; 
}
return $rss_all;
}

if( ! ( strpos($content["all"],'{RSS')===false ) ) {
  $content["all"] = preg_replace('/\{RSS:(\d+):(\-1|\d+):(.*?)\}/e','render_external_rss("$3","$1","$2");',$content["all"]);
}

//-----------------------------------------------------------------------------------------------------------------------------
//--- HERE COMES THE PARSERCLASS ----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------


/* 
====================================================================== 
lastRSS 0.9.1 

Simple yet powerfull PHP class to parse RSS files. 

by Vojtech Semecky, webmaster @ webdot . cz 

Latest version, features, manual and examples: 
    http://lastrss.webdot.cz/ 

---------------------------------------------------------------------- 
LICENSE 

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

This program is distributed in the hope that it will be useful, 
but WITHOUT ANY WARRANTY; without even the implied warranty of 
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
GNU General Public License for more details. 

To read the license please visit http://www.gnu.org/copyleft/gpl.html 
====================================================================== 
*/ 

/** 
* lastRSS CLASS
* Simple yet powerfull PHP class to parse RSS files. 
*/ 
class lastRSS { 
    // ------------------------------------------------------------------- 
    // Public properties 
    // ------------------------------------------------------------------- 
    var $default_cp = 'UTF-8'; 
    var $CDATA = 'nochange'; 
    var $cp = ''; 
    var $items_limit = 0; 
    var $stripHTML = False; 
    var $date_format = ''; 

    // ------------------------------------------------------------------- 
    // Private variables 
    // ------------------------------------------------------------------- 
    var $channeltags = array ('title', 'link', 'description', 'language', 'copyright', 'managingEditor', 'webMaster', 'lastBuildDate', 'rating', 'docs'); 
    var $itemtags = array('title', 'link', 'description', 'author', 'category', 'comments', 'enclosure', 'guid', 'pubDate', 'source'); 
    var $imagetags = array('title', 'url', 'link', 'width', 'height'); 
    var $textinputtags = array('title', 'description', 'name', 'link'); 

    // ------------------------------------------------------------------- 
    // Parse RSS file and returns associative array. 
    // ------------------------------------------------------------------- 
    function Get ($rss_url) { 
        // If CACHE ENABLED 
        if ($this->cache_dir != '') { 
            $cache_file = $this->cache_dir . '/rsscache_' . md5($rss_url); 
            $timedif = @(time() - filemtime($cache_file)); 
            if ($timedif < $this->cache_time) { 
                // cached file is fresh enough, return cached array 
                $result = unserialize(join('', file($cache_file))); 
                // set 'cached' to 1 only if cached file is correct 
                if ($result) $result['cached'] = 1; 
            } else { 
                // cached file is too old, create new 
                $result = $this->Parse($rss_url); 
                $serialized = serialize($result); 
                if ($f = @fopen($cache_file, 'w')) { 
                    fwrite ($f, $serialized, strlen($serialized)); 
                    fclose($f); 
                } 
                if ($result) $result['cached'] = 0; 
            } 
        } 
        // If CACHE DISABLED >> load and parse the file directly 
        else { 
            $result = $this->Parse($rss_url); 
            if ($result) $result['cached'] = 0; 
        } 
        // return result 
        return $result; 
    } 
     
    // ------------------------------------------------------------------- 
    // Modification of preg_match(); return trimed field with index 1 
    // from 'classic' preg_match() array output 
    // ------------------------------------------------------------------- 
    function my_preg_match ($pattern, $subject) { 
        // start regullar expression 
        preg_match($pattern, $subject, $out); 

        // if there is some result... process it and return it 
        if(isset($out[1])) { 
            // Process CDATA (if present) 
            if ($this->CDATA == 'content') { // Get CDATA content (without CDATA tag) 
                $out[1] = strtr($out[1], array('<![CDATA['=>'', ']]>'=>'')); 
            } elseif ($this->CDATA == 'strip') { // Strip CDATA 
                $out[1] = strtr($out[1], array('<![CDATA['=>'', ']]>'=>'')); 
            } 

            // If code page is set convert character encoding to required 
            if ($this->cp != '') 
                //$out[1] = $this->MyConvertEncoding($this->rsscp, $this->cp, $out[1]); 
                $out[1] = iconv($this->rsscp, $this->cp.'//TRANSLIT', $out[1]); 
            // Return result 
            return trim($out[1]); 
        } else { 
        // if there is NO result, return empty string 
            return ''; 
        } 
    } 

    // ------------------------------------------------------------------- 
    // Replace HTML entities &something; by real characters 
    // ------------------------------------------------------------------- 
    function unhtmlentities ($string) { 
        // Get HTML entities table 
        $trans_tbl = get_html_translation_table (HTML_ENTITIES, ENT_QUOTES); 
        // Flip keys<==>values 
        $trans_tbl = array_flip ($trans_tbl); 
        // Add support for &apos; entity (missing in HTML_ENTITIES) 
        $trans_tbl += array('&apos;' => "'"); 
        // Replace entities by values 
        return strtr ($string, $trans_tbl); 
    } 

    // ------------------------------------------------------------------- 
    // Parse() is private method used by Get() to load and parse RSS file. 
    // Don't use Parse() in your scripts - use Get($rss_file) instead. 
    // ------------------------------------------------------------------- 
    function Parse ($rss_url) { 
        // Open and load RSS file 
        if ($f = @fopen($rss_url, 'r')) { 
            $rss_content = ''; 
            while (!feof($f)) { 
                $rss_content .= fgets($f, 4096); 
            } 
            fclose($f); 

            // Parse document encoding 
            $result['encoding'] = $this->my_preg_match("'encoding=[\'\"](.*?)[\'\"]'si", $rss_content); 
            // if document codepage is specified, use it 
            if ($result['encoding'] != '') 
                { $this->rsscp = $result['encoding']; } // This is used in my_preg_match() 
            // otherwise use the default codepage 
            else 
                { $this->rsscp = $this->default_cp; } // This is used in my_preg_match() 

            // Parse CHANNEL info 
            preg_match("'<channel.*?>(.*?)</channel>'si", $rss_content, $out_channel); 
            foreach($this->channeltags as $channeltag) 
            { 
                $temp = $this->my_preg_match("'<$channeltag.*?>(.*?)</$channeltag>'si", $out_channel[1]); 
                if ($temp != '') $result[$channeltag] = $temp; // Set only if not empty 
            } 
            // If date_format is specified and lastBuildDate is valid 
            if ($this->date_format != '' && ($timestamp = strtotime($result['lastBuildDate'])) !==-1) { 
                        // convert lastBuildDate to specified date format 
                        $result['lastBuildDate'] = date($this->date_format, $timestamp); 
            } 

            // Parse TEXTINPUT info 
            preg_match("'<textinput(|[^>]*[^/])>(.*?)</textinput>'si", $rss_content, $out_textinfo); 
                // This a little strange regexp means: 
                // Look for tag <textinput> with or without any attributes, but skip truncated version <textinput /> (it's not beggining tag) 
            if (isset($out_textinfo[2])) { 
                foreach($this->textinputtags as $textinputtag) { 
                    $temp = $this->my_preg_match("'<$textinputtag.*?>(.*?)</$textinputtag>'si", $out_textinfo[2]); 
                    if ($temp != '') $result['textinput_'.$textinputtag] = $temp; // Set only if not empty 
                } 
            } 
            // Parse IMAGE info 
            preg_match("'<image.*?>(.*?)</image>'si", $rss_content, $out_imageinfo); 
            if (isset($out_imageinfo[1])) { 
                foreach($this->imagetags as $imagetag) { 
                    $temp = $this->my_preg_match("'<$imagetag.*?>(.*?)</$imagetag>'si", $out_imageinfo[1]); 
                    if ($temp != '') $result['image_'.$imagetag] = $temp; // Set only if not empty 
                } 
            } 
            // Parse ITEMS 
            preg_match_all("'<item(| .*?)>(.*?)</item>'si", $rss_content, $items); 
            $rss_items = $items[2]; 
            $i = 0; 
            $result['items'] = array(); // create array even if there are no items 
            foreach($rss_items as $rss_item) { 
                // If number of items is lower then limit: Parse one item 
                if ($i < $this->items_limit || $this->items_limit == 0) { 
                    foreach($this->itemtags as $itemtag) { 
                        $temp = $this->my_preg_match("'<$itemtag.*?>(.*?)</$itemtag>'si", $rss_item); 
                        if ($temp != '') $result['items'][$i][$itemtag] = $temp; // Set only if not empty 
                    } 
                    // Strip HTML tags and other bullshit from DESCRIPTION 
                    if ($this->stripHTML && $result['items'][$i]['description']) 
                        $result['items'][$i]['description'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['description']))); 
                    // Strip HTML tags and other bullshit from TITLE 
                    if ($this->stripHTML && $result['items'][$i]['title']) 
                        $result['items'][$i]['title'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['title']))); 
                    // If date_format is specified and pubDate is valid 
                    if ($this->date_format != '' && ($timestamp = strtotime($result['items'][$i]['pubDate'])) !==-1) { 
                        // convert pubDate to specified date format 
                        $result['items'][$i]['pubDate'] = date($this->date_format, $timestamp); 
                    } 
                    // Item counter 
                    $i++; 
                } 
            } 

            $result['items_count'] = $i; 
            return $result; 
        } 
        else // Error in opening return False 
        { 
            return False; 
        } 
    } 
} 

?>
Here you will find the well described Parser Class.
unfortunately i get the following error
Warning: Cannot modify header information - headers already sent by (output started at phpwcms_template/inc_script/frontend_render/external_rss.php:298) in index.php on line 124
any idea?

greetings marcus

ps: sorry for my lousy english :oops:
frold
Posts: 2151
Joined: Tue 25. Nov 2003, 22:42

Post by frold »

did you enable renders in conf.inc.php?

http://www.phpwcms-docu.de/conf.inc.php_en.phtml
$phpwcms["allow_ext_init"] = 0; Should it be allowed to load all scripts before the load of the frontend ( usefull in own PHP-functions) in the /phpwcms_template/inc_script/frontend_init folder of phpWCMS all scripts. Value: 0 = fobidden (standart) / 1 = allowed.

$phpwcms["allow_ext_render"] = 0; Should it be allowed to use the existing functions from the Init folder by rendering the page (/phpwcms_template/inc_script/frontend_render). Value: 0 = forbidden (standard)/ 1 = allowed.
http://www.studmed.dk Portal for doctors and medical students in Denmark
User avatar
marcus@localhorst
Posts: 815
Joined: Fri 28. May 2004, 11:31
Location: localhorst
Contact:

Post by marcus@localhorst »

yes - is enabled.
i've got this problem in the past, and deleted the sample.php as pappnase said and it works, but with the new script, it put out this warning :-(
User avatar
marcus@localhorst
Posts: 815
Joined: Fri 28. May 2004, 11:31
Location: localhorst
Contact:

Post by marcus@localhorst »

i've got the solution!

there where unneeded empty lines after the ?> Tag at the end oft the script in the external_rss.php file

http://www.phpbb.de/doku/kb/artikel.php?artikel=84

greetings marcus
TVKAS
Posts: 23
Joined: Fri 2. Jul 2004, 21:30

Didn't work for me...

Post by TVKAS »

Hello,

I love the idea of {RSS} tag. But I am unable to make this work. I created the file "external_rss.php" with the code provided. But no folder "frontend_render" in "phpwcms_template" so I created this folder and uploaded file.
When I place the tag nothing happens.
"allow_ext_render" is set to 1 so it is O.K.
Am I missing something????

tk
TVKAS
Posts: 23
Joined: Fri 2. Jul 2004, 21:30

I found it...

Post by TVKAS »

I found the correct folder at phpwcms_template/inc_script/frontend_render/. It all works now. Thank you for making this script!!!
User avatar
Oliver Georgi
Site Admin
Posts: 9907
Joined: Fri 3. Oct 2003, 22:22
Contact:

Post by Oliver Georgi »

use dev release if possible - there is a content part for RSS feeds integrated.

Oliver
Oliver Georgi | phpwcms Developer | GitHub | LinkedIn | Систрон
Post Reply