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