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