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