src/Tweeper.php: check http response code and return error for error codes
[tweeper.git] / src / Tweeper.php
1 <?php
2
3 namespace Tweeper;
4
5 /**
6  * @file
7  * Tweeper - a Twitter to RSS web scraper.
8  *
9  * Copyright (C) 2013-2020  Antonio Ospite <ao2@ao2.it>
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24
25 use DOMDocument;
26 use XSLTProcessor;
27
28 use Symfony\Component\Serializer\Serializer;
29 use Symfony\Component\Serializer\Encoder\XmlEncoder;
30 use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
31
32 date_default_timezone_set('UTC');
33
34 /**
35  * Scrape supported websites and perform conversion to RSS.
36  */
37 class Tweeper {
38
39   private static $userAgent = "APIs-Google (+https://developers.google.com/webmasters/APIs-Google.html)";
40   private static $maxConnectionTimeout = 5;
41   private static $maxConnectionRetries = 5;
42
43   /**
44    * Create a new Tweeper object controlling optional settings.
45    *
46    * @param bool $generate_enclosure
47    *   Enables the creation of <enclosure/> elements (disabled by default).
48    * @param bool $show_usernames
49    *   Enables showing the username in front of the content for multi-user
50    *   sites (enabled by default). Only some stylesheets supports this
51    *   functionality (twitter, instagram, pump.io).
52    * @param bool $show_multimedia
53    *   Enables showing multimedia content (images, videos) directly in the
54    *   item description (enabled by default). Only some stylesheets supports
55    *   this functionality (twitter, instagram, dilbert).
56    * @param bool $verbose_output
57    *   Enables showing non-fatal errors like XML parsing errors.
58    */
59   public function __construct($generate_enclosure = FALSE, $show_usernames = TRUE, $show_multimedia = TRUE, $verbose_output = TRUE) {
60     $this->generate_enclosure = $generate_enclosure;
61     $this->show_usernames = $show_usernames;
62     $this->show_multimedia = $show_multimedia;
63     $this->verbose_output = $verbose_output;
64   }
65
66   /**
67    * Convert numeric Epoch to the date format expected in a RSS document.
68    */
69   public static function epochToRssDate($timestamp) {
70     if (!is_numeric($timestamp) || is_nan($timestamp)) {
71       $timestamp = 0;
72     }
73
74     return gmdate(DATE_RSS, $timestamp);
75   }
76
77   /**
78    * Convert generic date string to the date format expected in a RSS document.
79    */
80   public static function strToRssDate($date) {
81     $timestamp = strtotime($date);
82     if (FALSE === $timestamp) {
83       $timestamp = 0;
84     }
85
86     return Tweeper::epochToRssDate($timestamp);
87   }
88
89   /**
90    * Convert string to UpperCamelCase.
91    */
92   public static function toUpperCamelCase($str, $delim = ' ') {
93     $str_upper = ucwords($str, $delim);
94     $str_camel_case = str_replace($delim, '', $str_upper);
95     return $str_camel_case;
96   }
97
98   /**
99    * Perform a cURL session multiple times when it fails with a timeout.
100    *
101    * @param resource $ch
102    *   a cURL session handle.
103    */
104   private static function curlExec($ch) {
105     $ret = FALSE;
106     $attempt = 0;
107     do {
108       $ret = curl_exec($ch);
109       if (FALSE === $ret) {
110         trigger_error(curl_error($ch), E_USER_WARNING);
111       }
112     } while (curl_errno($ch) == CURLE_OPERATION_TIMEDOUT && ++$attempt < Tweeper::$maxConnectionRetries);
113
114     $response_code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
115     if (FALSE === $response_code) {
116       trigger_error(curl_error($ch), E_USER_WARNING);
117       return FALSE;
118     }
119
120     if ($response_code >= 400) {
121       trigger_error("HTTP reponse code $response_code", E_USER_WARNING);
122       return FALSE;
123     }
124
125     return $ret;
126   }
127
128   /**
129    * Get the contents from a URL.
130    */
131   private static function getUrlContents($url, $user_agent = NULL) {
132     $ch = curl_init($url);
133     curl_setopt_array($ch, [
134       CURLOPT_HEADER => FALSE,
135       CURLOPT_CONNECTTIMEOUT => Tweeper::$maxConnectionTimeout,
136       // Follow http redirects to get the real URL.
137       CURLOPT_FOLLOWLOCATION => TRUE,
138       CURLOPT_COOKIEFILE => "",
139       CURLOPT_RETURNTRANSFER => TRUE,
140       CURLOPT_HTTPHEADER => ['Accept-language: en'],
141       CURLOPT_USERAGENT => isset($user_agent) ? $user_agent : Tweeper::$userAgent,
142     ]);
143     $contents = Tweeper::curlExec($ch);
144     curl_close($ch);
145
146     return $contents;
147   }
148
149   /**
150    * Get the headers from a URL.
151    */
152   private static function getUrlInfo($url, $user_agent = NULL) {
153     $ch = curl_init($url);
154     curl_setopt_array($ch, [
155       CURLOPT_HEADER => TRUE,
156       CURLOPT_NOBODY => TRUE,
157       CURLOPT_CONNECTTIMEOUT => Tweeper::$maxConnectionTimeout,
158       // Follow http redirects to get the real URL.
159       CURLOPT_FOLLOWLOCATION => TRUE,
160       CURLOPT_RETURNTRANSFER => TRUE,
161       CURLOPT_USERAGENT => isset($user_agent) ? $user_agent : Tweeper::$userAgent,
162     ]);
163
164     $ret = Tweeper::curlExec($ch);
165     if (FALSE === $ret) {
166       curl_close($ch);
167       return FALSE;
168     }
169
170     $url_info = curl_getinfo($ch);
171     if (FALSE === $url_info) {
172       trigger_error(curl_error($ch), E_USER_WARNING);
173     }
174     curl_close($ch);
175
176     return $url_info;
177   }
178
179   /**
180    * Generate an RSS <enclosure/> element.
181    */
182   public static function generateEnclosure($url) {
183     $supported_content_types = [
184       "application/octet-stream",
185       "application/ogg",
186       "application/pdf",
187       "audio/aac",
188       "audio/mp4",
189       "audio/mpeg",
190       "audio/ogg",
191       "audio/vorbis",
192       "audio/wav",
193       "audio/webm",
194       "audio/x-midi",
195       "image/gif",
196       "image/jpeg",
197       "image/png",
198       "video/avi",
199       "video/mp4",
200       "video/mpeg",
201       "video/ogg",
202     ];
203
204     $url_info = Tweeper::getUrlInfo($url);
205     if (FALSE === $url_info) {
206       trigger_error("Failed to retrieve info for URL: " . $url, E_USER_WARNING);
207       return '';
208     }
209
210     $supported = in_array($url_info['content_type'], $supported_content_types);
211     if (!$supported) {
212       trigger_error("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url'], E_USER_WARNING);
213       return '';
214     }
215
216     // The RSS specification says that the enclosure element URL must be http.
217     // See http://sourceforge.net/p/feedvalidator/bugs/72/
218     $http_url = preg_replace("/^https/", "http", $url_info['url']);
219
220     // When the server does not provide a Content-Length header,
221     // curl_getinfo() would return a negative value for
222     // "download_content_length", however RSS recommends to use 0 when the
223     // enclosure's size cannot be determined.
224     // See: https://www.feedvalidator.org/docs/error/UseZeroForUnknown.html
225     $length = max($url_info['download_content_length'], 0);
226
227     $dom = new DOMDocument();
228     $enc = $dom->createElement('enclosure');
229     $enc->setAttribute('url', $http_url);
230     $enc->setAttribute('length', $length);
231     $enc->setAttribute('type', $url_info['content_type']);
232
233     return $enc;
234   }
235
236   /**
237    * Mimic the message from libxml.c::php_libxml_ctx_error_level()
238    */
239   private static function logXmlError($error) {
240     $output = "";
241
242     switch ($error->level) {
243       case LIBXML_ERR_WARNING:
244         $output .= "Warning $error->code: ";
245         break;
246
247       case LIBXML_ERR_ERROR:
248         $output .= "Error $error->code: ";
249         break;
250
251       case LIBXML_ERR_FATAL:
252         $output .= "Fatal Error $error->code: ";
253         break;
254     }
255
256     $output .= trim($error->message);
257
258     if ($error->file) {
259       $output .= " in $error->file";
260     }
261     else {
262       $output .= " in Entity,";
263     }
264
265     $output .= " line $error->line";
266
267     trigger_error($output, E_USER_WARNING);
268   }
269
270   /**
271    * Convert json to XML.
272    */
273   private static function jsonToXml($json, $root_node_name) {
274     // Apparently the ObjectNormalizer used afterwards is not able to handle
275     // the stdClass object created by json_decode() with the default setting
276     // $assoc = false; so use $assoc = true.
277     $data = json_decode($json, $assoc = TRUE);
278     if (!$data) {
279       return NULL;
280     }
281
282     $encoder = new XmlEncoder();
283     $normalizer = new ObjectNormalizer();
284     $serializer = new Serializer([$normalizer], [$encoder]);
285
286     $serializer_options = [
287       'xml_encoding' => "UTF-8",
288       'xml_format_output' => TRUE,
289       'xml_root_node_name' => $root_node_name,
290     ];
291
292     $xml_data = $serializer->serialize($data, 'xml', $serializer_options);
293     if (!$xml_data) {
294       trigger_error("Cannot serialize data", E_USER_WARNING);
295       return NULL;
296     }
297
298     return $xml_data;
299   }
300
301   /**
302    * Convert the Instagram content to XML.
303    */
304   private function getXmlInstagramCom($html) {
305     // Extract the json data from the html code.
306     $json_match_expr = '/window._sharedData = (.*);/';
307     $ret = preg_match($json_match_expr, $html, $matches);
308     if ($ret !== 1) {
309       trigger_error("Cannot match expression: $json_match_expr\n", E_USER_WARNING);
310       return NULL;
311     }
312
313     $data = json_decode($matches[1], $assoc = TRUE);
314
315     // The "qe" object contains elements which will result in invalid XML
316     // element names, so remove it.
317     unset($data["qe"]);
318
319     // The "knobs" object contains elements with undefined namespaces, so
320     // remove it to silence an error message.
321     unset($data["knobs"]);
322
323     $json = json_encode($data);
324
325     return Tweeper::jsonToXml($json, 'instagram');
326   }
327
328   /**
329    * Make the Facebook HTML processable.
330    */
331   private function preprocessHtmlFacebookCom($html) {
332     $html = str_replace('<!--', '', $html);
333     $html = str_replace('-->', '', $html);
334     return $html;
335   }
336
337   /**
338    * Convert the HTML retrieved from the site to XML.
339    */
340   private function htmlToXml($html, $host) {
341     $xmlDoc = new DOMDocument();
342
343     // Handle warnings and errors when loading invalid HTML.
344     $xml_errors_value = libxml_use_internal_errors(TRUE);
345
346     // If there is a host-specific method to get the XML data, use it!
347     $get_xml_host_method = 'getXml' . Tweeper::toUpperCamelCase($host, '.');
348     if (method_exists($this, $get_xml_host_method)) {
349       $xml_data = call_user_func_array([$this, $get_xml_host_method], [$html]);
350       if (NULL === $xml_data) {
351         return NULL;
352       }
353       $xmlDoc->loadXML($xml_data);
354     }
355     else {
356       $xmlDoc->loadHTML($html);
357     }
358
359     if ($this->verbose_output) {
360       foreach (libxml_get_errors() as $xml_error) {
361         Tweeper::logXmlError($xml_error);
362       }
363     }
364     libxml_clear_errors();
365     libxml_use_internal_errors($xml_errors_value);
366
367     return $xmlDoc;
368   }
369
370   /**
371    * Load a stylesheet if the web site is supported.
372    */
373   private function loadStylesheet($host) {
374     $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
375     if (FALSE === file_exists($stylesheet)) {
376       trigger_error("Conversion to RSS not supported for $host ($stylesheet not found)", E_USER_WARNING);
377       return NULL;
378     }
379
380     $stylesheet_contents = file_get_contents($stylesheet);
381     if (FALSE === $stylesheet_contents) {
382       trigger_error("Cannot open $stylesheet", E_USER_WARNING);
383       return NULL;
384     }
385
386     $xslDoc = new DOMDocument();
387     $xslDoc->loadXML($stylesheet_contents);
388
389     $xsltProcessor = new XSLTProcessor();
390     $xsltProcessor->registerPHPFunctions();
391     $xsltProcessor->setParameter('', 'generate-enclosure', $this->generate_enclosure);
392     $xsltProcessor->setParameter('', 'show-usernames', $this->show_usernames);
393     $xsltProcessor->setParameter('', 'show-multimedia', $this->show_multimedia);
394     $xsltProcessor->importStylesheet($xslDoc);
395
396     return $xsltProcessor;
397   }
398
399   /**
400    * Convert the site content to RSS.
401    */
402   public function tweep($src_url, $host = NULL, $validate_scheme = TRUE) {
403     $url = parse_url($src_url);
404     if (FALSE === $url) {
405       trigger_error("Invalid URL: $src_url", E_USER_WARNING);
406       return NULL;
407     }
408
409     if (TRUE === $validate_scheme) {
410       $scheme = $url["scheme"];
411       if (!in_array($scheme, ["http", "https"])) {
412         trigger_error("unsupported scheme: $scheme", E_USER_WARNING);
413         return NULL;
414       }
415     }
416
417     // If the host is not given derive it from the URL.
418     if (NULL === $host) {
419       if (empty($url["host"])) {
420         trigger_error("Invalid host in URL: $src_url", E_USER_WARNING);
421         return NULL;
422       }
423       // Strip the leading www. to be more forgiving on input URLs.
424       $host = preg_replace('/^www\./', '', $url["host"]);
425     }
426
427     $xsltProcessor = $this->loadStylesheet($host);
428     if (NULL === $xsltProcessor) {
429       return NULL;
430     }
431
432     $html = Tweeper::getUrlContents($src_url);
433     if (FALSE === $html) {
434       trigger_error("Failed to retrieve $src_url", E_USER_WARNING);
435       return NULL;
436     }
437
438     $preprocess_html_host_method = 'preprocessHtml' . Tweeper::toUpperCamelCase($host, '.');
439     if (method_exists($this, $preprocess_html_host_method)) {
440       $html = call_user_func_array([$this, $preprocess_html_host_method], [$html]);
441     }
442
443     $xmlDoc = $this->htmlToXml($html, $host);
444     if (NULL === $xmlDoc) {
445       return NULL;
446     }
447
448     $output = $xsltProcessor->transformToXML($xmlDoc);
449     if (FALSE === $output) {
450       trigger_error('XSL transformation failed.', E_USER_WARNING);
451       return NULL;
452     }
453
454     return $output;
455   }
456
457 }