7 * Tweeper - a Twitter to RSS web scraper.
9 * Copyright (C) 2013-2015 Antonio Ospite <ao2@ao2.it>
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
28 require_once 'Symfony/Component/Serializer/autoload.php';
30 use Symfony\Component\Serializer\Serializer;
31 use Symfony\Component\Serializer\Encoder\XmlEncoder;
32 use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
34 date_default_timezone_set('UTC');
37 * Scrape supported websites and perform conversion to RSS.
41 private static $userAgent = "Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20130405 Firefox/22.0";
44 * Constructor sets up {@link $generate_enclosure}.
46 public function __construct($generate_enclosure = FALSE) {
47 $this->generate_enclosure = $generate_enclosure;
51 * Convert numeric Epoch to the date format expected in a RSS document.
53 public static function epochToRssDate($timestamp) {
54 if (!is_numeric($timestamp) || is_nan($timestamp)) {
58 return gmdate(DATE_RSS, $timestamp);
62 * Convert generic date string to the date format expected in a RSS document.
64 public static function strToRssDate($date) {
65 $timestamp = strtotime($date);
66 if (FALSE === $timestamp) {
70 return Tweeper::epochToRssDate($timestamp);
74 * Convert string to UpperCamelCase.
76 public static function toUpperCamelCase($str, $delim = ' ') {
77 $str_upper = ucwords($str, $delim);
78 $str_camel_case = str_replace($delim, '', $str_upper);
79 return $str_camel_case;
83 * Get the contents from a URL.
85 private static function getUrlContents($url) {
86 $ch = curl_init($url);
87 curl_setopt_array($ch, array(
88 CURLOPT_HEADER => FALSE,
89 // Follow http redirects to get the real URL.
90 CURLOPT_FOLLOWLOCATION => TRUE,
91 CURLOPT_RETURNTRANSFER => TRUE,
92 CURLOPT_SSL_VERIFYHOST => FALSE,
93 CURLOPT_SSL_VERIFYPEER => FALSE,
94 CURLOPT_HTTPHEADER => array('Accept-language: en'),
95 CURLOPT_USERAGENT => Tweeper::$userAgent,
97 $contents = curl_exec($ch);
98 if (FALSE === $contents) {
99 trigger_error(curl_error($ch));
107 * Get the headers from a URL.
109 private static function getUrlInfo($url) {
110 $ch = curl_init($url);
111 curl_setopt_array($ch, array(
112 CURLOPT_HEADER => TRUE,
113 CURLOPT_NOBODY => TRUE,
114 // Follow http redirects to get the real URL.
115 CURLOPT_FOLLOWLOCATION => TRUE,
116 CURLOPT_RETURNTRANSFER => TRUE,
117 CURLOPT_SSL_VERIFYHOST => FALSE,
118 CURLOPT_SSL_VERIFYPEER => FALSE,
119 CURLOPT_USERAGENT => Tweeper::$userAgent,
122 $url_info = curl_getinfo($ch);
123 if (FALSE === $url_info) {
124 trigger_error(curl_error($ch));
132 * Generate an RSS <enclosure/> element.
134 public static function generateEnclosure($url) {
135 $supported_content_types = array(
136 "application/octet-stream",
156 $url_info = Tweeper::getUrlInfo($url);
158 $supported = in_array($url_info['content_type'], $supported_content_types);
160 error_log("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url']);
164 // The RSS specification says that the enclosure element URL must be http.
165 // See http://sourceforge.net/p/feedvalidator/bugs/72/
166 $http_url = preg_replace("/^https/", "http", $url_info['url']);
168 $dom = new DOMDocument();
169 $enc = $dom->createElement('enclosure');
170 $enc->setAttribute('url', $http_url);
171 $enc->setAttribute('length', $url_info['download_content_length']);
172 $enc->setAttribute('type', $url_info['content_type']);
178 * Mimic the message from libxml.c::php_libxml_ctx_error_level()
180 private static function logXmlError($error) {
183 switch ($error->level) {
184 case LIBXML_ERR_WARNING:
185 $output .= "Warning $error->code: ";
188 case LIBXML_ERR_ERROR:
189 $output .= "Error $error->code: ";
192 case LIBXML_ERR_FATAL:
193 $output .= "Fatal Error $error->code: ";
197 $output .= trim($error->message);
200 $output .= " in $error->file";
203 $output .= " in Entity,";
206 $output .= " line $error->line";
212 * Convert json to XML.
214 private static function jsonToXml($json, $root_node_name) {
215 // Apparently the ObjectNormalizer used afterwards is not able to handle
216 // the stdClass object created by json_decode() with the default setting
217 // $assoc = false; so use $assoc = true.
218 $data = json_decode($json, $assoc = TRUE);
223 $encoder = new XmlEncoder();
224 $normalizer = new ObjectNormalizer();
225 $serializer = new Serializer(array($normalizer), array($encoder));
227 $serializer_options = array(
228 'xml_encoding' => "UTF-8",
229 'xml_format_output' => TRUE,
230 'xml_root_node_name' => $root_node_name,
233 $xml_data = $serializer->serialize($data, 'xml', $serializer_options);
235 trigger_error("Cannot serialize data", E_USER_ERROR);
243 * Convert the Instagram content to XML.
245 private function getXmlInstagramCom($html) {
246 // Extract the json data from the html code.
247 $json_match_expr = '/window._sharedData = (.*);/';
248 $ret = preg_match($json_match_expr, $html, $matches);
250 trigger_error("Cannot match expression: $json_match_expr\n", E_USER_ERROR);
254 return Tweeper::jsonToXml($matches[1], 'instagram');
258 * Make the Facebook HTML processable.
260 private function preprocessHtmlFacebookCom($html) {
261 $html = str_replace('<!--', '', $html);
262 $html = str_replace('-->', '', $html);
267 * Convert the HTML retrieved from the site to XML.
269 private function htmlToXml($html, $host) {
270 $xmlDoc = new DOMDocument();
272 // Handle warnings and errors when loading invalid HTML.
273 $xml_errors_value = libxml_use_internal_errors(TRUE);
275 // If there is a host-specific method to get the XML data, use it!
276 $get_xml_host_method = 'getXml' . Tweeper::toUpperCamelCase($host, '.');
277 if (method_exists($this, $get_xml_host_method)) {
278 $xml_data = call_user_func_array(array($this, $get_xml_host_method), array($html));
279 $xmlDoc->loadXML($xml_data);
282 $xmlDoc->loadHTML($html);
285 foreach (libxml_get_errors() as $xml_error) {
286 Tweeper::logXmlError($xml_error);
288 libxml_clear_errors();
289 libxml_use_internal_errors($xml_errors_value);
295 * Load a stylesheet if the web site is supported.
297 private function loadStylesheet($host) {
298 $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
299 if (FALSE === file_exists($stylesheet)) {
300 trigger_error("Conversion to RSS not supported for $host ($stylesheet not found)", E_USER_ERROR);
304 $stylesheet_contents = Tweeper::getUrlContents($stylesheet);
306 $xslDoc = new DOMDocument();
307 $xslDoc->loadXML($stylesheet_contents);
309 $xsltProcessor = new XSLTProcessor();
310 $xsltProcessor->registerPHPFunctions();
311 $xsltProcessor->setParameter('', 'generate-enclosure', $this->generate_enclosure);
312 $xsltProcessor->importStylesheet($xslDoc);
314 return $xsltProcessor;
318 * Convert the site content to RSS.
320 public function tweep($src_url) {
321 $url = parse_url($src_url);
322 if (FALSE === $url || empty($url["host"])) {
323 trigger_error("Invalid URL: $src_url", E_USER_ERROR);
327 $scheme = $url["scheme"];
328 if (!in_array($scheme, array("http", "https"))) {
329 trigger_error("unsupported scheme: $scheme", E_USER_ERROR);
333 // Strip the leading www. to be more forgiving on input URLs.
334 $host = preg_replace('/^www\./', '', $url["host"]);
336 $xsltProcessor = $this->loadStylesheet($host);
337 if (NULL === $xsltProcessor) {
341 $html = Tweeper::getUrlContents($src_url);
342 if (FALSE === $html) {
346 $preprocess_html_host_method = 'preprocessHtml' . Tweeper::toUpperCamelCase($host, '.');
347 if (method_exists($this, $preprocess_html_host_method)) {
348 $html = call_user_func_array(array($this, $preprocess_html_host_method), array($html));
351 $xmlDoc = $this->htmlToXml($html, $host);
352 if (NULL === $xmlDoc) {
356 $output = $xsltProcessor->transformToXML($xmlDoc);
358 if (FALSE === $output) {
359 trigger_error('XSL transformation failed.', E_USER_ERROR);