7 * Tweeper - a Twitter to RSS web scraper.
9 * Copyright (C) 2013-2018 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 use Symfony\Component\Serializer\Serializer;
29 use Symfony\Component\Serializer\Encoder\XmlEncoder;
30 use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
32 date_default_timezone_set('UTC');
35 * Scrape supported websites and perform conversion to RSS.
39 private static $userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:60.0) Gecko/20100101 Firefox/60.0";
42 * Create a new Tweeper object controlling optional settings.
44 * @param bool $generate_enclosure
45 * Enables the creation of <enclosure/> elements (disabled by default).
46 * @param bool $show_usernames
47 * Enables showing the username in front of the content for multi-user
48 * sites (enabled by default). Only some stylesheets supports this
49 * functionality (twitter, instagram, pump.io).
51 public function __construct($generate_enclosure = FALSE, $show_usernames = TRUE) {
52 $this->generate_enclosure = $generate_enclosure;
53 $this->show_usernames = $show_usernames;
57 * Convert numeric Epoch to the date format expected in a RSS document.
59 public static function epochToRssDate($timestamp) {
60 if (!is_numeric($timestamp) || is_nan($timestamp)) {
64 return gmdate(DATE_RSS, $timestamp);
68 * Convert generic date string to the date format expected in a RSS document.
70 public static function strToRssDate($date) {
71 $timestamp = strtotime($date);
72 if (FALSE === $timestamp) {
76 return Tweeper::epochToRssDate($timestamp);
80 * Convert string to UpperCamelCase.
82 public static function toUpperCamelCase($str, $delim = ' ') {
83 $str_upper = ucwords($str, $delim);
84 $str_camel_case = str_replace($delim, '', $str_upper);
85 return $str_camel_case;
89 * Get the contents from a URL.
91 private static function getUrlContents($url) {
92 $ch = curl_init($url);
93 curl_setopt_array($ch, array(
94 CURLOPT_HEADER => FALSE,
95 // Follow http redirects to get the real URL.
96 CURLOPT_FOLLOWLOCATION => TRUE,
97 CURLOPT_RETURNTRANSFER => TRUE,
98 CURLOPT_SSL_VERIFYHOST => FALSE,
99 CURLOPT_SSL_VERIFYPEER => FALSE,
100 CURLOPT_HTTPHEADER => array('Accept-language: en'),
101 CURLOPT_USERAGENT => Tweeper::$userAgent,
103 $contents = curl_exec($ch);
104 if (FALSE === $contents) {
105 trigger_error(curl_error($ch));
113 * Get the headers from a URL.
115 private static function getUrlInfo($url) {
116 $ch = curl_init($url);
117 curl_setopt_array($ch, array(
118 CURLOPT_HEADER => TRUE,
119 CURLOPT_NOBODY => TRUE,
120 // Follow http redirects to get the real URL.
121 CURLOPT_FOLLOWLOCATION => TRUE,
122 CURLOPT_RETURNTRANSFER => TRUE,
123 CURLOPT_SSL_VERIFYHOST => FALSE,
124 CURLOPT_SSL_VERIFYPEER => FALSE,
125 CURLOPT_USERAGENT => Tweeper::$userAgent,
128 $url_info = curl_getinfo($ch);
129 if (FALSE === $url_info) {
130 trigger_error(curl_error($ch));
138 * Generate an RSS <enclosure/> element.
140 public static function generateEnclosure($url) {
141 $supported_content_types = array(
142 "application/octet-stream",
162 $url_info = Tweeper::getUrlInfo($url);
164 $supported = in_array($url_info['content_type'], $supported_content_types);
166 error_log("Unsupported enclosure content type \"" . $url_info['content_type'] . "\" for URL: " . $url_info['url']);
170 // The RSS specification says that the enclosure element URL must be http.
171 // See http://sourceforge.net/p/feedvalidator/bugs/72/
172 $http_url = preg_replace("/^https/", "http", $url_info['url']);
174 $dom = new DOMDocument();
175 $enc = $dom->createElement('enclosure');
176 $enc->setAttribute('url', $http_url);
177 $enc->setAttribute('length', $url_info['download_content_length']);
178 $enc->setAttribute('type', $url_info['content_type']);
184 * Mimic the message from libxml.c::php_libxml_ctx_error_level()
186 private static function logXmlError($error) {
189 switch ($error->level) {
190 case LIBXML_ERR_WARNING:
191 $output .= "Warning $error->code: ";
194 case LIBXML_ERR_ERROR:
195 $output .= "Error $error->code: ";
198 case LIBXML_ERR_FATAL:
199 $output .= "Fatal Error $error->code: ";
203 $output .= trim($error->message);
206 $output .= " in $error->file";
209 $output .= " in Entity,";
212 $output .= " line $error->line";
218 * Convert json to XML.
220 private static function jsonToXml($json, $root_node_name) {
221 // Apparently the ObjectNormalizer used afterwards is not able to handle
222 // the stdClass object created by json_decode() with the default setting
223 // $assoc = false; so use $assoc = true.
224 $data = json_decode($json, $assoc = TRUE);
229 $encoder = new XmlEncoder();
230 $normalizer = new ObjectNormalizer();
231 $serializer = new Serializer(array($normalizer), array($encoder));
233 $serializer_options = array(
234 'xml_encoding' => "UTF-8",
235 'xml_format_output' => TRUE,
236 'xml_root_node_name' => $root_node_name,
239 $xml_data = $serializer->serialize($data, 'xml', $serializer_options);
241 trigger_error("Cannot serialize data", E_USER_ERROR);
249 * Convert the Instagram content to XML.
251 private function getXmlInstagramCom($html) {
252 // Extract the json data from the html code.
253 $json_match_expr = '/window._sharedData = (.*);/';
254 $ret = preg_match($json_match_expr, $html, $matches);
256 trigger_error("Cannot match expression: $json_match_expr\n", E_USER_ERROR);
260 $data = json_decode($matches[1], $assoc = TRUE);
262 // The "qe" object contains elements which will result in invalid XML
263 // element names, so remove it.
266 // The "knobs" object contains elements with undefined namespaces, so
267 // remove it to silence an error message.
268 unset($data["knobs"]);
270 $json = json_encode($data);
272 return Tweeper::jsonToXml($json, 'instagram');
276 * Make the Facebook HTML processable.
278 private function preprocessHtmlFacebookCom($html) {
279 $html = str_replace('<!--', '', $html);
280 $html = str_replace('-->', '', $html);
285 * Convert the HTML retrieved from the site to XML.
287 private function htmlToXml($html, $host) {
288 $xmlDoc = new DOMDocument();
290 // Handle warnings and errors when loading invalid HTML.
291 $xml_errors_value = libxml_use_internal_errors(TRUE);
293 // If there is a host-specific method to get the XML data, use it!
294 $get_xml_host_method = 'getXml' . Tweeper::toUpperCamelCase($host, '.');
295 if (method_exists($this, $get_xml_host_method)) {
296 $xml_data = call_user_func_array(array($this, $get_xml_host_method), array($html));
297 $xmlDoc->loadXML($xml_data);
300 $xmlDoc->loadHTML($html);
303 foreach (libxml_get_errors() as $xml_error) {
304 Tweeper::logXmlError($xml_error);
306 libxml_clear_errors();
307 libxml_use_internal_errors($xml_errors_value);
313 * Load a stylesheet if the web site is supported.
315 private function loadStylesheet($host) {
316 $stylesheet = "file://" . __DIR__ . "/rss_converter_" . $host . ".xsl";
317 if (FALSE === file_exists($stylesheet)) {
318 trigger_error("Conversion to RSS not supported for $host ($stylesheet not found)", E_USER_ERROR);
322 $stylesheet_contents = Tweeper::getUrlContents($stylesheet);
324 $xslDoc = new DOMDocument();
325 $xslDoc->loadXML($stylesheet_contents);
327 $xsltProcessor = new XSLTProcessor();
328 $xsltProcessor->registerPHPFunctions();
329 $xsltProcessor->setParameter('', 'generate-enclosure', $this->generate_enclosure);
330 $xsltProcessor->setParameter('', 'show-usernames', $this->show_usernames);
331 $xsltProcessor->importStylesheet($xslDoc);
333 return $xsltProcessor;
337 * Convert the site content to RSS.
339 public function tweep($src_url, $host=NULL, $validate_scheme=TRUE) {
340 $url = parse_url($src_url);
341 if (FALSE === $url) {
342 trigger_error("Invalid URL: $src_url", E_USER_ERROR);
346 if (TRUE === $validate_scheme) {
347 $scheme = $url["scheme"];
348 if (!in_array($scheme, array("http", "https"))) {
349 trigger_error("unsupported scheme: $scheme", E_USER_ERROR);
354 // if the host is not given derive it from the URL
355 if (NULL === $host) {
356 if (empty($url["host"])) {
357 trigger_error("Invalid host in URL: $src_url", E_USER_ERROR);
360 // Strip the leading www. to be more forgiving on input URLs.
361 $host = preg_replace('/^www\./', '', $url["host"]);
364 $xsltProcessor = $this->loadStylesheet($host);
365 if (NULL === $xsltProcessor) {
369 $html = Tweeper::getUrlContents($src_url);
370 if (FALSE === $html) {
374 $preprocess_html_host_method = 'preprocessHtml' . Tweeper::toUpperCamelCase($host, '.');
375 if (method_exists($this, $preprocess_html_host_method)) {
376 $html = call_user_func_array(array($this, $preprocess_html_host_method), array($html));
379 $xmlDoc = $this->htmlToXml($html, $host);
380 if (NULL === $xmlDoc) {
384 $output = $xsltProcessor->transformToXML($xmlDoc);
385 if (FALSE === $output) {
386 trigger_error('XSL transformation failed.', E_USER_ERROR);