3 * tweeper - a Twitter to RSS web scraper
5 * Copyright (C) 2013-2015 Antonio Ospite <ao2@ao2.it>
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.
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.
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/>.
21 require_once 'XML/Serializer.php';
23 date_default_timezone_set('UTC');
27 private static $USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20130405 Firefox/22.0";
29 public function __construct($generate_enclosure = FALSE) {
30 $this->generate_enclosure = $generate_enclosure;
33 public static function epoch_to_gmdate($timestamp)
35 if (!is_numeric($timestamp) || is_nan($timestamp)) {
39 return gmdate('D, d M Y H:i:s', $timestamp) . ' GMT';
42 public static function str_to_gmdate($date)
44 $timestamp = strtotime($date);
45 if (FALSE === $timestamp) {
49 return Tweeper::epoch_to_gmdate($timestamp);
52 private static function get_contents($url)
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,
64 $contents = curl_exec($ch);
70 private static function get_info($url)
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,
83 $url_info = curl_getinfo($ch);
89 public static function generate_enclosure($url)
91 $supported_content_types = array(
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);
113 $url_info = Tweeper::get_info($http_url);
115 $supported = in_array($url_info['content_type'], $supported_content_types);
117 error_log("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url']);
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']);
127 $dom->appendChild($enc);
129 return $dom->saveXML($enc);
132 /* Mimic the message from libxml.c::php_libxml_ctx_error_level() */
133 private function log_xml_error($error) {
136 switch ($error->level) {
137 case LIBXML_ERR_WARNING:
138 $output .= "Warning $error->code: ";
140 case LIBXML_ERR_ERROR:
141 $output .= "Error $error->code: ";
143 case LIBXML_ERR_FATAL:
144 $output .= "Fatal Error $error->code: ";
148 $output .= trim($error->message);
151 $output .= " in $error->file";
153 $output .= " in Entity,";
156 $output .=" line $error->line";
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);
168 $stylesheet_contents = $this->get_contents($stylesheet);
170 $xslDoc = new DOMDocument();
171 $xslDoc->loadXML($stylesheet_contents);
173 $xsltProcessor = new XSLTProcessor();
174 $xsltProcessor->registerPHPFunctions();
175 $xsltProcessor->setParameter('', 'generateEnclosure', $this->generate_enclosure);
176 $xsltProcessor->importStylesheet($xslDoc);
178 return $xsltProcessor;
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);
185 trigger_error("Cannot match expression: $json_match_expr\n", E_USER_ERROR);
189 $data = json_decode($matches[1]);
194 $serializer_options = array (
196 'encoding' => "UTF-8",
198 'rootName' => $rootName,
201 $serializer = new XML_Serializer($serializer_options);
203 $status = $serializer->serialize($data);
204 if (PEAR::isError($status)) {
205 trigger_error($status->getMessage(), E_USER_ERROR);
209 return $serializer->getSerializedData();
212 private function get_xml_instagram_com($html) {
213 return $this->json_to_xml($html, '/window._sharedData = (.*);/', 'instagram');
216 private function html_to_xml($html, $host) {
217 $xmlDoc = new DOMDocument();
219 // Handle warnings and errors when loading invalid HTML.
220 $xml_errors_value = libxml_use_internal_errors(true);
222 // If there is a host-specific method to get the xml data, use it!
223 $get_xml_host_method = 'get_xml_' . str_replace(".", "_", $host);
224 if (method_exists($this, $get_xml_host_method)) {
225 $xml_data = call_user_func_array(array($this, $get_xml_host_method), array($html));
226 $xmlDoc->loadXML($xml_data);
228 $xmlDoc->loadHTML($html);
231 foreach (libxml_get_errors() as $xml_error) {
232 $this->log_xml_error($xml_error);
234 libxml_clear_errors();
235 libxml_use_internal_errors($xml_errors_value);
240 public function tweep($src_url) {
241 $url = parse_url($src_url);
242 if (FALSE === $url || empty($url["host"])) {
243 trigger_error("Invalid url: $src_url", E_USER_ERROR);
247 // Strip the leading www. to be more forgiving on input URLs
248 $host = preg_replace('/^www\./', '', $url["host"]);
250 $xsltProcessor = $this->load_stylesheet($host);
251 if (NULL === $xsltProcessor) {
255 $html = $this->get_contents($src_url);
256 if (FALSE === $html) {
260 $preprocess_html_host_method = 'preprocess_html_' . str_replace(".", "_", $host);
261 if (method_exists($this, $preprocess_html_host_method)) {
262 $html = call_user_func_array(array($this, $preprocess_html_host_method), array($html));
265 $xmlDoc = $this->html_to_xml($html, $host);
266 if (NULL === $xmlDoc) {
270 $output = $xsltProcessor->transformToXML($xmlDoc);
272 if (FALSE === $output) {
273 trigger_error('XSL transformation failed.', E_USER_ERROR);
282 return (substr(php_sapi_name(), 0, 3) == 'cli');
285 function usage($argv)
288 $usage = "{$argv[0]} [-e|-h|--help] <src_url>\n";
290 $usage = htmlentities("{$_SERVER['SCRIPT_NAME']}?src_url=<src_url>&generate_enclosure=<0|1>");
293 return "usage: $usage";
296 function parse_options_cli($argv, $argc)
299 'generate_enclosure' => FALSE
305 $cli_options = getopt("eh", array("help"));
306 foreach ($cli_options as $opt => $val) {
309 $options['generate_enclosure'] = TRUE;
316 fwrite(STDERR, usage($argv));
321 $options['src_url'] = $argv[count($cli_options) + 1];
326 function parse_options_query_string()
329 'generate_enclosure' => FALSE
332 if (isset($_GET['src_url']))
333 $options['src_url'] = $_GET['src_url'];
335 if (isset($_GET['generate_enclosure']))
336 $options['generate_enclosure'] = $_GET['generate_enclosure'] == 1;
343 $options = parse_options_cli($argv, $argc);
344 $ERROR_STREAM = fopen('php://stderr', 'w');
346 $options = parse_options_query_string();
347 $ERROR_STREAM = fopen('php://output', 'w');
350 if (!isset($options['src_url'])) {
351 fwrite($ERROR_STREAM, usage($argv));
355 $tweeper = new Tweeper($options['generate_enclosure']);
356 echo $tweeper->tweep($options['src_url']);