]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/FileInfo.php
Consistent messages for missing required arguments
[SourceForge/phpwiki.git] / lib / plugin / FileInfo.php
1 <?php // -*-php-*-
2 // $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 along
20  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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  *   <<FileInfo file=Upload:setup.exe display=version,date >>
30  *   <<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         }
63         if (!$display) {
64             return $this->error(sprintf(_("A required argument '%s' is missing."), 'display'));
65         }
66         if (string_starts_with($file, "Upload:")) {
67             $file = preg_replace("/^Upload:(.*)$/", getUploadFilePath()."\\1", $file);
68             $is_Upload = 1;
69         }
70         $dir = getcwd();
71         if (defined('PHPWIKI_DIR')) {
72             chdir(PHPWIKI_DIR);
73         }
74         if (!file_exists($file)) {
75             if ($quiet) {
76                 return HTML::raw('');
77             } else {
78                 return $this->error(sprintf(_("File '%s' not found."), $file));
79             }
80         }
81         // sanify $file name
82         $realfile = realpath($file);
83         // Hmm, allow ADMIN to check a local file? Only if its locked
84         if (string_starts_with($realfile, realpath(getUploadDataPath()))) {
85             $isuploaded = 1;
86         } else {
87             $page = $dbi->getPage($basepage);
88             $user = $request->getUser();
89             if ($page->getOwner() != ADMIN_USER or !$page->get('locked')) {
90                 // For convenience we warn the admin
91                 if ($quiet and $user->isAdmin())
92                     return HTML::span(array('title' => _("Output suppressed. FileInfoPlugin with local files require a locked page.")),
93                                       HTML::em(_("page not locked")));
94                 else
95                     return $this->error("Invalid path \"$file\". Only ADMIN can allow local paths, and the page must be locked.");
96             }
97         }
98         $s = array();
99         $modes = explode(",", $display);
100         foreach ($modes as $mode) {
101             switch ($mode) {
102             case 'version':  $s[] = $this->exeversion($file); break;
103             case 'size':     $s[] = filesize($file); break;
104             case 'phonysize':$s[] = $this->phonysize(filesize($file)); break;
105             case 'date':     $s[] = strftime("%x %X", filemtime($file)); break;
106             case 'mtime':    $s[] = filemtime($file); break;
107             case 'owner':    $o = posix_getpwuid(fileowner($file)); $s[] = $o['name']; break;
108             case 'group':    $o = posix_getgrgid(filegroup($file)); $s[] = $o['name']; break;
109             case 'name':     $s[] = basename($file); break;
110             case 'path':     $s[] = $file; break;
111             case 'dirname':  $s[] = dirname($file); break;
112             case 'magic':    $s[] = $this->magic($file); break;
113             case 'mime-typ': $s[] = $this->mime_type($file); break;
114             case 'link':
115                 if ($is_Upload) {
116                     $s[] = " [".$args['file'] . "]";
117                 } elseif ($isuploaded) {
118                     // will fail with user uploads
119                     $s[] = " [Upload:".basename($file)."]";
120                 } else {
121                     $s[] = " [".basename($file)."] ";
122                 }
123                 break;
124             default:
125                 if (!$quiet) {
126                     return $this->error(sprintf(_("Unsupported argument: %s=%s"), 'display', $mode));
127                 } else {
128                     return HTML::raw('');
129                 }
130                 break;
131             }
132         }
133         chdir($dir);
134         if (!$format) {
135             $format = '';
136             foreach ($s as $x) { $format .= " %s"; }
137         }
138         array_unshift($s, $format);
139         // $x, array($i,$j) => sprintf($x, $i, $j)
140         $result = call_user_func_array("sprintf", $s);
141         if (in_array('link', $modes)) {
142             require_once("lib/InlineParser.php");
143             return TransformInline($result, 2, $basepage);
144         } else {
145             return HTML::raw($result);
146         }
147     }
148
149     function magic($file) {
150         if (function_exists('finfo_file') or loadPhpExtension('fileinfo')) {
151             // Valid finfo_open (i.e. libmagic) options:
152             // FILEINFO_NONE | FILEINFO_SYMLINK | FILEINFO_MIME | FILEINFO_COMPRESS | FILEINFO_DEVICES |
153             // FILEINFO_CONTINUE | FILEINFO_PRESERVE_ATIME | FILEINFO_RAW
154             $f = finfo_open(/*FILEINFO_MIME*/);
155             $result = finfo_file(realpath($file));
156             finfo_close($res);
157             return $result;
158         }
159         return '';
160     }
161
162     function mime_type($file) {
163         return '';
164     }
165
166     function _formatsize ($n, $factor, $suffix = '') {
167         if ($n > $factor) {
168             $b = $n / $factor;
169             $n -= floor($factor * $b);
170             return number_format($b, $n ? 3 : 0). $suffix;
171         }
172     }
173     function phonysize ($a) {
174         $factor = 1024 * 1024 * 1000;
175         if ($a > $factor)
176             return $this->_formatsize($a, $factor, ' GB');
177         $factor = 1024 * 1000;
178         if ($a > $factor)
179             return $this->_formatsize($a, $factor, ' MB');
180         $factor = 1024;
181         if ($a > $factor)
182             return $this->_formatsize($a, $factor, ' KB');
183         if ($a > 1)
184             return $this->_formatsize($a, 1, ' byte');
185         else
186             return $a;
187     }
188
189     function exeversion($file) {
190             if (!isWindows()) return "?";
191         if (class_exists('ffi') or loadPhpExtension('ffi'))
192             return $this->exeversion_ffi($file);
193         if (function_exists('res_list_type') or loadPhpExtension('win32std'))
194             return $this->exeversion_resopen($file);
195         return exeversion_showver($file);
196         return '';
197     }
198
199     // http://www.codeproject.com/dll/showver.asp
200     function exeversion_showver($file) {
201         $path = realpath($file);
202         $result = `showver $path`;
203             return "?";
204     }
205
206     function exeversion_ffi($file) {
207         if (!DEBUG)
208             return "?"; // not yet stable
209
210         if (function_exists('ffi') or loadPhpExtension('ffi')) {
211             $win32_idl = "
212 struct VS_FIXEDFILEINFO {
213         DWORD dwSignature;
214         DWORD dwStrucVersion;
215         DWORD dwFileVersionMS;
216         DWORD dwFileVersionLS;
217         DWORD dwProductVersionMS;
218         DWORD dwProductVersionLS;
219         DWORD dwFileFlagsMask;
220         DWORD dwFileFlags;
221         DWORD dwFileOS;
222         DWORD dwFileType;
223         DWORD dwFileSubtype;
224         DWORD dwFileDateMS;
225         DWORD dwFileDateLS;
226 };
227 struct VS_VERSIONINFO { struct VS_VERSIONINFO
228   WORD  wLength;
229   WORD  wValueLength;
230   WORD  wType;
231   WCHAR szKey[1];
232   WORD  Padding1[1];
233   VS_FIXEDFILEINFO Value;
234   WORD  Padding2[1];
235   WORD  Children[1];
236 };
237 [lib='kernel32.dll'] DWORD GetFileVersionInfoSizeA(char *szFileName, DWORD *dwVerHnd);
238 [lib='kernel32.dll'] int GetFileVersionInfoA(char *sfnFile, DWORD dummy, DWORD size, struct VS_VERSIONINFO *pVer);
239 ";
240             $ffi = new ffi($win32_idl);
241             $dummy = 0; // &DWORD
242              $size = $ffi->GetFileVersionInfoSizeA($file, $dummy);
243             //$pVer = str_repeat($size+1);
244             $pVer = new ffi_struct($ffi, "VS_VERSIONINFO");
245             if ($ffi->GetFileVersionInfoA($file, 0, $size, $pVer)
246                 and $pVer->wValueLength) {
247                 // analyze the VS_FIXEDFILEINFO(Value);
248                 // $pValue = new ffi_struct($ffi, "VS_FIXEDFILEINFO");
249                 $pValue =& $pVer->Value;
250                 return sprintf("%d.%d.%d.%d",
251                                $pValue->dwFileVersionMS >> 16,
252                                $pValue->dwFileVersionMS & 0xFFFF,
253                                $pValue->dwFileVersionLS >> 16,
254                                $pValue->dwFileVersionLS & 0xFFFF);
255             }
256         }
257     }
258
259     // Read "RT_VERSION/VERSIONINFO" exe/dll resource info for MSWin32 binaries
260     // The "win32std" extension is not ready yet to pass back a VERSIONINFO struct
261     function exeversion_resopen($file) {
262         if (function_exists('res_list_type') or loadPhpExtension('win32std')) {
263             // See http://msdn.microsoft.com/workshop/networking/predefined/res.asp
264             $v = file_get_contents('res://'.realpath($file).urlencode('/RT_VERSION/#1'));
265             if ($v) {
266                     // This is really a binary VERSIONINFO block, with lots of
267                     // nul bytes (widechar) which cannot be transported as string.
268                     return "$v";
269             }
270             else {
271                 $h = res_open(realpath($file));
272                 $v = res_get($h, 'RT_VERSION', 'FileVersion');
273                 res_close($h);
274                 if ($v) return $v;
275
276                 $h = res_open(realpath($file));
277                 $v = res_get($h, '#1', 'RT_VERSION', 1);
278                 res_close($h);
279                 if ($v) return $v;
280             }
281
282             /* The version consists of two 32-bit integers, defined by four 16-bit integers.
283                For example, "FILEVERSION 3,10,0,61" is translated into two doublewords:
284                0x0003000a and 0x0000003d, in that order. */
285 /*
286         $h = res_open(realpath($file));
287
288         echo "Res list of '$file': \n";
289         $list= res_list_type($h, true);
290         if( $list===FALSE ) err( "Can't list type" );
291
292         for( $i= 0; $i<count($list); $i++ ) {
293                 echo $list[$i]."\n";
294                 $res= res_list($h, $list[$i]);
295                 for( $j= 0; $j<count($res); $j++ ) {
296                         echo "\t".$res[$j]."\n";
297                 }
298         }
299         echo "Res get: ".res_get( $h, 'A_TYPE', 'A_RC_NAME' )."\n\n";
300         res_close( $h );
301 */
302             if ($v)
303                 return "$v";
304             else
305                 return "";
306         } else {
307             return "";
308         }
309
310     }
311 };
312
313 // Local Variables:
314 // mode: php
315 // tab-width: 8
316 // c-basic-offset: 4
317 // c-hanging-comment-ender-p: nil
318 // indent-tabs-mode: nil
319 // End:
320 ?>