d084398432e37dfc5dd3bf18a71f8537c6d573bf
[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 date_default_timezone_set('UTC');
22
23 class Tweeper {
24
25   private static $USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20130405 Firefox/22.0";
26
27   public function __construct($generate_enclosure = FALSE) {
28     $this->generate_enclosure = $generate_enclosure;
29   }
30
31   public static function epoch_to_gmdate($timestamp)
32   {
33     return gmdate('D, d M Y H:i:s', $timestamp) . ' GMT';
34   }
35
36   public static function str_to_gmdate($date)
37   {
38     $timestamp = strtotime($date);
39     return Tweeper::epoch_to_gmdate($timestamp);
40   }
41
42   private static function get_contents($url)
43   {
44     $ch = curl_init($url);
45     curl_setopt_array($ch, array(
46       CURLOPT_HEADER => FALSE,
47       CURLOPT_FOLLOWLOCATION => TRUE,  // follow http redirects to get the real URL
48       CURLOPT_RETURNTRANSFER => TRUE,
49       CURLOPT_SSL_VERIFYHOST => FALSE,
50       CURLOPT_SSL_VERIFYPEER => FALSE,
51       CURLOPT_HTTPHEADER => array('Accept-language: en'),
52       CURLOPT_USERAGENT => Tweeper::$USER_AGENT,
53     ));
54     $contents = curl_exec($ch);
55     curl_close($ch);
56
57     return $contents;
58   }
59
60   private static function get_info($url)
61   {
62     $ch = curl_init($url);
63     curl_setopt_array($ch, array(
64       CURLOPT_HEADER => TRUE,
65       CURLOPT_NOBODY => TRUE,
66       CURLOPT_FOLLOWLOCATION => TRUE,  // follow http redirects to get the real URL
67       CURLOPT_RETURNTRANSFER => TRUE,
68       CURLOPT_SSL_VERIFYHOST => FALSE,
69       CURLOPT_SSL_VERIFYPEER => FALSE,
70       CURLOPT_USERAGENT => Tweeper::$USER_AGENT,
71     ));
72     curl_exec($ch);
73     $url_info = curl_getinfo($ch);
74     curl_close($ch);
75
76     return $url_info;
77   }
78
79   public static function generate_enclosure($url)
80   {
81     $supported_content_types = array(
82       "application/ogg",
83       "audio/aac",
84       "audio/mp4",
85       "audio/mpeg",
86       "audio/ogg",
87       "audio/vorbis",
88       "audio/wav",
89       "audio/webm",
90       "audio/x-midi",
91       "image/gif",
92       "image/jpeg",
93       "video/avi",
94       "video/mp4",
95       "video/mpeg",
96       "video/ogg",
97     );
98
99     // The RSS specification says that the enclosure element url must be http.
100     // See http://sourceforge.net/p/feedvalidator/bugs/72/
101     $http_url = preg_replace("/^https/", "http", $url);
102
103     $url_info = Tweeper::get_info($http_url);
104
105     $supported = in_array($url_info['content_type'], $supported_content_types);
106     if (!$supported) {
107       error_log("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url']);
108       return '';
109     }
110
111     $dom = new DomDocument();
112     $enc = $dom->createElement('enclosure');
113     $enc->setAttribute('url', $url_info['url']);
114     $enc->setAttribute('length', $url_info['download_content_length']);
115     $enc->setAttribute('type', $url_info['content_type']);
116
117     $dom->appendChild($enc);
118
119     return $dom->saveXML($enc);
120   }
121
122   /* Mimic the message from libxml.c::php_libxml_ctx_error_level() */
123   private function log_xml_error($error) {
124     $output = "";
125
126     switch ($error->level) {
127     case LIBXML_ERR_WARNING:
128       $output .= "Warning $error->code: ";
129       break;
130     case LIBXML_ERR_ERROR:
131       $output .= "Error $error->code: ";
132       break;
133     case LIBXML_ERR_FATAL:
134       $output .= "Fatal Error $error->code: ";
135       break;
136     }
137
138     $output .= trim($error->message);
139
140     if ($error->file) {
141       $output .= " in $error->file";
142     } else {
143       $output .= " in Entity,";
144     }
145
146     $output .=" line $error->line";
147
148     error_log($output);
149   }
150
151   private function load_stylesheet($host) {
152     $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
153     if (FALSE === file_exists($stylesheet)) {
154       trigger_error("Conversion to RSS not supported: $host", E_USER_ERROR);
155       return NULL;
156     }
157
158     $stylesheet_contents = $this->get_contents($stylesheet);
159
160     $xslDoc = new DOMDocument();
161     $xslDoc->loadXML($stylesheet_contents);
162
163     $xsltProcessor = new XSLTProcessor();
164     $xsltProcessor->registerPHPFunctions();
165     $xsltProcessor->setParameter('', 'generateEnclosure', $this->generate_enclosure);
166     $xsltProcessor->importStylesheet($xslDoc);
167
168     return $xsltProcessor;
169   }
170
171   private function html_to_xml($html) {
172     $xmlDoc = new DOMDocument();
173
174     // Handle warnings and errors when loading invalid HTML.
175     $xml_errors_value = libxml_use_internal_errors(true);
176     $xmlDoc->loadHTML($html);
177     foreach (libxml_get_errors() as $xml_error) {
178       $this->log_xml_error($xml_error);
179     }
180     libxml_clear_errors();
181     libxml_use_internal_errors($xml_errors_value);
182
183     return $xmlDoc;
184   }
185
186   public function tweep($src_url) {
187     $url = parse_url($src_url);
188     if (FALSE === $url || empty($url["host"])) {
189       trigger_error("Invalid url: $src_url", E_USER_ERROR);
190       return NULL;
191     }
192
193     $xsltProcessor = $this->load_stylesheet($url["host"]);
194     if (NULL === $xsltProcessor) {
195       return NULL;
196     }
197
198     $html = $this->get_contents($src_url);
199     if (FALSE === $html) {
200       return NULL;
201     }
202
203     $xmlDoc = $this->html_to_xml($html);
204     if (NULL === $xmlDoc) {
205       return NULL;
206     }
207
208     $output = $xsltProcessor->transformToXML($xmlDoc);
209
210     if (FALSE === $output) {
211       trigger_error('XSL transformation failed.', E_USER_ERROR);
212       return NULL;
213     }
214     return $output;
215   }
216 }
217
218 function usage($argv)
219 {
220   if (php_sapi_name() != 'cli')
221     $usage = htmlentities("{$_SERVER['SCRIPT_NAME']}?src_url=<src_url>&generate_enclosure=<0|1>");
222   else
223     $usage = "{$argv[0]} [-e|-h|--help] <src_url>\n";
224
225   return "usage: $usage";
226 }
227
228 function parse_options_cli($argv, $argc)
229 {
230   $options = array(
231     'generate_enclosure' => FALSE
232   );
233
234   if ($argc < 2)
235     return $options;
236
237   $cli_options = getopt("eh", array("help"));
238   foreach ($cli_options as $opt => $val) {
239     switch ($opt) {
240     case 'e':
241       $options['generate_enclosure'] = TRUE;
242       break;
243     case 'h':
244     case 'help':
245       echo usage($argv);
246       exit(0);
247     default:
248       fwrite(STDERR, usage($argv));
249       exit(1);
250     }
251   }
252
253   $options['src_url'] = $argv[count($cli_options) + 1];
254
255   return $options;
256 }
257
258 function parse_options_query_string()
259 {
260   $options = array(
261     'generate_enclosure' => FALSE
262   );
263
264   if (isset($_GET['src_url']))
265     $options['src_url'] = $_GET['src_url'];
266
267   if (isset($_GET['generate_enclosure']))
268     $options['generate_enclosure'] = $_GET['generate_enclosure'] == 1;
269
270   return $options;
271 }
272
273
274 if (php_sapi_name() != 'cli') {
275   $options = parse_options_query_string();
276   $ERROR_STREAM = fopen('php://output', 'w');
277 } else {
278   $options = parse_options_cli($argv, $argc);
279   $ERROR_STREAM = fopen('php://stderr', 'w');
280 }
281
282 if (!isset($options['src_url'])) {
283   fwrite($ERROR_STREAM, usage($argv));
284   exit(1);
285 }
286
287 $tweeper = new Tweeper($options['generate_enclosure']);
288 echo $tweeper->tweep($options['src_url']);