tweeper.php: check curl_exec() return value
[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 $userAgent = "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 epochToRssDate($timestamp) {
48     if (!is_numeric($timestamp) || is_nan($timestamp)) {
49       $timestamp = 0;
50     }
51
52     return gmdate(DATE_RSS, $timestamp);
53   }
54
55   /**
56    * Convert generic date string to the date format expected in a RSS document.
57    */
58   public static function strToRssDate($date) {
59     $timestamp = strtotime($date);
60     if (FALSE === $timestamp) {
61       $timestamp = 0;
62     }
63
64     return Tweeper::epochToRssDate($timestamp);
65   }
66
67   /**
68    * Convert string to UpperCamelCase.
69    */
70   public static function toUpperCamelCase($str, $delim = ' ') {
71     $str_upper = ucwords($str, $delim);
72     $str_camel_case = str_replace($delim, '', $str_upper);
73     return $str_camel_case;
74   }
75
76   /**
77    * Get the contents from a URL.
78    */
79   private static function getUrlContents($url) {
80     $ch = curl_init($url);
81     curl_setopt_array($ch, array(
82       CURLOPT_HEADER => FALSE,
83       // Follow http redirects to get the real URL.
84       CURLOPT_FOLLOWLOCATION => TRUE,
85       CURLOPT_RETURNTRANSFER => TRUE,
86       CURLOPT_SSL_VERIFYHOST => FALSE,
87       CURLOPT_SSL_VERIFYPEER => FALSE,
88       CURLOPT_HTTPHEADER => array('Accept-language: en'),
89       CURLOPT_USERAGENT => Tweeper::$userAgent,
90     ));
91     $contents = curl_exec($ch);
92     if (FALSE === $contents) {
93       trigger_error(curl_error($ch));
94     }
95     curl_close($ch);
96
97     return $contents;
98   }
99
100   /**
101    * Get the headers from a URL.
102    */
103   private static function getUrlInfo($url) {
104     $ch = curl_init($url);
105     curl_setopt_array($ch, array(
106       CURLOPT_HEADER => TRUE,
107       CURLOPT_NOBODY => TRUE,
108       // Follow http redirects to get the real URL.
109       CURLOPT_FOLLOWLOCATION => TRUE,
110       CURLOPT_RETURNTRANSFER => TRUE,
111       CURLOPT_SSL_VERIFYHOST => FALSE,
112       CURLOPT_SSL_VERIFYPEER => FALSE,
113       CURLOPT_USERAGENT => Tweeper::$userAgent,
114     ));
115     curl_exec($ch);
116     $url_info = curl_getinfo($ch);
117     if (FALSE === $url_info) {
118       trigger_error(curl_error($ch));
119     }
120     curl_close($ch);
121
122     return $url_info;
123   }
124
125   /**
126    * Generate an RSS <enclosure/> element.
127    */
128   public static function generateEnclosure($url) {
129     $supported_content_types = array(
130       "application/octet-stream",
131       "application/ogg",
132       "application/pdf",
133       "audio/aac",
134       "audio/mp4",
135       "audio/mpeg",
136       "audio/ogg",
137       "audio/vorbis",
138       "audio/wav",
139       "audio/webm",
140       "audio/x-midi",
141       "image/gif",
142       "image/jpeg",
143       "image/png",
144       "video/avi",
145       "video/mp4",
146       "video/mpeg",
147       "video/ogg",
148     );
149
150     $url_info = Tweeper::getUrlInfo($url);
151
152     $supported = in_array($url_info['content_type'], $supported_content_types);
153     if (!$supported) {
154       error_log("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url']);
155       return '';
156     }
157
158     // The RSS specification says that the enclosure element URL must be http.
159     // See http://sourceforge.net/p/feedvalidator/bugs/72/
160     $http_url = preg_replace("/^https/", "http", $url_info['url']);
161
162     $dom = new DOMDocument();
163     $enc = $dom->createElement('enclosure');
164     $enc->setAttribute('url', $http_url);
165     $enc->setAttribute('length', $url_info['download_content_length']);
166     $enc->setAttribute('type', $url_info['content_type']);
167
168     return $enc;
169   }
170
171   /**
172    * Mimic the message from libxml.c::php_libxml_ctx_error_level()
173    */
174   private static function logXmlError($error) {
175     $output = "";
176
177     switch ($error->level) {
178       case LIBXML_ERR_WARNING:
179         $output .= "Warning $error->code: ";
180         break;
181
182       case LIBXML_ERR_ERROR:
183         $output .= "Error $error->code: ";
184         break;
185
186       case LIBXML_ERR_FATAL:
187         $output .= "Fatal Error $error->code: ";
188         break;
189     }
190
191     $output .= trim($error->message);
192
193     if ($error->file) {
194       $output .= " in $error->file";
195     }
196     else {
197       $output .= " in Entity,";
198     }
199
200     $output .= " line $error->line";
201
202     error_log($output);
203   }
204
205   /**
206    * Convert json to XML.
207    */
208   private static function jsonToXml($json, $root_node_name) {
209     // Apparently the ObjectNormalizer used afterwards is not able to handle
210     // the stdClass object created by json_decode() with the default setting
211     // $assoc = false; so use $assoc = true.
212     $data = json_decode($json, $assoc = TRUE);
213     if (!$data) {
214       return NULL;
215     }
216
217     $encoder = new XmlEncoder();
218     $normalizer = new ObjectNormalizer();
219     $serializer = new Serializer(array($normalizer), array($encoder));
220
221     $serializer_options = array(
222       'xml_encoding' => "UTF-8",
223       'xml_format_output' => TRUE,
224       'xml_root_node_name' => $root_node_name,
225     );
226
227     $xml_data = $serializer->serialize($data, 'xml', $serializer_options);
228     if (!$xml_data) {
229       trigger_error("Cannot serialize data", E_USER_ERROR);
230       return NULL;
231     }
232
233     return $xml_data;
234   }
235
236   /**
237    * Convert the Instagram content to XML.
238    */
239   private function getXmlInstagramCom($html) {
240     // Extract the json data from the html code.
241     $json_match_expr = '/window._sharedData = (.*);/';
242     $ret = preg_match($json_match_expr, $html, $matches);
243     if ($ret !== 1) {
244       trigger_error("Cannot match expression: $json_match_expr\n", E_USER_ERROR);
245       return NULL;
246     }
247
248     return Tweeper::jsonToXml($matches[1], 'instagram');
249   }
250
251   /**
252    * Make the Facebook HTML processable.
253    */
254   private function preprocessHtmlFacebookCom($html) {
255     $html = str_replace('<!--', '', $html);
256     $html = str_replace('-->', '', $html);
257     return $html;
258   }
259
260   /**
261    * Convert the HTML retrieved from the site to XML.
262    */
263   private function htmlToXml($html, $host) {
264     $xmlDoc = new DOMDocument();
265
266     // Handle warnings and errors when loading invalid HTML.
267     $xml_errors_value = libxml_use_internal_errors(TRUE);
268
269     // If there is a host-specific method to get the XML data, use it!
270     $get_xml_host_method = 'getXml' . Tweeper::toUpperCamelCase($host, '.');
271     if (method_exists($this, $get_xml_host_method)) {
272       $xml_data = call_user_func_array(array($this, $get_xml_host_method), array($html));
273       $xmlDoc->loadXML($xml_data);
274     }
275     else {
276       $xmlDoc->loadHTML($html);
277     }
278
279     foreach (libxml_get_errors() as $xml_error) {
280       Tweeper::logXmlError($xml_error);
281     }
282     libxml_clear_errors();
283     libxml_use_internal_errors($xml_errors_value);
284
285     return $xmlDoc;
286   }
287
288   /**
289    * Load a stylesheet if the web site is supported.
290    */
291   private function loadStylesheet($host) {
292     $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
293     if (FALSE === file_exists($stylesheet)) {
294       trigger_error("Conversion to RSS not supported for $host ($stylesheet not found)", E_USER_ERROR);
295       return NULL;
296     }
297
298     $stylesheet_contents = Tweeper::getUrlContents($stylesheet);
299
300     $xslDoc = new DOMDocument();
301     $xslDoc->loadXML($stylesheet_contents);
302
303     $xsltProcessor = new XSLTProcessor();
304     $xsltProcessor->registerPHPFunctions();
305     $xsltProcessor->setParameter('', 'generate-enclosure', $this->generate_enclosure);
306     $xsltProcessor->importStylesheet($xslDoc);
307
308     return $xsltProcessor;
309   }
310
311   /**
312    * Convert the site content to RSS.
313    */
314   public function tweep($src_url) {
315     $url = parse_url($src_url);
316     if (FALSE === $url || empty($url["host"])) {
317       trigger_error("Invalid URL: $src_url", E_USER_ERROR);
318       return NULL;
319     }
320
321     // Strip the leading www. to be more forgiving on input URLs.
322     $host = preg_replace('/^www\./', '', $url["host"]);
323
324     $xsltProcessor = $this->loadStylesheet($host);
325     if (NULL === $xsltProcessor) {
326       return NULL;
327     }
328
329     $html = Tweeper::getUrlContents($src_url);
330     if (FALSE === $html) {
331       return NULL;
332     }
333
334     $preprocess_html_host_method = 'preprocessHtml' . Tweeper::toUpperCamelCase($host, '.');
335     if (method_exists($this, $preprocess_html_host_method)) {
336       $html = call_user_func_array(array($this, $preprocess_html_host_method), array($html));
337     }
338
339     $xmlDoc = $this->htmlToXml($html, $host);
340     if (NULL === $xmlDoc) {
341       return NULL;
342     }
343
344     $output = $xsltProcessor->transformToXML($xmlDoc);
345
346     if (FALSE === $output) {
347       trigger_error('XSL transformation failed.', E_USER_ERROR);
348       return NULL;
349     }
350     return $output;
351   }
352
353 }
354
355 /**
356  * Check if the script is being run from the command line.
357  */
358 function is_cli() {
359   return (php_sapi_name() === "cli");
360 }
361
362 /**
363  * Show the script usage.
364  */
365 function usage($argv) {
366   if (is_cli()) {
367     $usage = "{$argv[0]} [-e|-h|--help] <src_url>\n";
368   }
369   else {
370     $usage = htmlentities("{$_SERVER['SCRIPT_NAME']}?src_url=<src_url>&generate_enclosure=<0|1>");
371   }
372
373   return "usage: $usage";
374 }
375
376 /**
377  * Parse command line options.
378  */
379 function parse_options_cli($argv, $argc) {
380   $options = array(
381     'generate_enclosure' => FALSE,
382   );
383
384   if ($argc < 2) {
385     return $options;
386   }
387
388   $cli_options = getopt("eh", array("help"));
389   foreach ($cli_options as $opt => $val) {
390     switch ($opt) {
391       case 'e':
392         $options['generate_enclosure'] = TRUE;
393         break;
394
395       case 'h':
396       case 'help':
397         echo usage($argv);
398         exit(0);
399
400       default:
401         fwrite(STDERR, usage($argv));
402         exit(1);
403     }
404   }
405
406   $options['src_url'] = $argv[count($cli_options) + 1];
407
408   return $options;
409 }
410
411 /**
412  * Parse options passed from a query string.
413  */
414 function parse_options_query_string() {
415   $options = array(
416     'generate_enclosure' => FALSE,
417   );
418
419   if (isset($_GET['src_url'])) {
420     $options['src_url'] = $_GET['src_url'];
421   }
422
423   if (isset($_GET['generate_enclosure'])) {
424     $options['generate_enclosure'] = $_GET['generate_enclosure'] == 1;
425   }
426
427   return $options;
428 }
429
430 if (is_cli()) {
431   $options = parse_options_cli($argv, $argc);
432   $error_stream = fopen('php://stderr', 'w');
433 }
434 else {
435   $options = parse_options_query_string();
436   $error_stream = fopen('php://output', 'w');
437 }
438
439 if (!isset($options['src_url'])) {
440   fwrite($error_stream, usage(is_cli() ? $argv : NULL));
441   exit(1);
442 }
443
444 $tweeper = new Tweeper($options['generate_enclosure']);
445 echo $tweeper->tweep($options['src_url']);