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 html_to_xml($html, $host) {
205 $xmlDoc = new DOMDocument();
207 // Handle warnings and errors when loading invalid HTML.
208 $xml_errors_value = libxml_use_internal_errors(true);
210 // If there is a host-specific method to get the xml data, use it!
211 $get_xml_host_method = 'get_xml_' . str_replace(".", "_", $host);
212 if (method_exists($this, $get_xml_host_method)) {
213 $xml_data = call_user_func_array(array($this, $get_xml_host_method), array($html));
214 $xmlDoc->loadXML($xml_data);
216 $xmlDoc->loadHTML($html);
219 foreach (libxml_get_errors() as $xml_error) {
220 $this->log_xml_error($xml_error);
222 libxml_clear_errors();
223 libxml_use_internal_errors($xml_errors_value);
228 public function tweep($src_url) {
229 $url = parse_url($src_url);
230 if (FALSE === $url || empty($url["host"])) {
231 trigger_error("Invalid url: $src_url", E_USER_ERROR);
235 $xsltProcessor = $this->load_stylesheet($url["host"]);
236 if (NULL === $xsltProcessor) {
240 $html = $this->get_contents($src_url);
241 if (FALSE === $html) {
245 $xmlDoc = $this->html_to_xml($html, $url["host"]);
246 if (NULL === $xmlDoc) {
250 $output = $xsltProcessor->transformToXML($xmlDoc);
252 if (FALSE === $output) {
253 trigger_error('XSL transformation failed.', E_USER_ERROR);
260 function usage($argv)
262 if (php_sapi_name() != 'cli')
263 $usage = htmlentities("{$_SERVER['SCRIPT_NAME']}?src_url=<src_url>&generate_enclosure=<0|1>");
265 $usage = "{$argv[0]} [-e|-h|--help] <src_url>\n";
267 return "usage: $usage";
270 function parse_options_cli($argv, $argc)
273 'generate_enclosure' => FALSE
279 $cli_options = getopt("eh", array("help"));
280 foreach ($cli_options as $opt => $val) {
283 $options['generate_enclosure'] = TRUE;
290 fwrite(STDERR, usage($argv));
295 $options['src_url'] = $argv[count($cli_options) + 1];
300 function parse_options_query_string()
303 'generate_enclosure' => FALSE
306 if (isset($_GET['src_url']))
307 $options['src_url'] = $_GET['src_url'];
309 if (isset($_GET['generate_enclosure']))
310 $options['generate_enclosure'] = $_GET['generate_enclosure'] == 1;
316 if (php_sapi_name() != 'cli') {
317 $options = parse_options_query_string();
318 $ERROR_STREAM = fopen('php://output', 'w');
320 $options = parse_options_cli($argv, $argc);
321 $ERROR_STREAM = fopen('php://stderr', 'w');
324 if (!isset($options['src_url'])) {
325 fwrite($ERROR_STREAM, usage($argv));
329 $tweeper = new Tweeper($options['generate_enclosure']);
330 echo $tweeper->tweep($options['src_url']);