summaryrefslogtreecommitdiffstats
path: root/articleenhancer/globalarticleenhancer.php
blob: 512d516972b8b1ee38f02c09ead9a6fce61cd655 (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
<?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;

use \OCA\News\Db\Item;


class GlobalArticleEnhancer implements ArticleEnhancer {


	/**
	 * This method is run after all enhancers and for every item
	 */
	public function enhance(Item $item) {
		$dom = new \DOMDocument();
		@$dom->loadHTML($item->getBody(), LIBXML_HTML_NOIMPLIED |
			                              LIBXML_HTML_NODEFDTD);
		$xpath = new \DOMXpath($dom);

		// remove youtube autoplay
		// NOTE: PHP supports only XPath 1.0 so no matches() function :(
		$youtubeIframes = "//iframe[contains(@src, 'youtube.com')]";

		$elements = $xpath->query($youtubeIframes);
		foreach ($elements as $element) {

			// src needs to be matched against regex to prevent false positives
			// and because theres no XPath matches function available
			$src = $element->getAttribute('src');
			$regex = '%^(http://|https://|//)(www\.)?youtube.com/.*\?.*autoplay=1.*%i';

			if (preg_match($regex, $src)) {
				$replaced = str_replace('autoplay=1', 'autoplay=0', $src);
				$element->setAttribute('src', $replaced);
			}
		}

		// save all changes back to the item
		$item->setBody(trim($dom->saveHTML()));

		return $item;
	}


}