OSDN Git Service

9968214411c5c626ff94accba2a3337abb834c03
[pukiwiki/pukiwiki.git] / plugin / showrss.inc.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone
3 // showrss.inc.php
4 // Copyright:
5 //     2002-2017 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         // Remove old caches in 5% rate
62         if (mt_rand(1, 20) === 1) {
63                 plugin_showrss_cache_expire(24);
64         }
65         list($rss, $time) = plugin_showrss_get_rss($uri, $cachehour);
66         if ($rss === FALSE) return '#showrss: Failed fetching RSS from the server<br />' . "\n";
67         if (! is_array($rss)) {
68                 // Show XML error message
69                 return '#showrss: Error - ' . htmlsc($rss) . '<br />' . "\n";
70         }
71         $time_display = '';
72         if ($timestamp > 0) {
73                 $time_display = '<p style="font-size:10px; font-weight:bold">Last-Modified:' .
74                         get_date('Y/m/d H:i:s', $time) .  '</p>';
75         }
76
77         $obj = new $class($rss);
78         return $obj->toString($time_display);
79 }
80
81 // Create HTML from RSS array()
82 class ShowRSS_html
83 {
84         var $items = array();
85         var $class = '';
86
87         function ShowRSS_html($rss)
88         {
89                 $this->__construct($rss);
90         }
91         function __construct($rss)
92         {
93                 foreach ($rss as $date=>$items) {
94                         foreach ($items as $item) {
95                                 $link  = $item['LINK'];
96                                 $title = $item['TITLE'];
97                                 $passage = get_passage($item['_TIMESTAMP']);
98                                 $link = '<a href="' . $link . '" title="' .  $title . ' ' .
99                                         $passage . '" rel="nofollow">' . $title . '</a>';
100                                 $this->items[$date][] = $this->format_link($link);
101                         }
102                 }
103         }
104
105         function format_link($link)
106         {
107                 return $link . '<br />' . "\n";
108         }
109
110         function format_list($date, $str)
111         {
112                 return $str;
113         }
114
115         function format_body($str)
116         {
117                 return $str;
118         }
119
120         function toString($timestamp)
121         {
122                 $retval = '';
123                 foreach ($this->items as $date=>$items)
124                         $retval .= $this->format_list($date, join('', $items));
125                 $retval = $this->format_body($retval);
126                 return <<<EOD
127 <div{$this->class}>
128 $retval$timestamp
129 </div>
130 EOD;
131         }
132 }
133
134 class ShowRSS_html_menubar extends ShowRSS_html
135 {
136         var $class = ' class="small"';
137
138         function format_link($link) {
139                 return '<li>' . $link . '</li>' . "\n";
140         }
141
142         function format_body($str) {
143                 return '<ul class="recent_list">' . "\n" . $str . '</ul>' . "\n";
144         }
145 }
146
147 class ShowRSS_html_recent extends ShowRSS_html
148 {
149         var $class = ' class="small"';
150
151         function format_link($link) {
152                 return '<li>' . $link . '</li>' . "\n";
153         }
154
155         function format_list($date, $str) {
156                 return '<strong>' . $date . '</strong>' . "\n" .
157                         '<ul class="recent_list">' . "\n" . $str . '</ul>' . "\n";
158         }
159 }
160
161 // Get and save RSS
162 function plugin_showrss_get_rss($target, $cachehour)
163 {
164         $buf  = '';
165         $time = NULL;
166         if ($cachehour) {
167                 $filename = CACHE_DIR . encode($target) . '.tmp';
168                 // Remove expired cache
169                 plugin_showrss_cache_expire_file($filename, $cachehour);
170                 // Get the cache not expired
171                 if (is_readable($filename)) {
172                         $buf  = join('', file($filename));
173                         $time = filemtime($filename) - LOCALZONE;
174                 }
175         }
176
177         if (is_null($time)) {
178                 // Newly get RSS
179                 $data = pkwk_http_request($target);
180                 if ($data['rc'] !== 200) {
181                         return array(FALSE, 0);
182                 }
183                 $buf = $data['data'];
184                 $time = UTIME;
185
186                 // Save RSS into cache
187                 if ($cachehour) {
188                         $fp = fopen($filename, 'w');
189                         fwrite($fp, $buf);
190                         fclose($fp);
191                 }
192         }
193         // Parse
194         $obj = new ShowRSS_XML();
195         $obj->modified_date = (is_null($time) ? UTIME : $time);
196         return array($obj->parse($buf),$time);
197 }
198
199 // Remove cache if expired limit exeed
200 function plugin_showrss_cache_expire($cachehour)
201 {
202         $expire = $cachehour * 60 * 60; // Hour
203         $dh = dir(CACHE_DIR);
204         while (($file = $dh->read()) !== FALSE) {
205                 if (substr($file, -4) != '.tmp') continue;
206                 $file = CACHE_DIR . $file;
207                 $last = time() - filemtime($file);
208                 if ($last > $expire) unlink($file);
209         }
210         $dh->close();
211 }
212
213 /**
214  * Remove single file cache if expired limit exeed
215  * @param $filename
216  * @param $cachehour
217  */
218 function plugin_showrss_cache_expire_file($filename, $cachehour)
219 {
220         $expire = $cachehour * 60 * 60; // Hour
221         $last = time() - filemtime($filename);
222         if ($last > $expire) {
223                 unlink($filename);
224         }
225 }
226
227 // Get RSS and array() them
228 class ShowRSS_XML
229 {
230         var $items;
231         var $item;
232         var $is_item;
233         var $tag;
234         var $encoding;
235         var $modified_date;
236
237         function parse($buf)
238         {
239                 $this->items   = array();
240                 $this->item    = array();
241                 $this->is_item = FALSE;
242                 $this->tag     = '';
243                 $utf8 = 'UTF-8';
244                 $this->encoding = $utf8;
245                 // Detect encoding
246                 $matches = array();
247                 if(preg_match('/<\?xml [^>]*\bencoding="([a-z0-9-_]+)"/i', $buf, $matches)) {
248                         $encoding = $matches[1];
249                         if (strtoupper($encoding) !== $utf8) {
250                                 // xml_parse() fails on non UTF-8 encoding attr in XML decLaration
251                                 $buf = preg_replace('/<\?xml ([^>]*)\bencoding="[a-z0-9-_]+"/i', '<?xml $1', $buf);
252                                 // xml_parse() requires UTF-8 compatible encoding
253                                 $buf = mb_convert_encoding($buf, $utf8, $encoding);
254                         }
255                 }
256                 // Parsing
257                 $xml_parser = xml_parser_create($utf8);
258                 xml_set_element_handler($xml_parser, array(& $this, 'start_element'), array(& $this, 'end_element'));
259                 xml_set_character_data_handler($xml_parser, array(& $this, 'character_data'));
260                 if (! xml_parse($xml_parser, $buf, 1)) {
261                         return sprintf('XML error: %s at line %d in %s',
262                                 xml_error_string(xml_get_error_code($xml_parser)),
263                                 xml_get_current_line_number($xml_parser),
264                                 (strlen($buf) < 500 ? $buf : substr($buf, 0, 500) . '...'));
265                 }
266                 xml_parser_free($xml_parser);
267                 return $this->items;
268         }
269
270         function escape($str)
271         {
272                 // Unescape already-escaped chars (&lt;, &gt;, &amp;, ...) in RSS body before htmlsc()
273                 $str = strtr($str, array_flip(get_html_translation_table(ENT_COMPAT)));
274                 // Escape
275                 $str = htmlsc($str);
276                 // Encoding conversion
277                 $str = mb_convert_encoding($str, SOURCE_ENCODING, $this->encoding);
278                 return trim($str);
279         }
280
281         // Tag start
282         function start_element($parser, $name, $attrs)
283         {
284                 if ($this->is_item) {
285                         $this->tag     = $name;
286                 } else if ($name == 'ITEM') {
287                         $this->is_item = TRUE;
288                 }
289         }
290
291         // Tag end
292         function end_element($parser, $name)
293         {
294                 if (! $this->is_item || $name != 'ITEM') return;
295
296                 $item = array_map(array(& $this, 'escape'), $this->item);
297                 $this->item = array();
298
299                 if (isset($item['DC:DATE'])) {
300                         $time = plugin_showrss_get_timestamp($item['DC:DATE'], $this->modified_date);
301                         
302                 } else if (isset($item['PUBDATE'])) {
303                         $time = plugin_showrss_get_timestamp($item['PUBDATE'], $this->modified_date);
304                 } else {
305                         $time_from_desc = FALSE;
306                         if (isset($item['DESCRIPTION']) &&
307                                 (($description = trim($item['DESCRIPTION'])) != '')) {
308                                 $time_from_desc = strtotime($description);
309                         }
310                         if ($time_from_desc !== FALSE && $time_from_desc !== -1) {
311                                 $time = $time_from_desc - LOCALZONE;
312                         } else {
313                                 $time = time() - LOCALZONE;
314                         }
315                 }
316                 $item['_TIMESTAMP'] = $time;
317                 $date = get_date('Y-m-d', $item['_TIMESTAMP']);
318
319                 $this->items[$date][] = $item;
320                 $this->is_item        = FALSE;
321         }
322
323         function character_data($parser, $data)
324         {
325                 if (! $this->is_item) return;
326                 if (! isset($this->item[$this->tag])) $this->item[$this->tag] = '';
327                 $this->item[$this->tag] .= $data;
328         }
329 }
330
331 function plugin_showrss_get_timestamp($str, $default_date)
332 {
333         $str = trim($str);
334         if ($str == '') return UTIME;
335
336         $matches = array();
337         if (preg_match('/(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})(([+-])(\d{2}):(\d{2}))?/', $str, $matches)) {
338                 $time = strtotime($matches[1] . ' ' . $matches[2]);
339                 if ($time === FALSE || $time === -1) {
340                         $time = $default_date;
341                 } else if (isset($matches[3])) {
342                         $diff = ($matches[5] * 60 + $matches[6]) * 60;
343                         $time += ($matches[4] == '-' ? $diff : -$diff);
344                 }
345                 return $time;
346         } else {
347                 $time = strtotime($str);
348                 return ($time === FALSE || $time === -1) ? $default_date : $time - LOCALZONE;
349         }
350 }