summaryrefslogtreecommitdiff
path: root/plugins/af_zz_imgsetsizes/init.php
blob: cdfd06338d95b6689bb0aefb030325d3a7dace14 (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
<?php
class Af_Zz_ImgSetSizes extends Plugin {
	private $host;

	function about() {
		return array(1.0,
			"Set width/height attributes for images in articles (requires CURL and GD)",
			"fox");
	}

	function flags() {
		return array("needs_curl" => true);
	}

	function init($host) {
		$this->host = $host;

		if (function_exists("curl_init") && function_exists("getimagesize")) {
			$host->add_hook($host::HOOK_ARTICLE_FILTER, $this);
		}
	}

	function hook_article_filter($article) {

		if (defined('NO_CURL') || !function_exists("curl_init"))
			return $article;

		$charset_hack = '<head>
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
		</head>';

		$doc = new DOMDocument();
		$doc->loadHTML($charset_hack . $article["content"]);

		$found = false;

		if ($doc) {
			$xpath = new DOMXpath($doc);

			$images = $xpath->query('(//img[@src])');

			foreach ($images as $img) {
				$src = $img->getAttribute("src");

				$ch = curl_init($src);
				curl_setopt($ch, CURLOPT_HEADER, 0);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
				curl_setopt($ch, CURLOPT_RANGE, "0-32768");

				@$result = curl_exec($ch);
				$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

				if ($result && ($http_code == 200 || $http_code == 206)) {
					$filename = tempnam(sys_get_temp_dir(), "ttsizecheck");

					if ($filename) {
						$fh = fopen($filename, "w");
						if ($fh) {
							fwrite($fh, $result);
							fclose($fh);

							@$info = getimagesize($filename);

							if ($info && $info[0] > 0 && $info[1] > 0) {
								$img->setAttribute("width", $info[0]);
								$img->setAttribute("height", $info[1]);
								$found = true;
							}

							unlink($filename);
						}
					}
				}
			}

			if ($found) {
				$doc->removeChild($doc->firstChild); //remove doctype
				$article["content"] = $doc->saveHTML();
			}
		}

		return $article;

	}


	function api_version() {
		return 2;
	}

}
?>