OSDN Git Service

Update UPDATING documents for Release 1.5.0 and 1.5.1
[pukiwiki/pukiwiki.git] / plugin / showrss.inc.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone
3 // showrss.inc.php
4 // Copyright:
5 //     2002-2016 PukiWiki Development Team
6 //     2002      PANDA <panda@arino.jp>
7 //     (Original)hiro_do3ob@yahoo.co.jp
8 // License: GPL, same as PukiWiki
9 //
10 // Show RSS (of remote site) plugin
11 // NOTE:
12 //    * This plugin needs 'PHP xml extension'
13 //    * Cache data will be stored as CACHE_DIR/*.tmp
14
15 define('PLUGIN_SHOWRSS_USAGE', '#showrss(URI-to-RSS[,default|menubar|recent[,Cache-lifetime[,Show-timestamp]]])');
16
17 // Show related extensions are found or not
18 function plugin_showrss_action()
19 {
20         if (PKWK_SAFE_MODE) die_message('PKWK_SAFE_MODE prohibit this');
21
22         $body = '';
23         foreach(array('xml', 'mbstring') as $extension){
24                 $$extension = extension_loaded($extension) ?
25                         '&color(green){Found};' :
26                         '&color(red){Not found};';
27                 $body .= '| ' . $extension . ' extension | ' . $$extension . ' |' . "\n";
28         }
29         return array('msg' => 'showrss_info', 'body' => convert_html($body));
30 }
31
32 function plugin_showrss_convert()
33 {
34         static $_xml;
35
36         if (! isset($_xml)) $_xml = extension_loaded('xml');
37         if (! $_xml) return '#showrss: xml extension is not found<br />' . "\n";
38
39         $num = func_num_args();
40         if ($num == 0) return PLUGIN_SHOWRSS_USAGE . '<br />' . "\n";
41
42         $argv = func_get_args();
43         $timestamp = FALSE;
44         $cachehour = 0;
45         $template = $uri = '';
46         switch ($num) {
47         case 4: $timestamp = (trim($argv[3]) == '1');   /*FALLTHROUGH*/
48         case 3: $cachehour = trim($argv[2]);            /*FALLTHROUGH*/
49         case 2: $template  = strtolower(trim($argv[1]));/*FALLTHROUGH*/
50         case 1: $uri       = trim($argv[0]);
51         }
52
53         $class = ($template == '' || $template == 'default') ? 'ShowRSS_html' : 'ShowRSS_html_' . $template;
54         if (! is_numeric($cachehour))
55                 return '#showrss: Cache-lifetime seems not numeric: ' . htmlsc($cachehour) . '<br />' . "\n";
56         if (! class_exists($class))
57                 return '#showrss: Template not found: ' . htmlsc($template) . '<br />' . "\n";
58         if (! is_url($uri))
59                 return '#showrss: Seems not URI: ' . htmlsc($uri) . '<br />' . "\n";
60
61         list($rss, $time) = plugin_showrss_get_rss($uri, $cachehour);
62         if ($rss === FALSE) return '#showrss: Failed fetching RSS from the server<br />' . "\n";
63
64         $time = '';
65         if ($timestamp > 0) {
66                 $time = '<p style="font-size:10px; font-weight:bold">Last-Modified:' .
67                         get_date('Y/m/d H:i:s', $time) .  '</p>';
68         }
69
70         $obj = new $class($rss);
71         return $obj->toString($time);
72 }
73
74 // Create HTML from RSS array()
75 class ShowRSS_html
76 {
77         var $items = array();
78         var $class = '';
79
80         function ShowRSS_html($rss)
81         {
82                 foreach ($rss as $date=>$items) {
83                         foreach ($items as $item) {
84                                 $link  = $item['LINK'];
85                                 $title = $item['TITLE'];
86                                 $passage = get_passage($item['_TIMESTAMP']);
87                                 $link = '<a href="' . $link . '" title="' .  $title . ' ' .
88                                         $passage . '" rel="nofollow">' . $title . '</a>';
89                                 $this->items[$date][] = $this->format_link($link);
90                         }
91                 }
92         }
93
94         function format_link($link)
95         {
96                 return $link . '<br />' . "\n";
97         }
98
99         function format_list($date, $str)
100         {
101                 return $str;
102         }
103
104         function format_body($str)
105         {
106                 return $str;
107         }
108
109         function toString($timestamp)
110         {
111                 $retval = '';
112                 foreach ($this->items as $date=>$items)
113                         $retval .= $this->format_list($date, join('', $items));
114                 $retval = $this->format_body($retval);
115                 return <<<EOD
116 <div{$this->class}>
117 $retval$timestamp
118 </div>
119 EOD;
120         }
121 }
122
123 class ShowRSS_html_menubar extends ShowRSS_html
124 {
125         var $class = ' class="small"';
126
127         function format_link($link) {
128                 return '<li>' . $link . '</li>' . "\n";
129         }
130
131         function format_body($str) {
132                 return '<ul class="recent_list">' . "\n" . $str . '</ul>' . "\n";
133         }
134 }
135
136 class ShowRSS_html_recent extends ShowRSS_html
137 {
138         var $class = ' class="small"';
139
140         function format_link($link) {
141                 return '<li>' . $link . '</li>' . "\n";
142         }
143
144         function format_list($date, $str) {
145                 return '<strong>' . $date . '</strong>' . "\n" .
146                         '<ul class="recent_list">' . "\n" . $str . '</ul>' . "\n";
147         }
148 }
149
150 // Get and save RSS
151 function plugin_showrss_get_rss($target, $cachehour)
152 {
153         $buf  = '';
154         $time = NULL;
155         if ($cachehour) {
156                 // Remove expired cache
157                 plugin_showrss_cache_expire($cachehour);
158
159                 // Get the cache not expired
160                 $filename = CACHE_DIR . encode($target) . '.tmp';
161                 if (is_readable($filename)) {
162                         $buf  = join('', file($filename));
163                         $time = filemtime($filename) - LOCALZONE;
164                 }
165         }
166
167         if ($time === NULL) {
168                 // Newly get RSS
169                 $data = pkwk_http_request($target);
170                 if ($data['rc'] !== 200)
171                         return array(FALSE, 0);
172
173                 $buf = $data['data'];
174                 $time = UTIME;
175
176                 // Save RSS into cache
177                 if ($cachehour) {
178                         $fp = fopen($filename, 'w');
179                         fwrite($fp, $buf);
180                         fclose($fp);
181                 }
182         }
183
184         // Parse
185         $obj = new ShowRSS_XML();
186         return array($obj->parse($buf),$time);
187 }
188
189 // Remove cache if expired limit exeed
190 function plugin_showrss_cache_expire($cachehour)
191 {
192         $expire = $cachehour * 60 * 60; // Hour
193         $dh = dir(CACHE_DIR);
194         while (($file = $dh->read()) !== FALSE) {
195                 if (substr($file, -4) != '.tmp') continue;
196                 $file = CACHE_DIR . $file;
197                 $last = time() - filemtime($file);
198                 if ($last > $expire) unlink($file);
199         }
200         $dh->close();
201 }
202
203 // Get RSS and array() them
204 class ShowRSS_XML
205 {
206         var $items;
207         var $item;
208         var $is_item;
209         var $tag;
210         var $encoding;
211
212         function parse($buf)
213         {
214                 $this->items   = array();
215                 $this->item    = array();
216                 $this->is_item = FALSE;
217                 $this->tag     = '';
218
219                 // Detect encoding
220                 $matches = array();
221                 if(preg_match('/<\?xml [^>]*\bencoding="([a-z0-9-_]+)"/i', $buf, $matches)) {
222                         $this->encoding = $matches[1];
223                 } else {
224                         $this->encoding = mb_detect_encoding($buf);
225                 }
226
227                 // Normalize to UTF-8 / ASCII
228                 if (! in_array(strtolower($this->encoding), array('us-ascii', 'iso-8859-1', 'utf-8'))) {
229                         $buf = mb_convert_encoding($buf, 'utf-8', $this->encoding);
230                         $this->encoding = 'utf-8';
231                 }
232
233                 // Parsing
234                 $xml_parser = xml_parser_create($this->encoding);
235                 xml_set_element_handler($xml_parser, array(& $this, 'start_element'), array(& $this, 'end_element'));
236                 xml_set_character_data_handler($xml_parser, array(& $this, 'character_data'));
237                 if (! xml_parse($xml_parser, $buf, 1)) {
238                         return(sprintf('XML error: %s at line %d in %s',
239                                 xml_error_string(xml_get_error_code($xml_parser)),
240                                 xml_get_current_line_number($xml_parser), $buf));
241                 }
242                 xml_parser_free($xml_parser);
243
244                 return $this->items;
245         }
246
247         function escape($str)
248         {
249                 // Unescape already-escaped chars (&lt;, &gt;, &amp;, ...) in RSS body before htmlsc()
250                 $str = strtr($str, array_flip(get_html_translation_table(ENT_COMPAT)));
251                 // Escape
252                 $str = htmlsc($str);
253                 // Encoding conversion
254                 $str = mb_convert_encoding($str, SOURCE_ENCODING, $this->encoding);
255                 return trim($str);
256         }
257
258         // Tag start
259         function start_element($parser, $name, $attrs)
260         {
261                 if ($this->is_item) {
262                         $this->tag     = $name;
263                 } else if ($name == 'ITEM') {
264                         $this->is_item = TRUE;
265                 }
266         }
267
268         // Tag end
269         function end_element($parser, $name)
270         {
271                 if (! $this->is_item || $name != 'ITEM') return;
272
273                 $item = array_map(array(& $this, 'escape'), $this->item);
274                 $this->item = array();
275
276                 if (isset($item['DC:DATE'])) {
277                         $time = plugin_showrss_get_timestamp($item['DC:DATE']);
278                         
279                 } else if (isset($item['PUBDATE'])) {
280                         $time = plugin_showrss_get_timestamp($item['PUBDATE']);
281                         
282                 } else if (isset($item['DESCRIPTION']) &&
283                         ($description = trim($item['DESCRIPTION'])) != '' &&
284                         ($time = strtotime($description)) != -1) {
285                                 $time -= LOCALZONE;
286
287                 } else {
288                         $time = time() - LOCALZONE;
289                 }
290                 $item['_TIMESTAMP'] = $time;
291                 $date = get_date('Y-m-d', $item['_TIMESTAMP']);
292
293                 $this->items[$date][] = $item;
294                 $this->is_item        = FALSE;
295         }
296
297         function character_data($parser, $data)
298         {
299                 if (! $this->is_item) return;
300                 if (! isset($this->item[$this->tag])) $this->item[$this->tag] = '';
301                 $this->item[$this->tag] .= $data;
302         }
303 }
304
305 function plugin_showrss_get_timestamp($str)
306 {
307         $str = trim($str);
308         if ($str == '') return UTIME;
309
310         $matches = array();
311         if (preg_match('/(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})(([+-])(\d{2}):(\d{2}))?/', $str, $matches)) {
312                 $time = strtotime($matches[1] . ' ' . $matches[2]);
313                 if ($time == -1) {
314                         $time = UTIME;
315                 } else if ($matches[3]) {
316                         $diff = ($matches[5] * 60 + $matches[6]) * 60;
317                         $time += ($matches[4] == '-' ? $diff : -$diff);
318                 }
319                 return $time;
320         } else {
321                 $time = strtotime($str);
322                 return ($time == -1) ? UTIME : $time - LOCALZONE;
323         }
324 }