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 'Symfony/Component/Serializer/autoload.php';
23 use Symfony\Component\Serializer\Serializer;
24 use Symfony\Component\Serializer\Encoder\XmlEncoder;
25 use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
27 date_default_timezone_set('UTC');
31 private static $USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20130405 Firefox/22.0";
33 public function __construct($generate_enclosure = FALSE) {
34 $this->generate_enclosure = $generate_enclosure;
37 public static function epoch_to_gmdate($timestamp) {
38 if (!is_numeric($timestamp) || is_nan($timestamp)) {
42 return gmdate('D, d M Y H:i:s', $timestamp) . ' GMT';
45 public static function str_to_gmdate($date) {
46 $timestamp = strtotime($date);
47 if (FALSE === $timestamp) {
51 return Tweeper::epoch_to_gmdate($timestamp);
54 private static function get_contents($url) {
55 $ch = curl_init($url);
56 curl_setopt_array($ch, array(
57 CURLOPT_HEADER => FALSE,
58 CURLOPT_FOLLOWLOCATION => TRUE, // follow http redirects to get the real URL
59 CURLOPT_RETURNTRANSFER => TRUE,
60 CURLOPT_SSL_VERIFYHOST => FALSE,
61 CURLOPT_SSL_VERIFYPEER => FALSE,
62 CURLOPT_HTTPHEADER => array('Accept-language: en'),
63 CURLOPT_USERAGENT => Tweeper::$USER_AGENT,
65 $contents = curl_exec($ch);
71 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) {
90 $supported_content_types = array(
108 // The RSS specification says that the enclosure element url must be http.
109 // See http://sourceforge.net/p/feedvalidator/bugs/72/
110 $http_url = preg_replace("/^https/", "http", $url);
112 $url_info = Tweeper::get_info($http_url);
114 $supported = in_array($url_info['content_type'], $supported_content_types);
116 error_log("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url']);
120 $dom = new DomDocument();
121 $enc = $dom->createElement('enclosure');
122 $enc->setAttribute('url', $url_info['url']);
123 $enc->setAttribute('length', $url_info['download_content_length']);
124 $enc->setAttribute('type', $url_info['content_type']);
126 $dom->appendChild($enc);
128 return $dom->saveXML($enc);
131 /* Mimic the message from libxml.c::php_libxml_ctx_error_level() */
132 private function log_xml_error($error) {
135 switch ($error->level) {
136 case LIBXML_ERR_WARNING:
137 $output .= "Warning $error->code: ";
139 case LIBXML_ERR_ERROR:
140 $output .= "Error $error->code: ";
142 case LIBXML_ERR_FATAL:
143 $output .= "Fatal Error $error->code: ";
147 $output .= trim($error->message);
150 $output .= " in $error->file";
152 $output .= " in Entity,";
155 $output .=" line $error->line";
160 private function load_stylesheet($host) {
161 $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
162 if (FALSE === file_exists($stylesheet)) {
163 trigger_error("Conversion to RSS not supported for $host ($stylesheet not found)", E_USER_ERROR);
167 $stylesheet_contents = $this->get_contents($stylesheet);
169 $xslDoc = new DOMDocument();
170 $xslDoc->loadXML($stylesheet_contents);
172 $xsltProcessor = new XSLTProcessor();
173 $xsltProcessor->registerPHPFunctions();
174 $xsltProcessor->setParameter('', 'generateEnclosure', $this->generate_enclosure);
175 $xsltProcessor->importStylesheet($xslDoc);
177 return $xsltProcessor;
180 private function json_to_xml($json, $root_node_name) {
181 // Apparenty the ObjectNormalizer used afterwards is not able to handle
182 // the stdClass object created by json_decode() with the default setting
183 // $assoc = false; so use $assoc = true
184 $data = json_decode($json, $assoc = true);
189 $encoder = new XmlEncoder();
190 $normalizer = new ObjectNormalizer();
191 $serializer = new Serializer(array($normalizer), array($encoder));
193 $serializer_options = array (
194 'xml_encoding' => "UTF-8",
195 'xml_format_output' => TRUE,
196 'xml_root_node_name' => $root_node_name,
199 $xml_data = $serializer->serialize($data, 'xml', $serializer_options);
201 trigger_error("Cannot serialize data", E_USER_ERROR);
208 private function get_xml_instagram_com($html) {
209 // extract the json data from the html code
210 $json_match_expr = '/window._sharedData = (.*);/';
211 $ret = preg_match($json_match_expr, $html, $matches);
213 trigger_error("Cannot match expression: $json_match_expr\n", E_USER_ERROR);
217 return $this->json_to_xml($matches[1], 'instagram');
220 private function preprocess_html_facebook_com($html) {
221 $html = str_replace('<!--', '', $html);
222 $html = str_replace('-->', '', $html);
226 private function html_to_xml($html, $host) {
227 $xmlDoc = new DOMDocument();
229 // Handle warnings and errors when loading invalid HTML.
230 $xml_errors_value = libxml_use_internal_errors(true);
232 // If there is a host-specific method to get the xml data, use it!
233 $get_xml_host_method = 'get_xml_' . str_replace(".", "_", $host);
234 if (method_exists($this, $get_xml_host_method)) {
235 $xml_data = call_user_func_array(array($this, $get_xml_host_method), array($html));
236 $xmlDoc->loadXML($xml_data);
238 $xmlDoc->loadHTML($html);
241 foreach (libxml_get_errors() as $xml_error) {
242 $this->log_xml_error($xml_error);
244 libxml_clear_errors();
245 libxml_use_internal_errors($xml_errors_value);
250 public function tweep($src_url) {
251 $url = parse_url($src_url);
252 if (FALSE === $url || empty($url["host"])) {
253 trigger_error("Invalid url: $src_url", E_USER_ERROR);
257 // Strip the leading www. to be more forgiving on input URLs
258 $host = preg_replace('/^www\./', '', $url["host"]);
260 $xsltProcessor = $this->load_stylesheet($host);
261 if (NULL === $xsltProcessor) {
265 $html = $this->get_contents($src_url);
266 if (FALSE === $html) {
270 $preprocess_html_host_method = 'preprocess_html_' . str_replace(".", "_", $host);
271 if (method_exists($this, $preprocess_html_host_method)) {
272 $html = call_user_func_array(array($this, $preprocess_html_host_method), array($html));
275 $xmlDoc = $this->html_to_xml($html, $host);
276 if (NULL === $xmlDoc) {
280 $output = $xsltProcessor->transformToXML($xmlDoc);
282 if (FALSE === $output) {
283 trigger_error('XSL transformation failed.', E_USER_ERROR);
291 return (php_sapi_name() === "cli");
294 function usage($argv) {
296 $usage = "{$argv[0]} [-e|-h|--help] <src_url>\n";
298 $usage = htmlentities("{$_SERVER['SCRIPT_NAME']}?src_url=<src_url>&generate_enclosure=<0|1>");
301 return "usage: $usage";
304 function parse_options_cli($argv, $argc) {
306 'generate_enclosure' => FALSE
312 $cli_options = getopt("eh", array("help"));
313 foreach ($cli_options as $opt => $val) {
316 $options['generate_enclosure'] = TRUE;
323 fwrite(STDERR, usage($argv));
328 $options['src_url'] = $argv[count($cli_options) + 1];
333 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']);