summaryrefslogtreecommitdiffstats
path: root/articleenhancer/xpatharticleenhancer.php
blob: 009486b8be521f3fb20722f56fc1f49f09d343ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
<?php
/**
 * ownCloud - News
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Alessandro Cosentino <cosenal@gmail.com>
 * @author Bernhard Posselt <dev@bernhard-posselt.com>
 * @copyright Alessandro Cosentino 2012
 * @copyright Bernhard Posselt 2012, 2014
 */

namespace OCA\News\ArticleEnhancer;

require_once __DIR__ . '/../3rdparty/Net_URL2/Net/URL2.php';

use \ZendXml\Security;
use \Net_URL2;

use \OCA\News\Db\Item;
use \OCA\News\Utility\SimplePieAPIFactory;
use \OCA\News\Utility\Config;



class XPathArticleEnhancer implements ArticleEnhancer {


	private $fileFactory;
	private $maximumTimeout;
	private $config;
	private $regexXPathPair;


    /**
     * @param \OCA\News\Utility\SimplePieAPIFactory $fileFactory
     * @param array $regexXPathPair an associative array containing regex to
     * match the url and the xpath that should be used for it to extract the
     * page
     * @param \OCA\News\Utility\Config $config
     * @internal param \OCA\News\ArticleEnhancer\a $SimplePieFileFactory factory for getting a simple pie file instance
     * @internal param int $maximumTimeout maximum timeout in seconds, defaults to 10 sec
     */
	public function __construct(SimplePieAPIFactory $fileFactory,
	                            array $regexXPathPair, Config $config){
		$this->regexXPathPair = $regexXPathPair;
		$this->fileFactory = $fileFactory;
		$this->maximumTimeout = $config->getFeedFetcherTimeout();
		$this->config = $config;
	}

	/**
	 * @param \OCA\News\Db\Item $item
	 * @return \OCA\News\Db\Item enhanced item
	 */
	public function enhance(Item $item){

		foreach($this->regexXPathPair as $regex => $search) {

			if(preg_match($regex, $item->getUrl())) {
				$file = $this->getFile($item->getUrl());

				// convert encoding by detecting charset from header
                $contentType = $file->headers['content-type'];
                $body = $file->body;

				if( preg_match( '/(?<=charset=)[^;]*/', $contentType, $matches ) ) {
                    $body = mb_convert_encoding($body, 'HTML-ENTITIES', $matches[0]);
				}

				$dom = new \DOMDocument();

				Security::scan($body, $dom, function ($xml, $dom) {
					return @$dom->loadHTML($xml, LIBXML_NONET);
				});

				$xpath = new \DOMXpath($dom);
				$xpathResult = $xpath->evaluate($search);

				// in case it wasnt a text query assume its a single entry
				if(!is_string($xpathResult)) {
					$xpathResult = $this->domToString($xpathResult);
				}

				// convert all relative to absolute URLs
				$xpathResult = $this->substituteRelativeLinks($xpathResult, $item->getUrl());

				if($xpathResult) {
					$item->setBody($xpathResult);
				}
			}
		}

		return $item;
	}


	private function getFile($url) {
		return $this->fileFactory->getFile(
			$url, $this->maximumTimeout, 5, null, 'Mozilla/5.0 AppleWebKit',
			false, null, null, null
		);
	}


	/**
	 * Method which converts all relative "href" and "src" URLs of
	 * a HTML snippet with their absolute equivalent
	 * @param string $xmlString a HTML snippet as string with the relative URLs to be replaced
	 * @param string $absoluteUrl the approptiate absolute url of the HTML snippet
	 * @return string the result HTML snippet as a string
	 */
	protected function substituteRelativeLinks($xmlString, $absoluteUrl) {
		$dom = new \DOMDocument();
		$dom->preserveWhiteSpace = false;

		// return, if xml is empty or loading the HTML fails
		$isLoaded = Security::scan($xmlString, $dom, function ($xml, $dom) {
			return @$dom->loadHTML($xml, LIBXML_NONET);
		});

		if(trim($xmlString) === '' || !$isLoaded) {
			return $xmlString;
		}

		// remove <!DOCTYPE
		$dom->removeChild($dom->firstChild);
		// remove <html></html>
		$dom->replaceChild($dom->firstChild->firstChild, $dom->firstChild);

		foreach (['href', 'src'] as $attribute) {
			$xpath = new \DOMXpath($dom);
			$xpathResult = $xpath->query(
				"//*[@" . $attribute . " " .
				"and not(contains(@" . $attribute . ", '://')) " .
				"and not(starts-with(@" . $attribute . ", 'mailto:')) " .
				"and not(starts-with(@" . $attribute . ", '//'))]");
			foreach ($xpathResult as $linkNode) {
				$urlElement = $linkNode->attributes->getNamedItem($attribute);
				$abs = $this->relativeToAbsoluteUrl($urlElement->nodeValue, $absoluteUrl);
				$urlElement->nodeValue = htmlspecialchars($abs);
			}
		}

		// save dom to string and remove <body></body>
		$xmlString = substr(trim($dom->saveHTML()), 6, -7);
		// domdocument spoils the string with line breaks between the elements. strip them.
		$xmlString = str_replace('\n', '', $xmlString);

		return $xmlString;
	}


	/**
	 * Method which builds a URL by taking a relative URL and its corresponding
	 * absolute URL
	 * For example relative URL "../example/path/file.php?a=1#anchor" and
	 * absolute URL "https://username:password@www.website.com/subfolder/index.html"
	 * will result in "https://username:password@www.website.com/example/path/file.php?a=1#anchor"
	 * @param string $relativeUrl the relative URL
	 * @param string $absoluteUrl the absolute URL with at least scheme and host
	 * @return string the resulting absolute URL
	 */
	protected function relativeToAbsoluteUrl($relativeUrl, $absoluteUrl) {
		$base = new Net_URL2($absoluteUrl);
		return $base->resolve($relativeUrl);
	}


	/**
	 * Method which turns an xpath result to a string
	 * you can customize it by overwriting this method
	 * @param mixed $xpathResult the result from the xpath query
	 * @return string the result as a string
	 */
	protected function domToString($xpathResult) {
		$result = '';
		foreach($xpathResult as $node) {
			$result .= $this->toInnerHTML($node);
		}
		return $result;
	}


	protected function toInnerHTML($node) {
		$dom = new \DOMDocument();
		$dom->appendChild($dom->importNode($node, true));
		return trim($dom->saveHTML($dom->documentElement));
	}


}