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