summaryrefslogtreecommitdiff
path: root/plugins/cache_starred_images/init.php
blob: ae0eaf56d679eb3834eab78d50ee3b403192cb74 (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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
<?php
class Cache_Starred_Images extends Plugin implements IHandler {

	/* @var PluginHost $host */
	private $host;
	private $cache_dir;
    private $max_cache_attempts = 5; // per-article

	function about() {
		return array(1.0,
			"Automatically cache Starred articles' images and HTML5 video files",
			"fox",
			true);
	}

	/**
	 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
	 */
	function csrf_ignore($method) {
		return false;
	}

	/**
	 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
	 */
	function before($method) {
		return true;
	}

	function after() {
		return true;
	}

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

		$this->cache_dir = CACHE_DIR . "/starred-images/";

		if (!is_dir($this->cache_dir)) {
			mkdir($this->cache_dir);
		}

		if (is_dir($this->cache_dir)) {

			if (!is_writable($this->cache_dir))
				chmod($this->cache_dir, 0777);

			if (is_writable($this->cache_dir)) {
				$host->add_hook($host::HOOK_UPDATE_TASK, $this);
				$host->add_hook($host::HOOK_HOUSE_KEEPING, $this);
				$host->add_hook($host::HOOK_SANITIZE, $this);
				$host->add_handler("public", "cache_starred_images_getimage", $this);

			} else {
				user_error("Starred cache directory is not writable.", E_USER_WARNING);
			}

		} else {
			user_error("Unable to create starred cache directory.", E_USER_WARNING);
		}
	}

	function cache_starred_images_getimage() {
		ob_end_clean();

		$hash = basename($_REQUEST["hash"]);

		if ($hash) {

			$filename = $this->cache_dir . "/" . basename($hash);

			if (file_exists($filename)) {
				header("Content-Disposition: attachment; filename=\"$hash\"");

				send_local_file($filename);
			} else {
				header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
				echo "File not found.";
			}
		}
	}

	/**
	 * @SuppressWarnings(PHPMD.UnusedLocalVariable)
	 */
	function hook_house_keeping() {
		$files = glob($this->cache_dir . "/*.{png,mp4,status}", GLOB_BRACE);

		$last_article_id = 0;
		$article_exists = 1;

		foreach ($files as $file) {
			list ($article_id, $hash) = explode("-", basename($file));

			if ($article_id != $last_article_id) {
				$last_article_id = $article_id;

				$sth = $this->pdo->prepare("SELECT id FROM ttrss_entries WHERE id = ?");
				$sth->execute([$article_id]);

				$article_exists = $sth->fetch();
			}

			if (!$article_exists) {
				unlink($file);
			}
		}
	}

	/**
	 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
	 */
	function hook_sanitize($doc, $site_url, $allowed_elements, $disallowed_attributes, $article_id) {
		$xpath = new DOMXpath($doc);

		if ($article_id) {
			$entries = $xpath->query('(//img[@src])|(//video/source[@src])');

			foreach ($entries as $entry) {
				if ($entry->hasAttribute('src')) {
					$src = rewrite_relative_url($site_url, $entry->getAttribute('src'));

					$extension = $entry->tagName == 'source' ? '.mp4' : '.png';
					$local_filename = $this->cache_dir . $article_id . "-" . sha1($src) . $extension;

					if (file_exists($local_filename)) {
						$entry->setAttribute("src", get_self_url_prefix() .
							"/public.php?op=cache_starred_images_getimage&method=image&hash=" .
							$article_id . "-" . sha1($src) . $extension);
					}

				}
			}
		}

		return $doc;
	}

	function hook_update_task() {
		$res = $this->pdo->query("SELECT content, ttrss_user_entries.owner_uid, link, site_url, ttrss_entries.id, plugin_data
			FROM ttrss_entries, ttrss_user_entries LEFT JOIN ttrss_feeds ON
				(ttrss_user_entries.feed_id = ttrss_feeds.id)
			WHERE ref_id = ttrss_entries.id AND
				marked = true AND
				(UPPER(content) LIKE '%<IMG%' OR UPPER(content) LIKE '%<VIDEO%') AND
				site_url != '' AND
				plugin_data NOT LIKE '%starred_cache_images%'
			ORDER BY ".sql_random_function()." LIMIT 100");

		$usth = $this->pdo->prepare("UPDATE ttrss_entries SET plugin_data = ? WHERE id = ?");

		while ($line = $res->fetch()) {
			if ($line["site_url"]) {
				$success = $this->cache_article_images($line["content"], $line["site_url"], $line["owner_uid"], $line["id"]);

				if ($success) {
					$plugin_data = "starred_cache_images,${line['owner_uid']}:" . $line["plugin_data"];

					$usth->execute([$plugin_data, $line['id']]);
				}
			}
		}
	}

	/**
	 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
	 */
	function cache_article_images($content, $site_url, $owner_uid, $article_id) {
		libxml_use_internal_errors(true);

		$status_filename = $this->cache_dir . $article_id . "-" . sha1($site_url) . ".status";

		//_debug("status: $status_filename"); return;

        if (file_exists($status_filename))
            $status = json_decode(file_get_contents($status_filename), true);
        else
            $status = [];

        $status["attempt"] += 1;

        // only allow several download attempts for article
        if ($status["attempt"] > $this->max_cache_attempts) {
            _debug("too many attempts for $site_url");
            return;
        }

        if (!file_put_contents($status_filename, json_encode($status))) {
            user_error("unable to write status file: $status_filename", E_USER_WARNING);
            return;
        }

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

		$doc = new DOMDocument();
		$doc->loadHTML($charset_hack . $content);
		$xpath = new DOMXPath($doc);

		$entries = $xpath->query('(//img[@src])|(//video/source[@src])');

		$success = false;
		$has_images = false;

		foreach ($entries as $entry) {

			if ($entry->hasAttribute('src') && strpos($entry->getAttribute('src'), "data:") !== 0) {

				$has_images = true;
				$src = rewrite_relative_url($site_url, $entry->getAttribute('src'));

				$extension = $entry->tagName == 'source' ? '.mp4' : '.png';

				$local_filename = $this->cache_dir . $article_id . "-" . sha1($src) . $extension;

				//_debug("cache_images: downloading: $src to $local_filename");

				if (!file_exists($local_filename)) {
					$file_content = fetch_file_contents(["url" => $src, "max_size" => MAX_CACHE_FILE_SIZE]);

					if ($file_content) {
                        if (strlen($file_content) > MIN_CACHE_FILE_SIZE) {
                            file_put_contents($local_filename, $file_content);
                        }

						$success = true;
					}
				} else {
					$success = true;
				}
			}
		}

		return $success || !$has_images;
	}

	function api_version() {
		return 2;
	}
}