rss_converter_dilbert.com.xsl: put the full text in the alt attribute
[tweeper.git] / tweeper.php
1 <?php
2 /*
3  * tweeper - a Twitter to RSS web scraper
4  *
5  * Copyright (C) 2013-2015  Antonio Ospite <ao2@ao2.it>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 require_once 'Symfony/Component/Serializer/autoload.php';
22
23 use Symfony\Component\Serializer\Serializer;
24 use Symfony\Component\Serializer\Encoder\XmlEncoder;
25 use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
26
27 date_default_timezone_set('UTC');
28
29 class Tweeper {
30
31   private static $USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20130405 Firefox/22.0";
32
33   public function __construct($generate_enclosure = FALSE) {
34     $this->generate_enclosure = $generate_enclosure;
35   }
36
37   public static function epoch_to_gmdate($timestamp)
38   {
39     if (!is_numeric($timestamp) || is_nan($timestamp)) {
40       $timestamp = 0;
41     }
42
43     return gmdate('D, d M Y H:i:s', $timestamp) . ' GMT';
44   }
45
46   public static function str_to_gmdate($date)
47   {
48     $timestamp = strtotime($date);
49     if (FALSE === $timestamp) {
50       $timestamp = 0;
51     }
52
53     return Tweeper::epoch_to_gmdate($timestamp);
54   }
55
56   private static function get_contents($url)
57   {
58     $ch = curl_init($url);
59     curl_setopt_array($ch, array(
60       CURLOPT_HEADER => FALSE,
61       CURLOPT_FOLLOWLOCATION => TRUE,  // follow http redirects to get the real URL
62       CURLOPT_RETURNTRANSFER => TRUE,
63       CURLOPT_SSL_VERIFYHOST => FALSE,
64       CURLOPT_SSL_VERIFYPEER => FALSE,
65       CURLOPT_HTTPHEADER => array('Accept-language: en'),
66       CURLOPT_USERAGENT => Tweeper::$USER_AGENT,
67     ));
68     $contents = curl_exec($ch);
69     curl_close($ch);
70
71     return $contents;
72   }
73
74   private static function get_info($url)
75   {
76     $ch = curl_init($url);
77     curl_setopt_array($ch, array(
78       CURLOPT_HEADER => TRUE,
79       CURLOPT_NOBODY => TRUE,
80       CURLOPT_FOLLOWLOCATION => TRUE,  // follow http redirects to get the real URL
81       CURLOPT_RETURNTRANSFER => TRUE,
82       CURLOPT_SSL_VERIFYHOST => FALSE,
83       CURLOPT_SSL_VERIFYPEER => FALSE,
84       CURLOPT_USERAGENT => Tweeper::$USER_AGENT,
85     ));
86     curl_exec($ch);
87     $url_info = curl_getinfo($ch);
88     curl_close($ch);
89
90     return $url_info;
91   }
92
93   public static function generate_enclosure($url)
94   {
95     $supported_content_types = array(
96       "application/ogg",
97       "audio/aac",
98       "audio/mp4",
99       "audio/mpeg",
100       "audio/ogg",
101       "audio/vorbis",
102       "audio/wav",
103       "audio/webm",
104       "audio/x-midi",
105       "image/gif",
106       "image/jpeg",
107       "video/avi",
108       "video/mp4",
109       "video/mpeg",
110       "video/ogg",
111     );
112
113     // The RSS specification says that the enclosure element url must be http.
114     // See http://sourceforge.net/p/feedvalidator/bugs/72/
115     $http_url = preg_replace("/^https/", "http", $url);
116
117     $url_info = Tweeper::get_info($http_url);
118
119     $supported = in_array($url_info['content_type'], $supported_content_types);
120     if (!$supported) {
121       error_log("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url']);
122       return '';
123     }
124
125     $dom = new DomDocument();
126     $enc = $dom->createElement('enclosure');
127     $enc->setAttribute('url', $url_info['url']);
128     $enc->setAttribute('length', $url_info['download_content_length']);
129     $enc->setAttribute('type', $url_info['content_type']);
130
131     $dom->appendChild($enc);
132
133     return $dom->saveXML($enc);
134   }
135
136   /* Mimic the message from libxml.c::php_libxml_ctx_error_level() */
137   private function log_xml_error($error) {
138     $output = "";
139
140     switch ($error->level) {
141     case LIBXML_ERR_WARNING:
142       $output .= "Warning $error->code: ";
143       break;
144     case LIBXML_ERR_ERROR:
145       $output .= "Error $error->code: ";
146       break;
147     case LIBXML_ERR_FATAL:
148       $output .= "Fatal Error $error->code: ";
149       break;
150     }
151
152     $output .= trim($error->message);
153
154     if ($error->file) {
155       $output .= " in $error->file";
156     } else {
157       $output .= " in Entity,";
158     }
159
160     $output .=" line $error->line";
161
162     error_log($output);
163   }
164
165   private function load_stylesheet($host) {
166     $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
167     if (FALSE === file_exists($stylesheet)) {
168       trigger_error("Conversion to RSS not supported for $host ($stylesheet not found)", E_USER_ERROR);
169       return NULL;
170     }
171
172     $stylesheet_contents = $this->get_contents($stylesheet);
173
174     $xslDoc = new DOMDocument();
175     $xslDoc->loadXML($stylesheet_contents);
176
177     $xsltProcessor = new XSLTProcessor();
178     $xsltProcessor->registerPHPFunctions();
179     $xsltProcessor->setParameter('', 'generateEnclosure', $this->generate_enclosure);
180     $xsltProcessor->importStylesheet($xslDoc);
181
182     return $xsltProcessor;
183   }
184
185   private function json_to_xml($html, $json_match_expr, $rootName) {
186     // pre-process, convert json to XML
187     $ret = preg_match($json_match_expr, $html, $matches);
188     if ($ret !== 1) {
189       trigger_error("Cannot match expression: $json_match_expr\n", E_USER_ERROR);
190       return NULL;
191     }
192
193     // Apparenty the ObjectNormalizer used afterwards is not able to handle
194     // the stdClass object created by json_decode() with the default setting
195     // $assoc = false; so use $assoc = true 
196     $data = json_decode($matches[1], $assoc = true);
197     if (!$data) {
198       return NULL;
199     }
200
201     $encoder = new XmlEncoder();
202     $normalizer = new ObjectNormalizer();
203     $serializer = new Serializer(array($normalizer), array($encoder));
204
205     $serializer_options = array (
206       'xml_encoding' => "UTF-8",
207       'xml_format_output' => TRUE,
208       'xml_root_node_name' => $rootName,
209     );
210
211     $xml_data = $serializer->serialize($data, 'xml', $serializer_options);
212     if (!$xml_data) {
213       trigger_error("Cannot serialize data", E_USER_ERROR);
214       return NULL;
215     }
216
217     return $xml_data;
218   }
219
220   private function get_xml_instagram_com($html) {
221     return $this->json_to_xml($html, '/window._sharedData = (.*);/', 'instagram');
222   }
223
224   private function preprocess_html_facebook_com($html) {
225     $html = str_replace('<!--', '', $html);
226     $html = str_replace('-->', '', $html);
227     return $html;
228   }
229
230   private function html_to_xml($html, $host) {
231     $xmlDoc = new DOMDocument();
232
233     // Handle warnings and errors when loading invalid HTML.
234     $xml_errors_value = libxml_use_internal_errors(true);
235
236     // If there is a host-specific method to get the xml data, use it!
237     $get_xml_host_method = 'get_xml_' . str_replace(".", "_", $host);
238     if (method_exists($this, $get_xml_host_method)) {
239       $xml_data = call_user_func_array(array($this, $get_xml_host_method), array($html));
240       $xmlDoc->loadXML($xml_data);
241     } else {
242       $xmlDoc->loadHTML($html);
243     }
244
245     foreach (libxml_get_errors() as $xml_error) {
246       $this->log_xml_error($xml_error);
247     }
248     libxml_clear_errors();
249     libxml_use_internal_errors($xml_errors_value);
250
251     return $xmlDoc;
252   }
253
254   public function tweep($src_url) {
255     $url = parse_url($src_url);
256     if (FALSE === $url || empty($url["host"])) {
257       trigger_error("Invalid url: $src_url", E_USER_ERROR);
258       return NULL;
259     }
260
261     // Strip the leading www. to be more forgiving on input URLs
262     $host = preg_replace('/^www\./', '', $url["host"]);
263
264     $xsltProcessor = $this->load_stylesheet($host);
265     if (NULL === $xsltProcessor) {
266       return NULL;
267     }
268
269     $html = $this->get_contents($src_url);
270     if (FALSE === $html) {
271       return NULL;
272     }
273
274     $preprocess_html_host_method = 'preprocess_html_' . str_replace(".", "_", $host);
275     if (method_exists($this, $preprocess_html_host_method)) {
276       $html = call_user_func_array(array($this, $preprocess_html_host_method), array($html));
277     }
278
279     $xmlDoc = $this->html_to_xml($html, $host);
280     if (NULL === $xmlDoc) {
281       return NULL;
282     }
283
284     $output = $xsltProcessor->transformToXML($xmlDoc);
285
286     if (FALSE === $output) {
287       trigger_error('XSL transformation failed.', E_USER_ERROR);
288       return NULL;
289     }
290     return $output;
291   }
292 }
293
294 function is_cli()
295 {
296   return (php_sapi_name() === "cli");
297 }
298
299 function usage($argv)
300 {
301   if (is_cli()) {
302     $usage = "{$argv[0]} [-e|-h|--help] <src_url>\n";
303   } else {
304     $usage = htmlentities("{$_SERVER['SCRIPT_NAME']}?src_url=<src_url>&generate_enclosure=<0|1>");
305   }
306
307   return "usage: $usage";
308 }
309
310 function parse_options_cli($argv, $argc)
311 {
312   $options = array(
313     'generate_enclosure' => FALSE
314   );
315
316   if ($argc < 2)
317     return $options;
318
319   $cli_options = getopt("eh", array("help"));
320   foreach ($cli_options as $opt => $val) {
321     switch ($opt) {
322     case 'e':
323       $options['generate_enclosure'] = TRUE;
324       break;
325     case 'h':
326     case 'help':
327       echo usage($argv);
328       exit(0);
329     default:
330       fwrite(STDERR, usage($argv));
331       exit(1);
332     }
333   }
334
335   $options['src_url'] = $argv[count($cli_options) + 1];
336
337   return $options;
338 }
339
340 function parse_options_query_string()
341 {
342   $options = array(
343     'generate_enclosure' => FALSE
344   );
345
346   if (isset($_GET['src_url']))
347     $options['src_url'] = $_GET['src_url'];
348
349   if (isset($_GET['generate_enclosure']))
350     $options['generate_enclosure'] = $_GET['generate_enclosure'] == 1;
351
352   return $options;
353 }
354
355
356 if (is_cli()) {
357   $options = parse_options_cli($argv, $argc);
358   $ERROR_STREAM = fopen('php://stderr', 'w');
359 } else {
360   $options = parse_options_query_string();
361   $ERROR_STREAM = fopen('php://output', 'w');
362 }
363
364 if (!isset($options['src_url'])) {
365   fwrite($ERROR_STREAM, usage(is_cli() ? $argv : NULL));
366   exit(1);
367 }
368
369 $tweeper = new Tweeper($options['generate_enclosure']);
370 echo $tweeper->tweep($options['src_url']);