4 * Tweeper - a Twitter to RSS web scraper.
6 * Copyright (C) 2013-2015 Antonio Ospite <ao2@ao2.it>
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 require_once 'Symfony/Component/Serializer/autoload.php';
24 use Symfony\Component\Serializer\Serializer;
25 use Symfony\Component\Serializer\Encoder\XmlEncoder;
26 use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
28 date_default_timezone_set('UTC');
31 * Scrape supported websites and perform conversion to RSS.
35 private static $USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20130405 Firefox/22.0";
38 * Constructor sets up {@link $generate_enclosure}.
40 public function __construct($generate_enclosure = FALSE) {
41 $this->generate_enclosure = $generate_enclosure;
45 * Convert numeric Epoch to the date format expected in a RSS document.
47 public static function epoch_to_gmdate($timestamp) {
48 if (!is_numeric($timestamp) || is_nan($timestamp)) {
52 return gmdate('D, d M Y H:i:s', $timestamp) . ' GMT';
56 * Convert generic date string to the date format expected in a RSS document.
58 public static function str_to_gmdate($date) {
59 $timestamp = strtotime($date);
60 if (FALSE === $timestamp) {
64 return Tweeper::epoch_to_gmdate($timestamp);
68 * Get the contents from a URL.
70 private static function get_contents($url) {
71 $ch = curl_init($url);
72 curl_setopt_array($ch, array(
73 CURLOPT_HEADER => FALSE,
74 // Follow http redirects to get the real URL.
75 CURLOPT_FOLLOWLOCATION => TRUE,
76 CURLOPT_RETURNTRANSFER => TRUE,
77 CURLOPT_SSL_VERIFYHOST => FALSE,
78 CURLOPT_SSL_VERIFYPEER => FALSE,
79 CURLOPT_HTTPHEADER => array('Accept-language: en'),
80 CURLOPT_USERAGENT => Tweeper::$USER_AGENT,
82 $contents = curl_exec($ch);
89 * Get the headers from a URL.
91 private static function get_info($url) {
92 $ch = curl_init($url);
93 curl_setopt_array($ch, array(
94 CURLOPT_HEADER => TRUE,
95 CURLOPT_NOBODY => TRUE,
96 // Follow http redirects to get the real URL.
97 CURLOPT_FOLLOWLOCATION => TRUE,
98 CURLOPT_RETURNTRANSFER => TRUE,
99 CURLOPT_SSL_VERIFYHOST => FALSE,
100 CURLOPT_SSL_VERIFYPEER => FALSE,
101 CURLOPT_USERAGENT => Tweeper::$USER_AGENT,
104 $url_info = curl_getinfo($ch);
111 * Generate an RSS <enclosure/> element.
113 public static function generate_enclosure($url) {
114 $supported_content_types = array(
132 // The RSS specification says that the enclosure element url must be http.
133 // See http://sourceforge.net/p/feedvalidator/bugs/72/
134 $http_url = preg_replace("/^https/", "http", $url);
136 $url_info = Tweeper::get_info($http_url);
138 $supported = in_array($url_info['content_type'], $supported_content_types);
140 error_log("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url']);
144 $dom = new DomDocument();
145 $enc = $dom->createElement('enclosure');
146 $enc->setAttribute('url', $url_info['url']);
147 $enc->setAttribute('length', $url_info['download_content_length']);
148 $enc->setAttribute('type', $url_info['content_type']);
150 $dom->appendChild($enc);
152 return $dom->saveXML($enc);
156 * Mimic the message from libxml.c::php_libxml_ctx_error_level()
158 private function log_xml_error($error) {
161 switch ($error->level) {
162 case LIBXML_ERR_WARNING:
163 $output .= "Warning $error->code: ";
166 case LIBXML_ERR_ERROR:
167 $output .= "Error $error->code: ";
170 case LIBXML_ERR_FATAL:
171 $output .= "Fatal Error $error->code: ";
175 $output .= trim($error->message);
178 $output .= " in $error->file";
181 $output .= " in Entity,";
184 $output .= " line $error->line";
190 * Load a stylesheet if the web site is supported.
192 private function load_stylesheet($host) {
193 $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
194 if (FALSE === file_exists($stylesheet)) {
195 trigger_error("Conversion to RSS not supported for $host ($stylesheet not found)", E_USER_ERROR);
199 $stylesheet_contents = $this->get_contents($stylesheet);
201 $xslDoc = new DOMDocument();
202 $xslDoc->loadXML($stylesheet_contents);
204 $xsltProcessor = new XSLTProcessor();
205 $xsltProcessor->registerPHPFunctions();
206 $xsltProcessor->setParameter('', 'generateEnclosure', $this->generate_enclosure);
207 $xsltProcessor->importStylesheet($xslDoc);
209 return $xsltProcessor;
213 * Convert json to xml.
215 private function json_to_xml($json, $root_node_name) {
216 // Apparenty the ObjectNormalizer used afterwards is not able to handle
217 // the stdClass object created by json_decode() with the default setting
218 // $assoc = false; so use $assoc = true.
219 $data = json_decode($json, $assoc = TRUE);
224 $encoder = new XmlEncoder();
225 $normalizer = new ObjectNormalizer();
226 $serializer = new Serializer(array($normalizer), array($encoder));
228 $serializer_options = array(
229 'xml_encoding' => "UTF-8",
230 'xml_format_output' => TRUE,
231 'xml_root_node_name' => $root_node_name,
234 $xml_data = $serializer->serialize($data, 'xml', $serializer_options);
236 trigger_error("Cannot serialize data", E_USER_ERROR);
244 * Convert the Instagram content to XML.
246 private function get_xml_instagram_com($html) {
247 // Extract the json data from the html code.
248 $json_match_expr = '/window._sharedData = (.*);/';
249 $ret = preg_match($json_match_expr, $html, $matches);
251 trigger_error("Cannot match expression: $json_match_expr\n", E_USER_ERROR);
255 return $this->json_to_xml($matches[1], 'instagram');
259 * Make the Facebook HTML processable.
261 private function preprocess_html_facebook_com($html) {
262 $html = str_replace('<!--', '', $html);
263 $html = str_replace('-->', '', $html);
268 * Convert the HTML retrieved from the site to XML.
270 private function html_to_xml($html, $host) {
271 $xmlDoc = new DOMDocument();
273 // Handle warnings and errors when loading invalid HTML.
274 $xml_errors_value = libxml_use_internal_errors(TRUE);
276 // If there is a host-specific method to get the xml data, use it!
277 $get_xml_host_method = 'get_xml_' . str_replace(".", "_", $host);
278 if (method_exists($this, $get_xml_host_method)) {
279 $xml_data = call_user_func_array(array($this, $get_xml_host_method), array($html));
280 $xmlDoc->loadXML($xml_data);
283 $xmlDoc->loadHTML($html);
286 foreach (libxml_get_errors() as $xml_error) {
287 $this->log_xml_error($xml_error);
289 libxml_clear_errors();
290 libxml_use_internal_errors($xml_errors_value);
296 * Convert the site content to RSS.
298 public function tweep($src_url) {
299 $url = parse_url($src_url);
300 if (FALSE === $url || empty($url["host"])) {
301 trigger_error("Invalid url: $src_url", E_USER_ERROR);
305 // Strip the leading www. to be more forgiving on input URLs.
306 $host = preg_replace('/^www\./', '', $url["host"]);
308 $xsltProcessor = $this->load_stylesheet($host);
309 if (NULL === $xsltProcessor) {
313 $html = $this->get_contents($src_url);
314 if (FALSE === $html) {
318 $preprocess_html_host_method = 'preprocess_html_' . str_replace(".", "_", $host);
319 if (method_exists($this, $preprocess_html_host_method)) {
320 $html = call_user_func_array(array($this, $preprocess_html_host_method), array($html));
323 $xmlDoc = $this->html_to_xml($html, $host);
324 if (NULL === $xmlDoc) {
328 $output = $xsltProcessor->transformToXML($xmlDoc);
330 if (FALSE === $output) {
331 trigger_error('XSL transformation failed.', E_USER_ERROR);
340 * Check if the script is being run from the command line.
343 return (php_sapi_name() === "cli");
347 * Show the script usage.
349 function usage($argv) {
351 $usage = "{$argv[0]} [-e|-h|--help] <src_url>\n";
354 $usage = htmlentities("{$_SERVER['SCRIPT_NAME']}?src_url=<src_url>&generate_enclosure=<0|1>");
357 return "usage: $usage";
361 * Parse command line options.
363 function parse_options_cli($argv, $argc) {
365 'generate_enclosure' => FALSE,
372 $cli_options = getopt("eh", array("help"));
373 foreach ($cli_options as $opt => $val) {
376 $options['generate_enclosure'] = TRUE;
385 fwrite(STDERR, usage($argv));
390 $options['src_url'] = $argv[count($cli_options) + 1];
396 * Parse options passed from a query string.
398 function parse_options_query_string() {
400 'generate_enclosure' => FALSE,
403 if (isset($_GET['src_url'])) {
404 $options['src_url'] = $_GET['src_url'];
407 if (isset($_GET['generate_enclosure'])) {
408 $options['generate_enclosure'] = $_GET['generate_enclosure'] == 1;
415 $options = parse_options_cli($argv, $argc);
416 $ERROR_STREAM = fopen('php://stderr', 'w');
419 $options = parse_options_query_string();
420 $ERROR_STREAM = fopen('php://output', 'w');
423 if (!isset($options['src_url'])) {
424 fwrite($ERROR_STREAM, usage(is_cli() ? $argv : NULL));
428 $tweeper = new Tweeper($options['generate_enclosure']);
429 echo $tweeper->tweep($options['src_url']);