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