root/trunk/midcom/de.bitfolge.feedcreator/feedcreator.php

Revision 14773, 72.3 kB (checked in by rambo, 8 months ago)

scripted whitespace normalization, see r14772

  • Property svn:keywords set to Author Date Id Revision
Line 
1 <?php
2 /**
3  * @package de.bitfolge.feedcreator
4  */
5 /***************************************************************************
6
7 FeedCreator class v1.7.7(BH)
8 originally (c) Kai Blankenhorn
9 www.bitfolge.de
10 kaib@bitfolge.de
11 v1.3 work by Scott Reynen (scott@randomchaos.com) and Kai Blankenhorn
12 v1.5 OPML support by Dirk Clemens
13
14 This library is free software; you can redistribute it and/or
15 modify it under the terms of the GNU Lesser General Public
16 License as published by the Free Software Foundation; either
17 version 2.1 of the License, or (at your option) any later version.
18
19 This library is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22 Lesser General Public License for more details.
23
24 You should have received a copy of the GNU Lesser General Public
25 License along with this library; if not, write to the Free Software
26 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
28 ****************************************************************************
29
30
31 Changelog:
32
33 v1.7.7(BH)    28-03-06
34     added GPX Feed (Barry Hunter)
35
36
37 v1.7.6(BH)    20-02-06
38     added GeoRSS Feed (Barry Hunter)
39
40
41 v1.7.5(BH)    16-11-05
42     added BASE Feed (Barry Hunter)
43
44 v1.7.4(BH)    05-07-05
45     added KML Feed (Barry Hunter)
46
47 v1.7.3(BH)    05-07-05
48     added PHP Feed (Barry Hunter)
49
50 v1.7.2    10-11-04
51     license changed to LGPL
52
53 v1.7.1
54     fixed a syntax bug
55     fixed left over debug code
56
57 v1.7    07-18-04
58     added HTML and JavaScript feeds (configurable via CSS) (thanks to Pascal Van Hecke)
59     added HTML descriptions for all feed formats (thanks to Pascal Van Hecke)
60     added a switch to select an external stylesheet (thanks to Pascal Van Hecke)
61     changed default content-type to application/xml
62     added character encoding setting
63     fixed numerous smaller bugs (thanks to Sᅵren Fuhrmann of golem.de)
64     improved changing ATOM versions handling (thanks to August Trometer)
65     improved the UniversalFeedCreator's useCached method (thanks to Sᅵren Fuhrmann of golem.de)
66     added charset output in HTTP headers (thanks to Sᅵren Fuhrmann of golem.de)
67     added Slashdot namespace to RSS 1.0 (thanks to Sᅵren Fuhrmann of golem.de)
68
69 v1.6    05-10-04
70     added stylesheet to RSS 1.0 feeds
71     fixed generator comment (thanks Kevin L. Papendick and Tanguy Pruvot)
72     fixed RFC822 date bug (thanks Tanguy Pruvot)
73     added TimeZone customization for RFC8601 (thanks Tanguy Pruvot)
74     fixed Content-type could be empty (thanks Tanguy Pruvot)
75     fixed author/creator in RSS1.0 (thanks Tanguy Pruvot)
76
77 v1.6 beta    02-28-04
78     added Atom 0.3 support (not all features, though)
79     improved OPML 1.0 support (hopefully - added more elements)
80     added support for arbitrary additional elements (use with caution)
81     code beautification :-)
82     considered beta due to some internal changes
83
84 v1.5.1    01-27-04
85     fixed some RSS 1.0 glitches (thanks to Stᅵphane Vanpoperynghe)
86     fixed some inconsistencies between documentation and code (thanks to Timothy Martin)
87
88 v1.5    01-06-04
89     added support for OPML 1.0
90     added more documentation
91
92 v1.4    11-11-03
93     optional feed saving and caching
94     improved documentation
95     minor improvements
96
97 v1.3    10-02-03
98     renamed to FeedCreator, as it not only creates RSS anymore
99     added support for mbox
100     tentative support for echo/necho/atom/pie/???
101
102 v1.2    07-20-03
103     intelligent auto-truncating of RSS 0.91 attributes
104     don't create some attributes when they're not set
105     documentation improved
106     fixed a real and a possible bug with date conversions
107     code cleanup
108
109 v1.1    06-29-03
110     added images to feeds
111     now includes most RSS 0.91 attributes
112     added RSS 2.0 feeds
113
114 v1.0    06-24-03
115     initial release
116
117
118
119 ***************************************************************************/
120
121 /*** GENERAL USAGE *********************************************************
122
123 include("feedcreator.class.php");
124
125 $rss = new UniversalFeedCreator();
126 $rss->useCached(); // use cached version if age<1 hour
127 $rss->title = "PHP news";
128 $rss->description = "daily news from the PHP scripting world";
129
130 //optional
131 $rss->descriptionTruncSize = 500;
132 $rss->descriptionHtmlSyndicated = true;
133
134 $rss->link = "http://www.dailyphp.net/news";
135 $rss->syndicationURL = "http://www.dailyphp.net/".$_SERVER["PHP_SELF"];
136
137 $image = new FeedImage();
138 $image->title = "dailyphp.net logo";
139 $image->url = "http://www.dailyphp.net/images/logo.gif";
140 $image->link = "http://www.dailyphp.net";
141 $image->description = "Feed provided by dailyphp.net. Click to visit.";
142
143 //optional
144 $image->descriptionTruncSize = 500;
145 $image->descriptionHtmlSyndicated = true;
146
147 $rss->image = $image;
148
149 // get your news items from somewhere, e.g. your database:
150 mysql_select_db($dbHost, $dbUser, $dbPass);
151 $res = mysql_query("SELECT * FROM news ORDER BY newsdate DESC");
152 while ($data = mysql_fetch_object($res)) {
153     $item = new FeedItem();
154     $item->title = $data->title;
155     $item->link = $data->url;
156     $item->description = $data->short;
157
158     //optional
159     item->descriptionTruncSize = 500;
160     item->descriptionHtmlSyndicated = true;
161
162     $item->date = $data->newsdate;
163     $item->source = "http://www.dailyphp.net";
164     $item->author = "John Doe";
165
166     $rss->addItem($item);
167 }
168
169 // valid format strings are: RSS0.91, RSS1.0, RSS2.0, PIE0.1 (deprecated),
170 // MBOX, OPML, ATOM, ATOM0.3, HTML, JS, PHP
171 echo $rss->saveFeed("RSS1.0", "news/feed.xml");
172
173
174 ***************************************************************************
175 *          A little setup                                                 *
176 **************************************************************************/
177
178 // your local timezone, set to "" to disable or for GMT
179 define("TIME_ZONE","");
180
181
182
183
184 /**
185  * Version string.
186  */
187 define("FEEDCREATOR_VERSION", "FeedCreator 1.7.6(BH)");
188
189
190
191 /**
192  * A FeedItem is a part of a FeedCreator feed.
193  *
194  * @author Kai Blankenhorn <kaib@bitfolge.de>
195  * @since 1.3
196  * @package de.bitfolge.feedcreator
197  */
198 class FeedItem extends HtmlDescribable {
199     /**
200      * Mandatory attributes of an item.
201      */
202     var $title, $description, $link;
203
204     /**
205      * Optional attributes of an item.
206      */
207     var $author, $authorEmail, $authorURL,$image, $category, $categoryScheme, $comments, $guid, $source, $creator, $contributor, $lat, $long, $thumb;
208
209     /**
210      * Publishing date of an item. May be in one of the following formats:
211      *
212      *    RFC 822:
213      *    "Mon, 20 Jan 03 18:05:41 +0400"
214      *    "20 Jan 03 18:05:41 +0000"
215      *
216      *    ISO 8601:
217      *    "2003-01-20T18:05:41+04:00"
218      *
219      *    Unix:
220      *    1043082341
221      */
222     var $date;
223
224     /**
225      * Add <enclosure> element tag RSS 2.0, supported by ATOM 1.0 too
226      * modified by : Mohammad Hafiz bin Ismail (mypapit@gmail.com)
227      *
228      *
229      * display :
230      * <enclosure length="17691" url="http://something.com/picture.jpg" type="image/jpeg" />
231      *
232      */
233     var $enclosure;
234
235     /**
236      * Any additional elements to include as an associated array. All $key => $value pairs
237      * will be included unencoded in the feed item in the form
238      *     <$key>$value</$key>
239      * Again: No encoding will be used! This means you can invalidate or enhance the feed
240      * if $value contains markup. This may be abused to embed tags not implemented by
241      * the FeedCreator class used.
242      */
243     var $additionalElements = Array();
244
245     // on hold
246     // var $source;
247 }
248
249
250
251 /**
252  * A FeedImage may be added to a FeedCreator feed.
253  * @author Kai Blankenhorn <kaib@bitfolge.de>
254  * @since 1.3
255  * @package de.bitfolge.feedcreator
256  */
257 class FeedImage extends HtmlDescribable {
258     /**
259      * Mandatory attributes of an image.
260      */
261     var $title, $url, $link;
262
263     /**
264      * Optional attributes of an image.
265      */
266     var $width, $height, $description;
267 }
268
269
270
271 /**
272  * An HtmlDescribable is an item within a feed that can have a description that may
273  * include HTML markup.
274  *
275  * @package de.bitfolge.feedcreator
276  */
277 class HtmlDescribable {
278     /**
279      * Indicates whether the description field should be rendered in HTML.
280      */
281     var $descriptionHtmlSyndicated;
282
283     /**
284      * Indicates whether and to how many characters a description should be truncated.
285      */
286     var $descriptionTruncSize;
287
288     /**
289      * Returns a formatted description field, depending on descriptionHtmlSyndicated and
290      * $descriptionTruncSize properties
291      * @return    string    the formatted description
292      */
293     function getDescription($overrideSyndicateHtml = false) {
294         $descriptionField = new FeedHtmlField($this->description);
295         $descriptionField->syndicateHtml = $overrideSyndicateHtml || $this->descriptionHtmlSyndicated;
296         $descriptionField->truncSize = $this->descriptionTruncSize;
297         return $descriptionField->output();
298     }
299
300 }
301
302
303 /**
304  * A FeedHtmlField describes and generates
305  * a feed, item or image html field (probably a description). Output is
306  * generated based on $truncSize, $syndicateHtml properties.
307  *
308  * @author Pascal Van Hecke <feedcreator.class.php@vanhecke.info>
309  * @version 1.6
310  * @package de.bitfolge.feedcreator
311  */
312 class FeedHtmlField {
313     /**
314      * Mandatory attributes of a FeedHtmlField.
315      */
316     var $rawFieldContent;
317
318     /**
319      * Optional attributes of a FeedHtmlField.
320      *
321      */
322     var $truncSize, $syndicateHtml;
323
324     /**
325      * Creates a new instance of FeedHtmlField.
326      * @param  $string: if given, sets the rawFieldContent property
327      */
328     function FeedHtmlField($parFieldContent) {
329         if ($parFieldContent) {
330             $this->rawFieldContent = $parFieldContent;
331         }
332     }
333
334
335     /**
336      * Creates the right output, depending on $truncSize, $syndicateHtml properties.
337      * @return string    the formatted field
338      */
339     function output() {
340         // when field available and syndicated in html we assume
341         // - valid html in $rawFieldContent and we enclose in CDATA tags
342         // - no truncation (truncating risks producing invalid html)
343         if (!$this->rawFieldContent) {
344             $result = "";
345         }    elseif ($this->syndicateHtml) {
346             $result = "<![CDATA[".$this->rawFieldContent."]]>";
347         } else {
348             if ($this->truncSize and is_int($this->truncSize)) {
349                 $result = FeedCreator::iTrunc(htmlspecialchars($this->rawFieldContent),$this->truncSize);
350             } else {
351                 $result = htmlspecialchars($this->rawFieldContent);
352             }
353         }
354         return $result;
355     }
356
357 }
358
359
360
361 /**
362  * UniversalFeedCreator lets you choose during runtime which
363  * format to build.
364  * For general usage of a feed class, see the FeedCreator class
365  * below or the example above.
366  *
367  * @since 1.3
368  * @author Kai Blankenhorn <kaib@bitfolge.de>
369  * @package de.bitfolge.feedcreator
370  */
371 class UniversalFeedCreator extends FeedCreator {
372     var $_feed;
373
374     function _setFormat($format) {
375         switch (strtoupper($format)) {
376
377             case "BASE":
378                 $this->format = $format;
379             case "2.0":
380                 // fall through
381             case "RSS2.0":
382                 $this->_feed = new RSSCreator20();
383                 break;
384
385             case "GEOPHOTORSS":
386             case "PHOTORSS":
387             case "GEORSS":
388                 $this->format = $format;
389             case "1.0":
390                 // fall through
391             case "RSS1.0":
392                 $this->_feed = new RSSCreator10();
393                 break;
394
395             case "0.91":
396                 // fall through
397             case "RSS0.91":
398                 $this->_feed = new RSSCreator091();
399                 break;
400
401             case "PIE0.1":
402                 $this->_feed = new PIECreator01();
403                 break;
404
405             case "MBOX":
406                 $this->_feed = new MBOXCreator();
407                 break;
408
409             case "OPML":
410                 $this->_feed = new OPMLCreator();
411                 break;
412
413             case "TOOLBAR":
414                 $this->format = $format;
415
416             case "ATOM":
417                 // fall through: always the latest ATOM version
418             case "ATOM1.0":
419                 $this->_feed = new AtomCreator10();
420                 break;
421
422             case "ATOM0.3":
423                 $this->_feed = new AtomCreator03();
424                 break;
425
426             case "HTML":
427                 $this->_feed = new HTMLCreator();
428                 break;
429
430             case "PHP":
431                 $this->_feed = new PHPCreator();
432                 break;
433             case "GPX":
434                 $this->_feed = new GPXCreator();
435                 break;
436             case "KML":
437                 $this->_feed = new KMLCreator();
438                 break;
439             case "JS":
440                 // fall through
441             case "JAVASCRIPT":
442                 $this->_feed = new JSCreator();
443                 break;
444
445             default:
446                 $this->_feed = new RSSCreator091();
447                 break;
448         }
449
450         $vars = get_object_vars($this);
451         foreach ($vars as $key => $value) {
452             // prevent overwriting of properties "contentType", "encoding"; do not copy "_feed" itself
453             if (!in_array($key, array("_feed", "contentType", "encoding"))) {
454                 $this->_feed->{$key} = $this->{$key};
455             }
456         }
457     }
458
459     /**
460      * Creates a syndication feed based on the items previously added.
461      *
462      * @see        FeedCreator::addItem()
463      * @param    string    format    format the feed should comply to. Valid values are:
464      *            "PIE0.1", "mbox", "RSS0.91", "RSS1.0", "RSS2.0", "OPML", "ATOM0.3", "HTML", "JS"
465      * @return    string    the contents of the feed.
466      */
467     function createFeed($format = "RSS0.91") {
468         $this->_setFormat($format);
469         return $this->_feed->createFeed();
470     }
471
472
473
474     /**
475      * Saves this feed as a file on the local disk. After the file is saved, an HTTP redirect
476      * header may be sent to redirect the use to the newly created file.
477      * @since 1.4
478      *
479      * @param    string    format    format the feed should comply to. Valid values are:
480      *            "PIE0.1" (deprecated), "mbox", "RSS0.91", "RSS1.0", "RSS2.0", "OPML", "ATOM", "ATOM0.3", "HTML", "JS"
481      * @param    string    filename    optional    the filename where a recent version of the feed is saved. If not specified, the filename is $_SERVER["PHP_SELF"] with the extension changed to .xml (see _generateFilename()).
482      * @param    boolean    displayContents    optional    send the content of the file or not. If true, the file will be sent in the body of the response.
483      */
484     function saveFeed($format="RSS0.91", $filename="", $displayContents=true) {
485         $this->_setFormat($format);
486         $this->_feed->saveFeed($filename, $displayContents);
487     }
488
489
490    /**
491     * Turns on caching and checks if there is a recent version of this feed in the cache.
492     * If there is, an HTTP redirect header is sent.
493     * To effectively use caching, you should create the FeedCreator object and call this method
494     * before anything else, especially before you do the time consuming task to build the feed
495     * (web fetching, for example).
496     *
497     * @param   string   format   format the feed should comply to. Valid values are:
498     *       "PIE0.1" (deprecated), "mbox", "RSS0.91", "RSS1.0", "RSS2.0", "OPML", "ATOM0.3".
499     * @param filename   string   optional the filename where a recent version of the feed is saved. If not specified, the filename is $_SERVER["PHP_SELF"] with the extension changed to .xml (see _generateFilename()).
500     * @param timeout int      optional the timeout in seconds before a cached version is refreshed (defaults to 3600 = 1 hour)
501     */
502    function useCached($format="RSS0.91", $filename="", $timeout=3600) {
503       $this->_setFormat($format);
504       $this->_feed->useCached($filename, $timeout);
505    }
506
507 }
508
509
510 /**
511  * FeedCreator is the abstract base implementation for concrete
512  * implementations that implement a specific format of syndication.
513  *
514  * @abstract
515  * @author Kai Blankenhorn <kaib@bitfolge.de>
516  * @since 1.4
517  * @package de.bitfolge.feedcreator
518  */
519 class FeedCreator extends HtmlDescribable {
520
521     /**
522      * Mandatory attributes of a feed.
523      */
524     var $title, $description, $link;
525     var $format = 'BASE';
526
527     /**
528      * Optional attributes of a feed.
529      */
530     var $syndicationURL, $image, $language, $copyright, $pubDate, $lastBuildDate, $editor, $editorEmail, $webmaster, $category, $docs, $ttl, $rating, $skipHours, $skipDays;
531
532     /**
533      * The url of the external xsl stylesheet used to format the naked rss feed.
534      * Ignored in the output when empty.
535      */
536     var $xslStyleSheet = "";
537
538
539     /**
540      * @access private
541      */
542     var $items = Array();
543
544     /**
545      * Generator string
546      *
547      */
548
549      var $generator = "info@mypapit.net";
550
551     /**
552      * This feed's MIME content type.
553      * @since 1.4
554      * @access private
555      */
556     var $contentType = "application/xml";
557
558
559     /**
560      * This feed's character encoding.
561      * @since 1.6.1
562      */
563     var $encoding = "UTF-8"; //"ISO-8859-1";
564
565
566     /**
567      * Any additional elements to include as an associated array. All $key => $value pairs
568      * will be included unencoded in the feed in the form
569      *     <$key>$value</$key>
570      * Again: No encoding will be used! This means you can invalidate or enhance the feed
571      * if $value contains markup. This may be abused to embed tags not implemented by
572      * the FeedCreator class used.
573      */
574     var $additionalElements = Array();
575
576
577     /**
578      * Adds a FeedItem to the feed.
579      *
580      * @param object FeedItem $item The FeedItem to add to the feed.
581      * @access public
582      */
583     function addItem($item) {
584         $this->items[] = $item;
585     }
586
587     /**
588      *
589      *
590      *
591      */
592      function version() {
593
594          return FEEDCREATOR_VERSION." (".$this->generator.")";
595      }
596
597     /**
598      * Truncates a string to a certain length at the most sensible point.
599      * First, if there's a '.' character near the end of the string, the string is truncated after this character.
600      * If there is no '.', the string is truncated after the last ' ' character.
601      * If the string is truncated, " ..." is appended.
602      * If the string is already shorter than $length, it is returned unchanged.
603      *
604      * @static
605      * @param string    string A string to be truncated.
606      * @param int        length the maximum length the string should be truncated to
607      * @return string    the truncated string
608      */
609     function iTrunc($string, $length) {
610         if (strlen($string)<=$length) {
611             return $string;
612         }
613
614         $pos = strrpos($string,".");
615         if ($pos>=$length-4) {
616             $string = substr($string,0,$length-4);
617             $pos = strrpos($string,".");
618         }
619         if ($pos>=$length*0.4) {
620             return substr($string,0,$pos+1)." ...";
621         }
622
623         $pos = strrpos($string," ");
624         if ($pos>=$length-4) {
625             $string = substr($string,0,$length-4);
626             $pos = strrpos($string," ");
627         }
628         if ($pos>=$length*0.4) {
629             return substr($string,0,$pos)." ...";
630         }
631
632         return substr($string,0,$length-4)." ...";
633
634     }
635
636
637     /**
638      * Creates a comment indicating the generator of this feed.
639      * The format of this comment seems to be recognized by
640      * Syndic8.com.
641      */
642     function _createGeneratorComment() {
643         return "<!-- generator=\"".FEEDCREATOR_VERSION."\" -->\n";
644     }
645
646
647     /**
648      * Creates a string containing all additional elements specified in
649      * $additionalElements.
650      * @param    elements    array    an associative array containing key => value pairs
651      * @param indentString    string    a string that will be inserted before every generated line
652      * @return    string    the XML tags corresponding to $additionalElements
653      */
654     function _createAdditionalElements($elements, $indentString="") {
655         $ae = "";
656         if (is_array($elements)) {
657             foreach($elements AS $key => $value) {
658                 $ae.= $indentString."<$key>$value</$key>\n";
659             }
660         }
661         return $ae;
662     }
663
664     function _createStylesheetReferences() {
665         $xml = "";
666         if (!empty($this->cssStyleSheet)) $xml .= "<?xml-stylesheet href=\"".$this->cssStyleSheet."\" type=\"text/css\"?>\n";
667         if (!empty($this->xslStyleSheet)) $xml .= "<?xml-stylesheet href=\"".$this->xslStyleSheet."\" type=\"text/xsl\"?>\n";
668         return $xml;
669     }
670
671
672     /**
673      * Builds the feed's text.
674      * @abstract
675      * @return    string    the feed's complete text
676      */
677     function createFeed() {
678     }
679
680     /**
681      * Generate a filename for the feed cache file. The result will be $_SERVER["PHP_SELF"] with the extension changed to .xml.
682      * For example:
683      *
684      * echo $_SERVER["PHP_SELF"]."\n";
685      * echo FeedCreator::_generateFilename();
686      *
687      * would produce:
688      *
689      * /rss/latestnews.php
690      * latestnews.xml
691      *
692      * @return string the feed cache filename
693      * @since 1.4
694      * @access private
695      */
696     function _generateFilename() {
697         $fileInfo = pathinfo($_SERVER["PHP_SELF"]);
698         return substr($fileInfo["basename"],0,-(strlen($fileInfo["extension"])+1)).".xml";
699     }
700
701
702     /**
703      * @since 1.4
704      * @access private
705      */
706     function _redirect($filename) {
707