6cdf8cfe9c9919bbe2d09d96f0e283d9111ca7f5
[tweeper.git] / tweeper.php
1 <?php
2 /*
3  * tweeper - a Twitter to RSS web scraper
4  * 
5  * Copyright (C) 2013  Antonio Ospite <ospite@studenti.unina.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 define('USER_AGENT', 'Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20130405 Firefox/22.0');
24
25 function str_to_gmdate($date)
26 {
27   $timestamp = strtotime($date);
28   return epoch_to_gmdate($timestamp);
29 }
30
31 function epoch_to_gmdate($timestamp)
32 {
33   return gmdate('D, d M Y H:i:s', $timestamp) . ' GMT';
34 }
35
36 function get_url_info($url)
37 {
38   $ch = curl_init($url);
39   curl_setopt_array($ch, array(
40       CURLOPT_HEADER => TRUE,
41       CURLOPT_NOBODY => TRUE,
42       CURLOPT_FOLLOWLOCATION => TRUE,  // follow http redirects to get the real URL
43       CURLOPT_RETURNTRANSFER => TRUE,
44       CURLOPT_SSL_VERIFYHOST => FALSE,
45       CURLOPT_SSL_VERIFYPEER => FALSE,
46       CURLOPT_USERAGENT => USER_AGENT,
47   ));
48   curl_exec($ch);
49   $url_info = curl_getinfo($ch);;
50   curl_close($ch);
51
52   return $url_info;
53 }
54
55 function generate_enclosure($url)
56 {
57   $supported_content_types = array(
58     "application/ogg",
59     "audio/aac",
60     "audio/mp4",
61     "audio/mpeg",
62     "audio/vorbis",
63     "audio/wav",
64     "audio/webm",
65     "audio/x-midi",
66     "image/gif",
67     "image/jpeg",
68     "video/avi",
69     "video/mp4",
70     "video/mpeg",
71     "video/ogg",
72   );
73
74   $url_info = get_url_info($url);
75
76   $supported = in_array($url_info['content_type'], $supported_content_types);
77   if (!$supported) {
78     error_log("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url']);
79     return '';
80   }
81
82   $dom = new DomDocument();
83   $enc = $dom->createElement('enclosure');
84   $enc->setAttribute('url', $url_info['url']);
85   $enc->setAttribute('length', $url_info['download_content_length']);
86   $enc->setAttribute('type', $url_info['content_type']);
87
88   $dom->appendChild($enc);
89
90   return $dom->saveXML($enc);
91 }
92
93
94 class Tweeper {
95
96   public function __construct($stylesheet, $generate_enclosure = FALSE) {
97     $stylesheet_contents = $this->get_contents($stylesheet);
98
99     $xslDoc = new DOMDocument();
100     $xslDoc->loadXML($stylesheet_contents);
101
102     $this->xsltProcessor = new XSLTProcessor();
103     $this->xsltProcessor->registerPHPFunctions();
104     $this->xsltProcessor->setParameter('', 'generateEnclosure', $generate_enclosure);
105     $this->xsltProcessor->importStylesheet($xslDoc);
106   }
107
108   private static function get_contents($uri) {
109     # https://www.wjsams.com/c/docs/Wiki/Php-HowToSetUserAgentOnFileGetContents
110     $opts = array(
111       'http' => array(
112         'method' => "GET",
113         'header' => join(array(
114           "Accept-language: en\r\n",
115           "User-Agent: {" + USER_AGENT + "}\r\n"
116         ))
117       )
118     );
119
120     $context = stream_context_create($opts);
121     $contents = file_get_contents($uri, false, $context);
122     return $contents;
123   }
124
125   public function tweep($uri) {
126     $html = Tweeper::get_contents($uri);
127
128     $xmlDoc = new DOMDocument();
129     $xmlDoc->loadHTML($html);
130
131     $output = $this->xsltProcessor->transformToXML($xmlDoc);
132
133     if (FALSE === $output) {
134       trigger_error('XSL transformation failed.', E_USER_ERROR);
135       return NULL;
136     }
137     return $output;
138   }
139 }
140
141 function usage($argv)
142 {
143   if (php_sapi_name() != 'cli')
144     $usage = htmlentities("{$_SERVER['SCRIPT_NAME']}?src_url=<src_url>&generate_enclosure=<0|1>");
145   else
146     $usage = "{$argv[0]} [-e|-h|--help] <src_url>\n";
147
148   return "usage: $usage";
149 }
150
151 function parse_options_cli($argv, $argc)
152 {
153   $options = array(
154     'generate_enclosure' => FALSE
155   );
156
157   if ($argc < 2)
158     return $options;
159
160   $cli_options = getopt("eh", array("help"));
161   foreach ($cli_options as $opt => $val) {
162     switch ($opt) {
163     case 'e':
164       $options['generate_enclosure'] = TRUE;
165       break;
166     case 'h':
167     case 'help':
168       echo usage($argv);
169       exit(0);
170     default:
171       die(usage($argv));
172     }
173   }
174
175   $options['src_url'] = $argv[count($cli_options) + 1];
176
177   return $options;
178 }
179
180 function parse_options_query_string()
181 {
182   $options = array(
183     'generate_enclosure' => FALSE
184   );
185
186   if (isset($_GET['src_url']))
187     $options['src_url'] = $_GET['src_url'];
188
189   if (isset($_GET['generate_enclosure']))
190     $options['generate_enclosure'] = $_GET['generate_enclosure'] == 1;
191
192   return $options;
193 }
194
195
196 if (php_sapi_name() != 'cli')
197   $options = parse_options_query_string();
198 else
199   $options = parse_options_cli($argv, $argc);
200
201 if (!isset($options['src_url']))
202   die(usage($argv));
203
204 $url = parse_url($options['src_url']);
205 if (FALSE === $url || empty($url["host"]))
206   die("Invalid url: ${options['src_url']}\n");
207
208 $stylesheet = __DIR__ . "/rss_converter_" . $url["host"] . ".xsl";
209 if (FALSE === file_exists($stylesheet))
210   die("Conversion to RSS not supported: {$url["host"]}\n");
211
212 $tweeper = new Tweeper($stylesheet, $options['generate_enclosure']);
213 echo $tweeper->tweep($options['src_url']);