xref: /plugin/mediathumbnails/syntax.php (revision 29e328d90cd5f1ecb4112d5013d40185c50429fa)
1<?php
2/**
3 * DokuWiki Plugin mediathumbnails (Syntax Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Thomas Schäfer <thomas.schaefer@itschert.net>
7 */
8
9// must be run within Dokuwiki
10if (!defined('DOKU_INC')) {
11    die();
12}
13
14class syntax_plugin_mediathumbnails extends DokuWiki_Syntax_Plugin {
15
16	/**
17     * @return string Syntax mode type
18     */
19    public function getType()
20    {
21        return 'substition';
22    }
23
24    /**
25     * @return string Paragraph type
26     */
27    public function getPType()
28    {
29        return 'normal';
30    }
31
32    /**
33     * @return int Sort order - Low numbers go before high numbers
34     */
35    public function getSort()
36    {
37        return 1;
38    }
39
40    /**
41     * Connect lookup pattern to lexer.
42     *
43     * @param string $mode Parser mode
44     */
45    public function connectTo($mode)
46    {
47		$this->Lexer->addSpecialPattern("{{thumbnail>.+?}}", $mode, substr(get_class($this), 7));
48	}
49
50    /**
51     * Handle matches of the mediathumbnails syntax
52     *
53     * @param string       $match   The match of the syntax
54     * @param int          $state   The state of the handler
55     * @param int          $pos     The position in the document
56     * @param Doku_Handler $handler The handler
57     *
58     * @return array Data for the renderer
59     */
60    public function handle($match, $state, $pos, Doku_Handler $handler)
61    {
62		// Locate the given media file and check if it can be opened as zip
63		$mediapath_file = substr($match, 12, -2); //strip markup
64
65		$thumb = new thumbnail($mediapath_file,$this);
66		if ($thumb->create()) {
67			return array($mediapath_file,$thumb->getMediapath());
68		}
69
70		return array($mediapath_file);
71    }
72
73    /**
74     * Render xhtml output or metadata
75     *
76     * @param string        $mode     Renderer mode (supported modes: xhtml)
77     * @param Doku_Renderer $renderer The renderer
78     * @param array         $data     The data from the handler() function
79     *
80     * @return bool If rendering was successful.
81     */
82    public function render($mode, Doku_Renderer $renderer, $data)
83    {
84		list ($mediapath_file, $mediapath_thumbnail) = $data;
85
86        if ($mode == 'xhtml') {
87
88			// check if a thumbnail file was found
89			if (!$mediapath_thumbnail) {
90				if ($this->getConf('show_missing_thumb_error')) {
91					$renderer->doc .= trim($this->getConf('no_thumb_error_message')) . " " . $mediapath_file;
92					return true;
93				} else {
94					return false;
95				}
96			}
97
98			$src = ml($mediapath_thumbnail,array());
99
100			$i             = array();
101			$i['width']    = $this->getConf('thumb_width');
102			//$i['height']   = '';
103			$i['title']      = $mediapath_file;
104			$i['class']    = 'tn';
105			$iatt = buildAttributes($i);
106
107			$renderer->doc .= 	($this->getConf('link_to_media_file') ? '<a href="/lib/exe/fetch.php?media=' . $mediapath_file . '">' : '') .
108								'<img src="'.$src.'" '.$iatt.' />' .
109								($this->getConf('link_to_media_file') ? '</a>' : '');
110            return true;
111
112        } elseif ($mode == 'odt') {
113
114			// TODO: yet to implement
115			$renderer->cdata("");
116			return true;
117
118		}
119
120        return false;
121    }
122}
123
124function getFileSuffix(string $file) {
125	return substr(strrchr($file,'.'),1);
126}
127
128class thumbnail {
129
130	private $source_filepath;
131	private $source_mediapath;
132	private ?thumb_engine $thumb_engine = null;
133	private $formats;
134
135	public function __construct(string $source_filepath, DokuWiki_Syntax_Plugin $plugin, bool $ismediapath = true) {
136
137		if ($ismediapath) {
138			$this->source_mediapath = $source_filepath;
139			$this->source_filepath = mediaFN($source_filepath);
140		} else {
141			$this->source_mediapath = false;
142			$this->source_filepath = $source_filepath;
143		}
144
145		// determine file formats supported by ImageMagick
146		$this->formats = \Imagick::queryformats();
147
148		// Now attach the correct thumb_engine for the file type of the source file
149		//TODO: check for extension "fileinfo", then check for MIME type: if (mime_content_type($filepath_local_file) == "application/pdf") {
150		$sourceFileSuffix = getFileSuffix($this->source_filepath);
151		if ($sourceFileSuffix == "pdf") {
152			// file suffix is pdf, so assume it's a PDF file
153			$this->thumb_engine = new thumb_pdf_engine($this,$plugin->getConf('thumb_width'));
154		} else if (in_array(strtoupper($sourceFileSuffix), $this->formats)) {
155			// file suffix is in support list of ImageMagick
156			$this->thumb_engine = new thumb_img_engine($this,$plugin->getConf('thumb_width'));
157		} else {
158			// last resort: check if the source file is a ZIP file and look for thumbnails, therein
159			$this->thumb_engine = new thumb_zip_engine($this,$plugin->getConf('thumb_width'),$plugin->getConf('thumb_paths'));
160		}
161	}
162
163	public function create() {
164		if (!$this->thumb_engine) {
165			return false;
166		}
167
168		return $this->thumb_engine->act();
169	}
170
171	public function getSourceFilepath() {
172		return $this->source_filepath;
173	}
174
175	protected function getFilename() {
176
177		return basename($this->source_filepath) . ".thumb.".$this->thumb_engine->getFileSuffix();
178	}
179
180	public function getFilepath() {
181		return dirname($this->source_filepath) . DIRECTORY_SEPARATOR . $this->getFilename();
182	}
183
184	public function getMediapath() {
185		if ($this->source_mediapath !== false) {
186			return substr($this->source_mediapath,0,strrpos($this->source_mediapath,':')) . ":" . $this->getFilename();
187		} else {
188			return false;
189		}
190	}
191
192	public function getTimestamp() {
193		return file_exists($this->getFilepath()) ? filemtime($this->getFilepath()) : false;
194	}
195}
196
197abstract class thumb_engine {
198
199	private ?thumbnail $thumbnail = null;
200	private int $width;
201
202	public function __construct(thumbnail $thumbnail, int $width) {
203		$this->thumbnail = $thumbnail;
204		$this->width = $width;
205	}
206
207	protected function getSourceFilepath() {
208		return $this->thumbnail->getSourceFilepath();
209	}
210
211	protected function getTargetFilepath() {
212		return $this->thumbnail->getFilepath();
213	}
214
215	protected function getTargetWidth() {
216		return $this->width;
217	}
218
219	public function act() {
220		if ($this->act_internal()) {
221			// Set timestamp to the source file's timestamp (this is used to check in later passes if the file already exists in the correct version).
222			if (filemtime($this->getSourceFilepath()) !== filemtime($this->getTargetFilepath())) {
223				touch($this->getTargetFilepath(), filemtime($this->getSourceFilepath()));
224			}
225			return true;
226		}
227		return false;
228	}
229
230	// Checks if a thumbnail file for the current file version has already been created
231	protected function thumb_needs_update() {
232		return !file_exists($this->getTargetFilepath()) || filemtime($this->getTargetFilepath()) !== filemtime($this->getSourceFilepath());
233	}
234
235	public abstract function act_internal();
236
237	public abstract function getFileSuffix();
238}
239
240class thumb_pdf_engine extends thumb_engine {
241
242	public function getFileSuffix() {
243		return "jpg";
244	}
245
246	public function act_internal() {
247		if ($this->thumb_needs_update()) {
248			$im = new imagick( $this->getSourceFilepath()."[0]" );
249			$im->setImageColorspace(255);
250			$im->setResolution(300, 300);
251			$im->setCompressionQuality(95);
252			$im->setImageFormat('jpeg');
253			//$im->resizeImage(substr($this->getConf('thumb_width'),-2),0,imagick::FILTER_LANCZOS,0.9);
254			$im->writeImage($this->getTargetFilepath());
255			$im->clear();
256			$im->destroy();
257
258			return true;
259		} else {
260			return true;
261		}
262	}
263}
264
265class thumb_img_engine extends thumb_engine {
266
267	public function getFileSuffix() {
268		return getFileSuffix($this->getSourceFilepath());
269	}
270
271	public function act_internal() {
272		if ($this->thumb_needs_update()) {
273			$im = new imagick( $this->getSourceFilepath() );
274			//TODO: consider height?
275			$im->thumbnailImage($this->getTargetWidth(),$this->getTargetWidth(),true,false);
276			$im->writeImage($this->getTargetFilepath());
277			$im->clear();
278			$im->destroy();
279
280			return true;
281		} else {
282			return true;
283		}
284	}
285}
286
287class thumb_zip_engine extends thumb_engine {
288
289	private array $thumb_paths;
290	private $file_suffix = "";
291
292	public function __construct(thumbnail $thumbnail, int $width, array $thumb_paths) {
293		parent::__construct($thumbnail,$width);
294		$this->thumb_paths = $thumb_paths;
295	}
296
297	public function getFileSuffix() {
298		return $this->file_suffix;
299	}
300
301	public function act_internal() {
302
303		$zip = new ZipArchive;
304		if ($zip->open($this->getSourceFilepath()) !== true) {
305			// file is no zip or cannot be opened
306			return false;
307		}
308
309		// The media file exists and acts as a zip file!
310
311		// Check all possible paths (configured in configuration key 'thumb_paths') if there is a file available
312		foreach($this->thumb_paths as $thumbnail_path) {
313			$this->file_suffix = substr(strrchr($thumbnail_path,'.'),1);
314
315			if ($zip->locateName($thumbnail_path) !== false) {
316
317				if (!$this->thumb_needs_update()) {
318					return true;
319				}
320
321				// Get the thumbnail file!
322				$fp = $zip->getStream($thumbnail_path);
323				if(!$fp) {
324					return false;
325				}
326
327				$thumbnaildata = '';
328				while (!feof($fp)) {
329					$thumbnaildata .= fread($fp, 8192);
330				}
331
332				fclose($fp);
333
334				// Write thumbnail file to media folder
335				file_put_contents($this->getTargetFilepath(), $thumbnaildata);
336
337				return true;
338			}
339		}
340
341		return true;
342	}
343}