rss_converter_twitter.com.xsl: update XPath of tweet content
[tweeper.git] / tweeper.php
1 <?php
2 /*
3  * tweeper - a Twitter to RSS web scraper
4  *
5  * Copyright (C) 2013-2015  Antonio Ospite <ao2@ao2.it>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 require_once 'XML/Serializer.php';
22
23 date_default_timezone_set('UTC');
24
25 class Tweeper {
26
27   private static $USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20130405 Firefox/22.0";
28
29   public function __construct($generate_enclosure = FALSE) {
30     $this->generate_enclosure = $generate_enclosure;
31   }
32
33   public static function epoch_to_gmdate($timestamp)
34   {
35     if (!is_numeric($timestamp) || is_nan($timestamp)) {
36       $timestamp = 0;
37     }
38
39     return gmdate('D, d M Y H:i:s', $timestamp) . ' GMT';
40   }
41
42   public static function str_to_gmdate($date)
43   {
44     $timestamp = strtotime($date);
45     if (FALSE === $timestamp) {
46       $timestamp = 0;
47     }
48
49     return Tweeper::epoch_to_gmdate($timestamp);
50   }
51
52   private static function get_contents($url)
53   {
54     $ch = curl_init($url);
55     curl_setopt_array($ch, array(
56       CURLOPT_HEADER => FALSE,
57       CURLOPT_FOLLOWLOCATION => TRUE,  // follow http redirects to get the real URL
58       CURLOPT_RETURNTRANSFER => TRUE,
59       CURLOPT_SSL_VERIFYHOST => FALSE,
60       CURLOPT_SSL_VERIFYPEER => FALSE,
61       CURLOPT_HTTPHEADER => array('Accept-language: en'),
62       CURLOPT_USERAGENT => Tweeper::$USER_AGENT,
63     ));
64     $contents = curl_exec($ch);
65     curl_close($ch);
66
67     return $contents;
68   }
69
70   private static function get_info($url)
71   {
72     $ch = curl_init($url);
73     curl_setopt_array($ch, array(
74       CURLOPT_HEADER => TRUE,
75       CURLOPT_NOBODY => TRUE,
76       CURLOPT_FOLLOWLOCATION => TRUE,  // follow http redirects to get the real URL
77       CURLOPT_RETURNTRANSFER => TRUE,
78       CURLOPT_SSL_VERIFYHOST => FALSE,
79       CURLOPT_SSL_VERIFYPEER => FALSE,
80       CURLOPT_USERAGENT => Tweeper::$USER_AGENT,
81     ));
82     curl_exec($ch);
83     $url_info = curl_getinfo($ch);
84     curl_close($ch);
85
86     return $url_info;
87   }
88
89   public static function generate_enclosure($url)
90   {
91     $supported_content_types = array(
92       "application/ogg",
93       "audio/aac",
94       "audio/mp4",
95       "audio/mpeg",
96       "audio/ogg",
97       "audio/vorbis",
98       "audio/wav",
99       "audio/webm",
100       "audio/x-midi",
101       "image/gif",
102       "image/jpeg",
103       "video/avi",
104       "video/mp4",
105       "video/mpeg",
106       "video/ogg",
107     );
108
109     // The RSS specification says that the enclosure element url must be http.
110     // See http://sourceforge.net/p/feedvalidator/bugs/72/
111     $http_url = preg_replace("/^https/", "http", $url);
112
113     $url_info = Tweeper::get_info($http_url);
114
115     $supported = in_array($url_info['content_type'], $supported_content_types);
116     if (!$supported) {
117       error_log("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url']);
118       return '';
119     }
120
121     $dom = new DomDocument();
122     $enc = $dom->createElement('enclosure');
123     $enc->setAttribute('url', $url_info['url']);
124     $enc->setAttribute('length', $url_info['download_content_length']);
125     $enc->setAttribute('type', $url_info['content_type']);
126
127     $dom->appendChild($enc);
128
129     return $dom->saveXML($enc);
130   }
131
132   /* Mimic the message from libxml.c::php_libxml_ctx_error_level() */
133   private function log_xml_error($error) {
134     $output = "";
135
136     switch ($error->level) {
137     case LIBXML_ERR_WARNING:
138       $output .= "Warning $error->code: ";
139       break;
140     case LIBXML_ERR_ERROR:
141       $output .= "Error $error->code: ";
142       break;
143     case LIBXML_ERR_FATAL:
144       $output .= "Fatal Error $error->code: ";
145       break;
146     }
147
148     $output .= trim($error->message);
149
150     if ($error->file) {
151       $output .= " in $error->file";
152     } else {
153       $output .= " in Entity,";
154     }
155
156     $output .=" line $error->line";
157
158     error_log($output);
159   }
160
161   private function load_stylesheet($host) {
162     $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
163     if (FALSE === file_exists($stylesheet)) {
164       trigger_error("Conversion to RSS not supported: $host", E_USER_ERROR);
165       return NULL;
166     }
167
168     $stylesheet_contents = $this->get_contents($stylesheet);
169
170     $xslDoc = new DOMDocument();
171     $xslDoc->loadXML($stylesheet_contents);
172
173     $xsltProcessor = new XSLTProcessor();
174     $xsltProcessor->registerPHPFunctions();
175     $xsltProcessor->setParameter('', 'generateEnclosure', $this->generate_enclosure);
176     $xsltProcessor->importStylesheet($xslDoc);
177
178     return $xsltProcessor;
179   }
180
181   private function json_to_xml($html, $json_match_expr, $rootName) {
182     // pre-process, convert json to XML
183     $ret = preg_match($json_match_expr, $html, $matches);
184     if ($ret !== 1) {
185       trigger_error("Cannot match expression: $json_match_expr\n", E_USER_ERROR);
186       return NULL;
187     }
188
189     $data = json_decode($matches[1]);
190     if (!$data) {
191       return NULL;
192     }
193
194     $serializer_options = array (
195       'addDecl' => TRUE,
196       'encoding' => "UTF-8",
197       'indent' => '  ',
198       'rootName' => $rootName,
199     );
200
201     $serializer = new XML_Serializer($serializer_options);
202
203     $status = $serializer->serialize($data);
204     if (PEAR::isError($status)) {
205       trigger_error($status->getMessage(), E_USER_ERROR);
206       return NULL;
207     }
208
209     return $serializer->getSerializedData();
210   }
211
212   private function get_xml_instagram_com($html) {
213     return $this->json_to_xml($html, '/window._sharedData = (.*);/', 'instagram');
214   }
215
216   private function html_to_xml($html, $host) {
217     $xmlDoc = new DOMDocument();
218
219     // Handle warnings and errors when loading invalid HTML.
220     $xml_errors_value = libxml_use_internal_errors(true);
221
222     // If there is a host-specific method to get the xml data, use it!
223     $get_xml_host_method = 'get_xml_' . str_replace(".", "_", $host);
224     if (method_exists($this, $get_xml_host_method)) {
225       $xml_data = call_user_func_array(array($this, $get_xml_host_method), array($html));
226       $xmlDoc->loadXML($xml_data);
227     } else {
228       $xmlDoc->loadHTML($html);
229     }
230
231     foreach (libxml_get_errors() as $xml_error) {
232       $this->log_xml_error($xml_error);
233     }
234     libxml_clear_errors();
235     libxml_use_internal_errors($xml_errors_value);
236
237     return $xmlDoc;
238   }
239
240   public function tweep($src_url) {
241     $url = parse_url($src_url);
242     if (FALSE === $url || empty($url["host"])) {
243       trigger_error("Invalid url: $src_url", E_USER_ERROR);
244       return NULL;
245     }
246
247     $xsltProcessor = $this->load_stylesheet($url["host"]);
248     if (NULL === $xsltProcessor) {
249       return NULL;
250     }
251
252     $html = $this->get_contents($src_url);
253     if (FALSE === $html) {
254       return NULL;
255     }
256
257     $xmlDoc = $this->html_to_xml($html, $url["host"]);
258     if (NULL === $xmlDoc) {
259       return NULL;
260     }
261
262     $output = $xsltProcessor->transformToXML($xmlDoc);
263
264     if (FALSE === $output) {
265       trigger_error('XSL transformation failed.', E_USER_ERROR);
266       return NULL;
267     }
268     return $output;
269   }
270 }
271
272 function is_cli()
273 {
274   return (substr(php_sapi_name(), 0, 3) == 'cli');
275 }
276
277 function usage($argv)
278 {
279   if (is_cli()) {
280     $usage = "{$argv[0]} [-e|-h|--help] <src_url>\n";
281   } else {
282     $usage = htmlentities("{$_SERVER['SCRIPT_NAME']}?src_url=<src_url>&generate_enclosure=<0|1>");
283   }
284
285   return "usage: $usage";
286 }
287
288 function parse_options_cli($argv, $argc)
289 {
290   $options = array(
291     'generate_enclosure' => FALSE
292   );
293
294   if ($argc < 2)
295     return $options;
296
297   $cli_options = getopt("eh", array("help"));
298   foreach ($cli_options as $opt => $val) {
299     switch ($opt) {
300     case 'e':
301       $options['generate_enclosure'] = TRUE;
302       break;
303     case 'h':
304     case 'help':
305       echo usage($argv);
306       exit(0);
307     default:
308       fwrite(STDERR, usage($argv));
309       exit(1);
310     }
311   }
312
313   $options['src_url'] = $argv[count($cli_options) + 1];
314
315   return $options;
316 }
317
318 function parse_options_query_string()
319 {
320   $options = array(
321     'generate_enclosure' => FALSE
322   );
323
324   if (isset($_GET['src_url']))
325     $options['src_url'] = $_GET['src_url'];
326
327   if (isset($_GET['generate_enclosure']))
328     $options['generate_enclosure'] = $_GET['generate_enclosure'] == 1;
329
330   return $options;
331 }
332
333
334 if (is_cli()) {
335   $options = parse_options_cli($argv, $argc);
336   $ERROR_STREAM = fopen('php://stderr', 'w');
337 } else {
338   $options = parse_options_query_string();
339   $ERROR_STREAM = fopen('php://output', 'w');
340 }
341
342 if (!isset($options['src_url'])) {
343   fwrite($ERROR_STREAM, usage($argv));
344   exit(1);
345 }
346
347 $tweeper = new Tweeper($options['generate_enclosure']);
348 echo $tweeper->tweep($options['src_url']);