]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/FileInfo.php
rcs_id no longer makes sense with Subversion global version number
[SourceForge/phpwiki.git] / lib / plugin / FileInfo.php
1 <?php // -*-php-*-
2 // rcs_id('$Id$');
3 /*
4  * Copyright 2005,2007 $ThePhpWikiProgrammingTeam
5  * Copyright 2008-2009 Marc-Etienne Vargenau, Alcatel-Lucent
6  *
7  * This file is part of PhpWiki.
8  *
9  * PhpWiki is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * PhpWiki is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with PhpWiki; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 /**
25  * This plugin displays the version, date, size, perms of an uploaded file.
26  * Only files relative and below to the uploads path can be handled.
27  *
28  * Usage:
29  *   <?plugin FileInfo file=Upload:setup.exe display=version,date ?>
30  *   <?plugin FileInfo file=Upload:setup.exe display=name,version,date
31  *                     format="%s (version: %s, date: %s)" ?>
32  *
33  * @author: ReiniUrban
34  */
35
36 class WikiPlugin_FileInfo
37 extends WikiPlugin
38 {
39     function getName () {
40         return _("FileInfo");
41     }
42
43     function getDescription () {
44         return _("Display file information like version, size, date... of uploaded files.");
45     }
46
47     function getDefaultArguments() {
48         return array(
49                      'file'      => false, // relative path from PHPWIKI_DIR. (required)
50                      'display'   => false, // version,phonysize,size,date,mtime,owner,name,path,dirname,link.  (required)
51                      'format'    => false, // printf format string with %s only, all display modes
52                      'quiet'     => false  // print no error if file not found
53                                                 // from above vars return strings (optional)
54                     );
55     }
56
57     function run($dbi, $argstr, &$request, $basepage) {
58             $args = $this->getArgs($argstr, $request);
59         extract($args);
60         if (!$file)
61             return $this->error(sprintf(_("A required argument '%s' is missing."), 'file'));
62         if (!$display)
63             return $this->error(sprintf(_("A required argument '%s' is missing."), 'display'));
64         if (string_starts_with($file, "Upload:")) {
65             $file = preg_replace("/^Upload:(.*)$/", getUploadFilePath()."\\1", $file);
66             $is_Upload = 1;
67         }
68         $dir = getcwd();
69         if (defined('PHPWIKI_DIR')) {
70             chdir(PHPWIKI_DIR);
71         }
72         if (!file_exists($file)) {
73             if ($quiet) {
74                 return HTML::raw('');
75             } else {
76                 return $this->error(sprintf(_("File '%s' not found."), $file));
77             }
78         }
79         // sanify $file name
80         $realfile = realpath($file);
81         // Hmm, allow ADMIN to check a local file? Only if its locked
82         if (string_starts_with($realfile, realpath(getUploadDataPath()))) {
83             $isuploaded = 1;
84         } else {
85             $page = $dbi->getPage($basepage);
86             $user = $request->getUser();
87             if ($page->getOwner() != ADMIN_USER or !$page->get('locked')) {
88                 // For convenience we warn the admin
89                 if ($quiet and $user->isAdmin())
90                     return HTML::span(array('title' => _("Output suppressed. FileInfoPlugin with local files require a locked page.")),
91                                       HTML::em(_("page not locked")));
92                 else
93                     return $this->error("Invalid path \"$file\". Only ADMIN can allow local paths, and the page must be locked.");
94             }
95         }
96         $s = array();
97         $modes = explode(",", $display);
98         foreach ($modes as $mode) {
99             switch ($mode) {
100             case 'version':  $s[] = $this->exeversion($file); break;
101             case 'size':     $s[] = filesize($file); break;
102             case 'phonysize':$s[] = $this->phonysize(filesize($file)); break;
103             case 'date':     $s[] = strftime("%x %X", filemtime($file)); break;
104             case 'mtime':    $s[] = filemtime($file); break;
105             case 'owner':    $o = posix_getpwuid(fileowner($file)); $s[] = $o['name']; break;
106             case 'group':    $o = posix_getgrgid(filegroup($file)); $s[] = $o['name']; break;
107             case 'name':     $s[] = basename($file); break;
108             case 'path':     $s[] = $file; break;
109             case 'dirname':  $s[] = dirname($file); break;
110             case 'magic':    $s[] = $this->magic($file); break;
111             case 'mime-typ': $s[] = $this->mime_type($file); break;
112             case 'link':
113                 if ($is_Upload) {
114                     $s[] = " [".$args['file'] . "]";
115                 } elseif ($isuploaded) {
116                     // will fail with user uploads
117                     $s[] = " [Upload:".basename($file)."]";
118                 } else {
119                     $s[] = " [".basename($file)."] ";
120                 }
121                 break;
122             default:
123                 if (!$quiet) {
124                     return $this->error(sprintf(_("Unsupported argument: %s=%s"), 'display', $mode));
125                 } else {
126                     return HTML::raw('');
127                 }
128                 break;
129             }
130         }
131         chdir($dir);
132         if (!$format) {
133             $format = '';
134             foreach ($s as $x) { $format .= " %s"; }
135         }
136         array_unshift($s, $format);
137         // $x, array($i,$j) => sprintf($x, $i, $j)
138         $result = call_user_func_array("sprintf", $s);
139         if (in_array('link', $modes)) {
140             require_once("lib/InlineParser.php");
141             return TransformInline($result, 2, $basepage);
142         } else {
143             return HTML::raw($result);
144         }
145     }
146
147     function magic($file) {
148         if (function_exists('finfo_file') or loadPhpExtension('fileinfo')) {
149             // Valid finfo_open (i.e. libmagic) options:
150             // FILEINFO_NONE | FILEINFO_SYMLINK | FILEINFO_MIME | FILEINFO_COMPRESS | FILEINFO_DEVICES |
151             // FILEINFO_CONTINUE | FILEINFO_PRESERVE_ATIME | FILEINFO_RAW
152             $f = finfo_open(/*FILEINFO_MIME*/);
153             $result = finfo_file(realpath($file));
154             finfo_close($res);
155             return $result;
156         }
157         return '';
158     }
159
160     function mime_type($file) {
161         return '';
162     }
163
164     function _formatsize ($n, $factor, $suffix = '') {
165         if ($n > $factor) {
166             $b = $n / $factor;
167             $n -= floor($factor * $b);
168             return number_format($b, $n ? 3 : 0). $suffix;
169         }
170     }
171     function phonysize ($a) {
172         $factor = 1024 * 1024 * 1000;
173         if ($a > $factor)
174             return $this->_formatsize($a, $factor, ' GB');
175         $factor = 1024 * 1000;
176         if ($a > $factor)
177             return $this->_formatsize($a, $factor, ' MB');
178         $factor = 1024;
179         if ($a > $factor)
180             return $this->_formatsize($a, $factor, ' KB');
181         if ($a > 1)
182             return $this->_formatsize($a, 1, ' byte');
183         else
184             return $a;
185     }
186
187     function exeversion($file) {
188             if (!isWindows()) return "?";
189         if (class_exists('ffi') or loadPhpExtension('ffi'))
190             return $this->exeversion_ffi($file);
191         if (function_exists('res_list_type') or loadPhpExtension('win32std'))
192             return $this->exeversion_resopen($file);
193         return exeversion_showver($file);
194         return '';
195     }
196
197     // http://www.codeproject.com/dll/showver.asp
198     function exeversion_showver($file) {
199         $path = realpath($file);
200         $result = `showver $path`;
201             return "?";
202     }
203
204     function exeversion_ffi($file) {
205         if (!DEBUG)
206             return "?"; // not yet stable
207
208         if (function_exists('ffi') or loadPhpExtension('ffi')) {
209             $win32_idl = "
210 struct VS_FIXEDFILEINFO {
211         DWORD dwSignature;
212         DWORD dwStrucVersion;
213         DWORD dwFileVersionMS;
214         DWORD dwFileVersionLS;
215         DWORD dwProductVersionMS;
216         DWORD dwProductVersionLS;
217         DWORD dwFileFlagsMask;
218         DWORD dwFileFlags;
219         DWORD dwFileOS;
220         DWORD dwFileType;
221         DWORD dwFileSubtype;
222         DWORD dwFileDateMS;
223         DWORD dwFileDateLS;
224 };
225 struct VS_VERSIONINFO { struct VS_VERSIONINFO
226   WORD  wLength;
227   WORD  wValueLength;
228   WORD  wType;
229   WCHAR szKey[1];
230   WORD  Padding1[1];
231   VS_FIXEDFILEINFO Value;
232   WORD  Padding2[1];
233   WORD  Children[1];
234 };
235 [lib='kernel32.dll'] DWORD GetFileVersionInfoSizeA(char *szFileName, DWORD *dwVerHnd);
236 [lib='kernel32.dll'] int GetFileVersionInfoA(char *sfnFile, DWORD dummy, DWORD size, struct VS_VERSIONINFO *pVer);
237 ";
238             $ffi = new ffi($win32_idl);
239             $dummy = 0; // &DWORD
240              $size = $ffi->GetFileVersionInfoSizeA($file, $dummy);
241             //$pVer = str_repeat($size+1);
242             $pVer = new ffi_struct($ffi, "VS_VERSIONINFO");
243             if ($ffi->GetFileVersionInfoA($file, 0, $size, $pVer)
244                 and $pVer->wValueLength) {
245                 // analyze the VS_FIXEDFILEINFO(Value);
246                 // $pValue = new ffi_struct($ffi, "VS_FIXEDFILEINFO");
247                 $pValue =& $pVer->Value;
248                 return sprintf("%d.%d.%d.%d",
249                                $pValue->dwFileVersionMS >> 16,
250                                $pValue->dwFileVersionMS & 0xFFFF,
251                                $pValue->dwFileVersionLS >> 16,
252                                $pValue->dwFileVersionLS & 0xFFFF);
253             }
254         }
255     }
256
257     // Read "RT_VERSION/VERSIONINFO" exe/dll resource info for MSWin32 binaries
258     // The "win32std" extension is not ready yet to pass back a VERSIONINFO struct
259     function exeversion_resopen($file) {
260         if (function_exists('res_list_type') or loadPhpExtension('win32std')) {
261             // See http://msdn.microsoft.com/workshop/networking/predefined/res.asp
262             $v = file_get_contents('res://'.realpath($file).urlencode('/RT_VERSION/#1'));
263             if ($v) {
264                     // This is really a binary VERSIONINFO block, with lots of
265                     // nul bytes (widechar) which cannot be transported as string.
266                     return "$v";
267             }
268             else {
269                 $h = res_open(realpath($file));
270                 $v = res_get($h, 'RT_VERSION', 'FileVersion');
271                 res_close($h);
272                 if ($v) return $v;
273
274                 $h = res_open(realpath($file));
275                 $v = res_get($h, '#1', 'RT_VERSION', 1);
276                 res_close($h);
277                 if ($v) return $v;
278             }
279
280             /* The version consists of two 32-bit integers, defined by four 16-bit integers.
281                For example, "FILEVERSION 3,10,0,61" is translated into two doublewords:
282                0x0003000a and 0x0000003d, in that order. */
283 /*
284         $h = res_open(realpath($file));
285
286         echo "Res list of '$file': \n";
287         $list= res_list_type($h, true);
288         if( $list===FALSE ) err( "Can't list type" );
289
290         for( $i= 0; $i<count($list); $i++ ) {
291                 echo $list[$i]."\n";
292                 $res= res_list($h, $list[$i]);
293                 for( $j= 0; $j<count($res); $j++ ) {
294                         echo "\t".$res[$j]."\n";
295                 }
296         }
297         echo "Res get: ".res_get( $h, 'A_TYPE', 'A_RC_NAME' )."\n\n";
298         res_close( $h );
299 */
300             if ($v)
301                 return "$v";
302             else
303                 return "";
304         } else {
305             return "";
306         }
307
308     }
309 };
310
311 // For emacs users
312 // Local Variables:
313 // mode: php
314 // tab-width: 8
315 // c-basic-offset: 4
316 // c-hanging-comment-ender-p: nil
317 // indent-tabs-mode: nil
318 // End:
319 ?>