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