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 return gmdate('D, d M Y H:i:s', $timestamp) . ' GMT';
38 public static function str_to_gmdate($date)
40 $timestamp = strtotime($date);
41 return Tweeper::epoch_to_gmdate($timestamp);
44 private static function get_contents($url)
46 $ch = curl_init($url);
47 curl_setopt_array($ch, array(
48 CURLOPT_HEADER => FALSE,
49 CURLOPT_FOLLOWLOCATION => TRUE, // follow http redirects to get the real URL
50 CURLOPT_RETURNTRANSFER => TRUE,
51 CURLOPT_SSL_VERIFYHOST => FALSE,
52 CURLOPT_SSL_VERIFYPEER => FALSE,
53 CURLOPT_HTTPHEADER => array('Accept-language: en'),
54 CURLOPT_USERAGENT => Tweeper::$USER_AGENT,
56 $contents = curl_exec($ch);
62 private static function get_info($url)
64 $ch = curl_init($url);
65 curl_setopt_array($ch, array(
66 CURLOPT_HEADER => TRUE,
67 CURLOPT_NOBODY => TRUE,
68 CURLOPT_FOLLOWLOCATION => TRUE, // follow http redirects to get the real URL
69 CURLOPT_RETURNTRANSFER => TRUE,
70 CURLOPT_SSL_VERIFYHOST => FALSE,
71 CURLOPT_SSL_VERIFYPEER => FALSE,
72 CURLOPT_USERAGENT => Tweeper::$USER_AGENT,
75 $url_info = curl_getinfo($ch);
81 public static function generate_enclosure($url)
83 $supported_content_types = array(
101 // The RSS specification says that the enclosure element url must be http.
102 // See http://sourceforge.net/p/feedvalidator/bugs/72/
103 $http_url = preg_replace("/^https/", "http", $url);
105 $url_info = Tweeper::get_info($http_url);
107 $supported = in_array($url_info['content_type'], $supported_content_types);
109 error_log("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url']);
113 $dom = new DomDocument();
114 $enc = $dom->createElement('enclosure');
115 $enc->setAttribute('url', $url_info['url']);
116 $enc->setAttribute('length', $url_info['download_content_length']);
117 $enc->setAttribute('type', $url_info['content_type']);
119 $dom->appendChild($enc);
121 return $dom->saveXML($enc);
124 /* Mimic the message from libxml.c::php_libxml_ctx_error_level() */
125 private function log_xml_error($error) {
128 switch ($error->level) {
129 case LIBXML_ERR_WARNING:
130 $output .= "Warning $error->code: ";
132 case LIBXML_ERR_ERROR:
133 $output .= "Error $error->code: ";
135 case LIBXML_ERR_FATAL:
136 $output .= "Fatal Error $error->code: ";
140 $output .= trim($error->message);
143 $output .= " in $error->file";
145 $output .= " in Entity,";
148 $output .=" line $error->line";
153 private function load_stylesheet($host) {
154 $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
155 if (FALSE === file_exists($stylesheet)) {
156 trigger_error("Conversion to RSS not supported: $host", E_USER_ERROR);
160 $stylesheet_contents = $this->get_contents($stylesheet);
162 $xslDoc = new DOMDocument();
163 $xslDoc->loadXML($stylesheet_contents);
165 $xsltProcessor = new XSLTProcessor();
166 $xsltProcessor->registerPHPFunctions();
167 $xsltProcessor->setParameter('', 'generateEnclosure', $this->generate_enclosure);
168 $xsltProcessor->importStylesheet($xslDoc);
170 return $xsltProcessor;
173 private function json_to_xml($html, $json_match_expr, $rootName) {
174 // pre-process, convert json to XML
175 $ret = preg_match($json_match_expr, $html, $matches);
177 trigger_error("Cannot match expression: $json_match_expr\n", E_USER_ERROR);
181 $data = json_decode($matches[1]);
186 $serializer_options = array (
188 'encoding' => "UTF-8",
190 'rootName' => $rootName,
193 $serializer = new XML_Serializer($serializer_options);
195 $status = $serializer->serialize($data);
196 if (PEAR::isError($status)) {
197 trigger_error($status->getMessage(), E_USER_ERROR);
201 return $serializer->getSerializedData();
204 private function get_xml_instagram_com($html) {
205 return $this->json_to_xml($html, '/window._sharedData = (.*);/', 'instagram');
208 private function html_to_xml($html, $host) {
209 $xmlDoc = new DOMDocument();
211 // Handle warnings and errors when loading invalid HTML.
212 $xml_errors_value = libxml_use_internal_errors(true);
214 // If there is a host-specific method to get the xml data, use it!
215 $get_xml_host_method = 'get_xml_' . str_replace(".", "_", $host);
216 if (method_exists($this, $get_xml_host_method)) {
217 $xml_data = call_user_func_array(array($this, $get_xml_host_method), array($html));
218 $xmlDoc->loadXML($xml_data);
220 $xmlDoc->loadHTML($html);
223 foreach (libxml_get_errors() as $xml_error) {
224 $this->log_xml_error($xml_error);
226 libxml_clear_errors();
227 libxml_use_internal_errors($xml_errors_value);
232 public function tweep($src_url) {
233 $url = parse_url($src_url);
234 if (FALSE === $url || empty($url["host"])) {
235 trigger_error("Invalid url: $src_url", E_USER_ERROR);
239 $xsltProcessor = $this->load_stylesheet($url["host"]);
240 if (NULL === $xsltProcessor) {
244 $html = $this->get_contents($src_url);
245 if (FALSE === $html) {
249 $xmlDoc = $this->html_to_xml($html, $url["host"]);
250 if (NULL === $xmlDoc) {
254 $output = $xsltProcessor->transformToXML($xmlDoc);
256 if (FALSE === $output) {
257 trigger_error('XSL transformation failed.', E_USER_ERROR);
266 return (substr(php_sapi_name(), 0, 3) == 'cli');
269 function usage($argv)
272 $usage = "{$argv[0]} [-e|-h|--help] <src_url>\n";
274 $usage = htmlentities("{$_SERVER['SCRIPT_NAME']}?src_url=<src_url>&generate_enclosure=<0|1>");
277 return "usage: $usage";
280 function parse_options_cli($argv, $argc)
283 'generate_enclosure' => FALSE
289 $cli_options = getopt("eh", array("help"));
290 foreach ($cli_options as $opt => $val) {
293 $options['generate_enclosure'] = TRUE;
300 fwrite(STDERR, usage($argv));
305 $options['src_url'] = $argv[count($cli_options) + 1];
310 function parse_options_query_string()
313 'generate_enclosure' => FALSE
316 if (isset($_GET['src_url']))
317 $options['src_url'] = $_GET['src_url'];
319 if (isset($_GET['generate_enclosure']))
320 $options['generate_enclosure'] = $_GET['generate_enclosure'] == 1;
327 $options = parse_options_cli($argv, $argc);
328 $ERROR_STREAM = fopen('php://stderr', 'w');
330 $options = parse_options_query_string();
331 $ERROR_STREAM = fopen('php://output', 'w');
334 if (!isset($options['src_url'])) {
335 fwrite($ERROR_STREAM, usage($argv));
339 $tweeper = new Tweeper($options['generate_enclosure']);
340 echo $tweeper->tweep($options['src_url']);