xref: /plugin/mediathumbnails/syntax.php (revision 4d8fafba2029f1800935e3aa2826389ac0cee9a0)
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		$filepath_local_file = mediaFN($mediapath_file);
65		$timestamp_local_file = file_exists($filepath_local_file) ? filemtime($filepath_local_file) : false;
66
67		//TODO: check for extension "fileinfo", then check for MIME type: if (mime_content_type($filepath_local_file) == "application/pdf") {
68		if (substr($mediapath_file,-4) == ".pdf") {
69			//$extended_filename = basename($filepath_local_file) . ".".$this->getConf('thumb_width').".jpg";
70			$extended_filename = basename($filepath_local_file) . ".thumb.jpg";
71			$filepath_thumbnail = dirname($filepath_local_file) . DIRECTORY_SEPARATOR . $extended_filename;
72			$mediapath_thumbnail = substr($mediapath_file,0,strrpos($mediapath_file,':')) . ":" . $extended_filename;
73
74			$im = new imagick( $filepath_local_file."[0]" );
75			$im->setImageColorspace(255);
76			$im->setResolution(300, 300);
77			$im->setCompressionQuality(95);
78			$im->setImageFormat('jpeg');
79			//$im->resizeImage($this->getConf('thumb_width')*3,0,imagick::FILTER_LANCZOS ,1);
80			$im->writeImage($filepath_thumbnail);
81			$im->clear();
82			$im->destroy();
83			return array($mediapath_file,$mediapath_thumbnail);
84		}
85
86		$zip = new ZipArchive;
87		if ($zip->open($filepath_local_file) !== TRUE) {
88			// media file does not exist
89			return array($mediapath_file);
90		}
91
92		// The media file exists and acts as a zip file!
93
94		// Check all possible paths (configured in configuration key 'thumb_paths') if there is a file available
95		$thumb_paths_to_investigate = $this->getConf('thumb_paths');
96
97		foreach($thumb_paths_to_investigate as $thumbnail_path) {
98			$thumbnail_ending = strrchr($thumbnail_path,'.');
99
100			if ($zip->locateName($thumbnail_path) !== false) {
101
102				// The thumbnail file exists, so prepare more information, now!
103				$extended_filename = basename($filepath_local_file) . ".thumb" . $thumbnail_ending;
104				$filepath_thumbnail = dirname($filepath_local_file) . DIRECTORY_SEPARATOR . $extended_filename;
105				$mediapath_thumbnail = substr($mediapath_file,0,strrpos($mediapath_file,':')) . ":" . $extended_filename;
106
107				if (file_exists($filepath_thumbnail) && filemtime($filepath_thumbnail) == $timestamp_local_file) {
108					// A thumbnail file for the current file version has already been created, don't extract it again, but give the renderer all needed information!
109					return array($mediapath_file, $mediapath_thumbnail);
110				}
111
112				// Get the thumbnail file!
113				$fp = $zip->getStream($thumbnail_path);
114				if(!$fp) {
115					return array();
116				}
117
118				$thumbnaildata = '';
119				while (!feof($fp)) {
120					$thumbnaildata .= fread($fp, 8192);
121				}
122
123				fclose($fp);
124
125				// Write thumbnail file to media folder
126				file_put_contents($filepath_thumbnail, $thumbnaildata);
127
128				// Set timestamp to the media file's timestamp (this is used to check in later passes if the file already exists in the correct version).
129				touch($filepath_thumbnail, $timestamp_local_file);
130
131				// Give media path to renderer
132				return array($mediapath_file, $mediapath_thumbnail);
133			}
134		}
135
136		return array($mediapath_file);
137    }
138
139    /**
140     * Render xhtml output or metadata
141     *
142     * @param string        $mode     Renderer mode (supported modes: xhtml)
143     * @param Doku_Renderer $renderer The renderer
144     * @param array         $data     The data from the handler() function
145     *
146     * @return bool If rendering was successful.
147     */
148    public function render($mode, Doku_Renderer $renderer, $data)
149    {
150		list ($mediapath_file, $mediapath_thumbnail) = $data;
151
152        if ($mode == 'xhtml') {
153
154			// check if a thumbnail file was found
155			if (!$mediapath_thumbnail) {
156				if ($this->getConf('show_missing_thumb_error')) {
157					$renderer->doc .= trim($this->getConf('no_thumb_error_message')) . " " . $mediapath_file;
158					return true;
159				} else {
160					return false;
161				}
162			}
163
164			$src = ml($mediapath_thumbnail,array());
165
166			$i             = array();
167			$i['width']    = $this->getConf('thumb_width');
168			//$i['height']   = '';
169			$i['title']      = $mediapath_file;
170			$i['class']    = 'tn';
171			$iatt = buildAttributes($i);
172
173			$renderer->doc .= 	($this->getConf('link_to_media_file') ? '<a href="/lib/exe/fetch.php?media=' . $mediapath_file . '">' : '') .
174								'<img src="'.$src.'" '.$iatt.' />' .
175								($this->getConf('link_to_media_file') ? '</a>' : '');
176            return true;
177
178        } elseif ($mode == 'odt') {
179
180			// TODO: yet to implement
181			$renderer->cdata("");
182			return true;
183
184		}
185
186        return false;
187    }
188}
189
190