src/Tweeper.php: use file_get_contents to retrieve the local stylesheet
[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 = "Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J)";
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 Twitter mobile date to the date format expected in a RSS document.
91    */
92   public static function twitterToRssDate($date) {
93     // Twitter uses relative timestamps in minutes for recent tweets.
94     if (preg_match('/^(\d+)m$/', $date, $matches)) {
95       $timestamp = strtotime("+" . $matches[1] . " min", time());
96       if (FALSE === $timestamp) {
97         $timestamp = 0;
98       }
99     }
100     else {
101       /*
102        * In case the time is specified put it after the date,
103        * to make it recognized by strptime().
104        */
105       if (preg_match('/(.*) - (.*)/', $date, $matches)) {
106         $date = $matches[2] . " " . $matches[1];
107       }
108
109       $timestamp = strtotime($date);
110       if (FALSE === $timestamp) {
111         $timestamp = 0;
112       }
113
114       /*
115        * The twitter mobile UI usually only specifies the month and the day, so
116        * strtotime($date) may interpret the date as being in the future.
117        *
118        * If the date is in the future it is probably in the same day but in the
119        * previous year.
120        */
121       if ($timestamp > time()) {
122         $timestamp = strtotime('-1 years', $timestamp);
123       }
124     }
125
126     return Tweeper::epochToRssDate($timestamp);
127   }
128
129   /**
130    * Convert string to UpperCamelCase.
131    */
132   public static function toUpperCamelCase($str, $delim = ' ') {
133     $str_upper = ucwords($str, $delim);
134     $str_camel_case = str_replace($delim, '', $str_upper);
135     return $str_camel_case;
136   }
137
138   /**
139    * Perform a cURL session multiple times when it fails with a timeout.
140    *
141    * @param resource $ch
142    *   a cURL session handle.
143    */
144   private static function curlExec($ch) {
145     $ret = FALSE;
146     $attempt = 0;
147     do {
148       $ret = curl_exec($ch);
149       if (FALSE === $ret) {
150         trigger_error(curl_error($ch), E_USER_WARNING);
151       }
152     } while (curl_errno($ch) == CURLE_OPERATION_TIMEDOUT && ++$attempt < Tweeper::$maxConnectionRetries);
153
154     return $ret;
155   }
156
157   /**
158    * Get the contents from a URL.
159    */
160   private static function getUrlContents($url) {
161     $ch = curl_init($url);
162     curl_setopt_array($ch, [
163       CURLOPT_HEADER => FALSE,
164       CURLOPT_CONNECTTIMEOUT => Tweeper::$maxConnectionTimeout,
165       // Follow http redirects to get the real URL.
166       CURLOPT_FOLLOWLOCATION => TRUE,
167       CURLOPT_COOKIEFILE => "",
168       CURLOPT_RETURNTRANSFER => TRUE,
169       CURLOPT_HTTPHEADER => ['Accept-language: en'],
170       CURLOPT_USERAGENT => Tweeper::$userAgent,
171     ]);
172     $contents = Tweeper::curlExec($ch);
173     curl_close($ch);
174
175     return $contents;
176   }
177
178   /**
179    * Get the headers from a URL.
180    */
181   private static function getUrlInfo($url) {
182     $ch = curl_init($url);
183     curl_setopt_array($ch, [
184       CURLOPT_HEADER => TRUE,
185       CURLOPT_NOBODY => TRUE,
186       CURLOPT_CONNECTTIMEOUT => Tweeper::$maxConnectionTimeout,
187       // Follow http redirects to get the real URL.
188       CURLOPT_FOLLOWLOCATION => TRUE,
189       CURLOPT_RETURNTRANSFER => TRUE,
190       CURLOPT_USERAGENT => Tweeper::$userAgent,
191     ]);
192
193     $ret = Tweeper::curlExec($ch);
194     if (FALSE === $ret) {
195       curl_close($ch);
196       return FALSE;
197     }
198
199     $url_info = curl_getinfo($ch);
200     if (FALSE === $url_info) {
201       trigger_error(curl_error($ch), E_USER_WARNING);
202     }
203     curl_close($ch);
204
205     return $url_info;
206   }
207
208   /**
209    * Generate an RSS <enclosure/> element.
210    */
211   public static function generateEnclosure($url) {
212     $supported_content_types = [
213       "application/octet-stream",
214       "application/ogg",
215       "application/pdf",
216       "audio/aac",
217       "audio/mp4",
218       "audio/mpeg",
219       "audio/ogg",
220       "audio/vorbis",
221       "audio/wav",
222       "audio/webm",
223       "audio/x-midi",
224       "image/gif",
225       "image/jpeg",
226       "image/png",
227       "video/avi",
228       "video/mp4",
229       "video/mpeg",
230       "video/ogg",
231     ];
232
233     $url_info = Tweeper::getUrlInfo($url);
234     if (FALSE === $url_info) {
235       trigger_error("Failed to retrieve info for URL: " . $url, E_USER_WARNING);
236       return '';
237     }
238
239     $supported = in_array($url_info['content_type'], $supported_content_types);
240     if (!$supported) {
241       trigger_error("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url'], E_USER_WARNING);
242       return '';
243     }
244
245     // The RSS specification says that the enclosure element URL must be http.
246     // See http://sourceforge.net/p/feedvalidator/bugs/72/
247     $http_url = preg_replace("/^https/", "http", $url_info['url']);
248
249     // When the server does not provide a Content-Length header,
250     // curl_getinfo() would return a negative value for
251     // "download_content_length", however RSS recommends to use 0 when the
252     // enclosure's size cannot be determined.
253     // See: https://www.feedvalidator.org/docs/error/UseZeroForUnknown.html
254     $length = max($url_info['download_content_length'], 0);
255
256     $dom = new DOMDocument();
257     $enc = $dom->createElement('enclosure');
258     $enc->setAttribute('url', $http_url);
259     $enc->setAttribute('length', $length);
260     $enc->setAttribute('type', $url_info['content_type']);
261
262     return $enc;
263   }
264
265   /**
266    * Mimic the message from libxml.c::php_libxml_ctx_error_level()
267    */
268   private static function logXmlError($error) {
269     $output = "";
270
271     switch ($error->level) {
272       case LIBXML_ERR_WARNING:
273         $output .= "Warning $error->code: ";
274         break;
275
276       case LIBXML_ERR_ERROR:
277         $output .= "Error $error->code: ";
278         break;
279
280       case LIBXML_ERR_FATAL:
281         $output .= "Fatal Error $error->code: ";
282         break;
283     }
284
285     $output .= trim($error->message);
286
287     if ($error->file) {
288       $output .= " in $error->file";
289     }
290     else {
291       $output .= " in Entity,";
292     }
293
294     $output .= " line $error->line";
295
296     trigger_error($output, E_USER_WARNING);
297   }
298
299   /**
300    * Convert json to XML.
301    */
302   private static function jsonToXml($json, $root_node_name) {
303     // Apparently the ObjectNormalizer used afterwards is not able to handle
304     // the stdClass object created by json_decode() with the default setting
305     // $assoc = false; so use $assoc = true.
306     $data = json_decode($json, $assoc = TRUE);
307     if (!$data) {
308       return NULL;
309     }
310
311     $encoder = new XmlEncoder();
312     $normalizer = new ObjectNormalizer();
313     $serializer = new Serializer([$normalizer], [$encoder]);
314
315     $serializer_options = [
316       'xml_encoding' => "UTF-8",
317       'xml_format_output' => TRUE,
318       'xml_root_node_name' => $root_node_name,
319     ];
320
321     $xml_data = $serializer->serialize($data, 'xml', $serializer_options);
322     if (!$xml_data) {
323       trigger_error("Cannot serialize data", E_USER_WARNING);
324       return NULL;
325     }
326
327     return $xml_data;
328   }
329
330   /**
331    * Convert the Instagram content to XML.
332    */
333   private function getXmlInstagramCom($html) {
334     // Extract the json data from the html code.
335     $json_match_expr = '/window._sharedData = (.*);/';
336     $ret = preg_match($json_match_expr, $html, $matches);
337     if ($ret !== 1) {
338       trigger_error("Cannot match expression: $json_match_expr\n", E_USER_WARNING);
339       return NULL;
340     }
341
342     $data = json_decode($matches[1], $assoc = TRUE);
343
344     // The "qe" object contains elements which will result in invalid XML
345     // element names, so remove it.
346     unset($data["qe"]);
347
348     // The "knobs" object contains elements with undefined namespaces, so
349     // remove it to silence an error message.
350     unset($data["knobs"]);
351
352     $json = json_encode($data);
353
354     return Tweeper::jsonToXml($json, 'instagram');
355   }
356
357   /**
358    * Make the Facebook HTML processable.
359    */
360   private function preprocessHtmlFacebookCom($html) {
361     $html = str_replace('<!--', '', $html);
362     $html = str_replace('-->', '', $html);
363     return $html;
364   }
365
366   /**
367    * Convert the HTML retrieved from the site to XML.
368    */
369   private function htmlToXml($html, $host) {
370     $xmlDoc = new DOMDocument();
371
372     // Handle warnings and errors when loading invalid HTML.
373     $xml_errors_value = libxml_use_internal_errors(TRUE);
374
375     // If there is a host-specific method to get the XML data, use it!
376     $get_xml_host_method = 'getXml' . Tweeper::toUpperCamelCase($host, '.');
377     if (method_exists($this, $get_xml_host_method)) {
378       $xml_data = call_user_func_array([$this, $get_xml_host_method], [$html]);
379       $xmlDoc->loadXML($xml_data);
380     }
381     else {
382       $xmlDoc->loadHTML($html);
383     }
384
385     if ($this->verbose_output) {
386       foreach (libxml_get_errors() as $xml_error) {
387         Tweeper::logXmlError($xml_error);
388       }
389     }
390     libxml_clear_errors();
391     libxml_use_internal_errors($xml_errors_value);
392
393     return $xmlDoc;
394   }
395
396   /**
397    * Load a stylesheet if the web site is supported.
398    */
399   private function loadStylesheet($host) {
400     $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
401     if (FALSE === file_exists($stylesheet)) {
402       trigger_error("Conversion to RSS not supported for $host ($stylesheet not found)", E_USER_WARNING);
403       return NULL;
404     }
405
406     $stylesheet_contents = file_get_contents($stylesheet);
407     if (FALSE === $stylesheet_contents) {
408       trigger_error("Cannot open $stylesheet", E_USER_WARNING);
409       return NULL;
410     }
411
412     $xslDoc = new DOMDocument();
413     $xslDoc->loadXML($stylesheet_contents);
414
415     $xsltProcessor = new XSLTProcessor();
416     $xsltProcessor->registerPHPFunctions();
417     $xsltProcessor->setParameter('', 'generate-enclosure', $this->generate_enclosure);
418     $xsltProcessor->setParameter('', 'show-usernames', $this->show_usernames);
419     $xsltProcessor->setParameter('', 'show-multimedia', $this->show_multimedia);
420     $xsltProcessor->importStylesheet($xslDoc);
421
422     return $xsltProcessor;
423   }
424
425   /**
426    * Convert the site content to RSS.
427    */
428   public function tweep($src_url, $host = NULL, $validate_scheme = TRUE) {
429     $url = parse_url($src_url);
430     if (FALSE === $url) {
431       trigger_error("Invalid URL: $src_url", E_USER_WARNING);
432       return NULL;
433     }
434
435     if (TRUE === $validate_scheme) {
436       $scheme = $url["scheme"];
437       if (!in_array($scheme, ["http", "https"])) {
438         trigger_error("unsupported scheme: $scheme", E_USER_WARNING);
439         return NULL;
440       }
441     }
442
443     // If the host is not given derive it from the URL.
444     if (NULL === $host) {
445       if (empty($url["host"])) {
446         trigger_error("Invalid host in URL: $src_url", E_USER_WARNING);
447         return NULL;
448       }
449       // Strip the leading www. to be more forgiving on input URLs.
450       $host = preg_replace('/^www\./', '', $url["host"]);
451     }
452
453     $xsltProcessor = $this->loadStylesheet($host);
454     if (NULL === $xsltProcessor) {
455       return NULL;
456     }
457
458     $html = Tweeper::getUrlContents($src_url);
459     if (FALSE === $html) {
460       trigger_error("Failed to retrieve $src_url", E_USER_WARNING);
461       return NULL;
462     }
463
464     $preprocess_html_host_method = 'preprocessHtml' . Tweeper::toUpperCamelCase($host, '.');
465     if (method_exists($this, $preprocess_html_host_method)) {
466       $html = call_user_func_array([$this, $preprocess_html_host_method], [$html]);
467     }
468
469     $xmlDoc = $this->htmlToXml($html, $host);
470     if (NULL === $xmlDoc) {
471       return NULL;
472     }
473
474     $output = $xsltProcessor->transformToXML($xmlDoc);
475     if (FALSE === $output) {
476       trigger_error('XSL transformation failed.', E_USER_WARNING);
477       return NULL;
478     }
479
480     return $output;
481   }
482
483 }