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 preprocess_html_facebook_com($html) {
217 $html = str_replace('<!--', '', $html);
218 $html = str_replace('-->', '', $html);
222 private function html_to_xml($html, $host) {
223 $xmlDoc = new DOMDocument();
225 // Handle warnings and errors when loading invalid HTML.
226 $xml_errors_value = libxml_use_internal_errors(true);
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);
234 $xmlDoc->loadHTML($html);
237 foreach (libxml_get_errors() as $xml_error) {
238 $this->log_xml_error($xml_error);
240 libxml_clear_errors();
241 libxml_use_internal_errors($xml_errors_value);
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);
253 // Strip the leading www. to be more forgiving on input URLs
254 $host = preg_replace('/^www\./', '', $url["host"]);
256 $xsltProcessor = $this->load_stylesheet($host);
257 if (NULL === $xsltProcessor) {
261 $html = $this->get_contents($src_url);
262 if (FALSE === $html) {
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));
271 $xmlDoc = $this->html_to_xml($html, $host);
272 if (NULL === $xmlDoc) {
276 $output = $xsltProcessor->transformToXML($xmlDoc);
278 if (FALSE === $output) {
279 trigger_error('XSL transformation failed.', E_USER_ERROR);
288 return (php_sapi_name() === "cli");
291 function usage($argv)
294 $usage = "{$argv[0]} [-e|-h|--help] <src_url>\n";
296 $usage = htmlentities("{$_SERVER['SCRIPT_NAME']}?src_url=<src_url>&generate_enclosure=<0|1>");
299 return "usage: $usage";
302 function parse_options_cli($argv, $argc)
305 'generate_enclosure' => FALSE
311 $cli_options = getopt("eh", array("help"));
312 foreach ($cli_options as $opt => $val) {
315 $options['generate_enclosure'] = TRUE;
322 fwrite(STDERR, usage($argv));
327 $options['src_url'] = $argv[count($cli_options) + 1];
332 function parse_options_query_string()
335 'generate_enclosure' => FALSE
338 if (isset($_GET['src_url']))
339 $options['src_url'] = $_GET['src_url'];
341 if (isset($_GET['generate_enclosure']))
342 $options['generate_enclosure'] = $_GET['generate_enclosure'] == 1;
349 $options = parse_options_cli($argv, $argc);
350 $ERROR_STREAM = fopen('php://stderr', 'w');
352 $options = parse_options_query_string();
353 $ERROR_STREAM = fopen('php://output', 'w');
356 if (!isset($options['src_url'])) {
357 fwrite($ERROR_STREAM, usage(is_cli() ? $argv : NULL));
361 $tweeper = new Tweeper($options['generate_enclosure']);
362 echo $tweeper->tweep($options['src_url']);