view e2gallerypro/e2upload/Backend/FileManager.php @ 12:2f433df9b961 judyates

[svn r13] Modified esgallery source to enable multiple paypal buttons; got the photo gallery operational and tested.
author rlm
date Mon, 12 Apr 2010 03:24:08 -0400
parents 3f6b44aa6b35
children
line wrap: on
line source
1 <?php
2 /*
3 Script: FileManager.php
4 MooTools FileManager - Backend for the FileManager Script
6 License:
7 MIT-style license.
9 Copyright:
10 Copyright (c) 2009 [Christoph Pojer](http://og5.net/christoph).
12 Dependencies:
13 - Upload.php
14 - Image.php
15 - getId3 Library
17 Options:
18 - directory: (string) The base directory to be used for the FileManger
19 - assetBasePath: (string) The path to all images and swf files
20 - dateFormat: (string, defaults to *j M Y - H:i*) The format in which dates should be displayed
21 - upload: (boolean, defaults to *false*) Whether to allow uploads or not
22 - destroy: (boolean, defaults to *false*) Whether to allow deletion of files or not
23 - maxUploadSize: (integeter, defaults to *3145728* bytes) The maximum file size for upload in bytes
24 - safe: (string, defaults to *true*) If true, disallows
25 - filter: (string) If specified, the mimetypes to be allowed (for display and upload).
26 Example: image/ allows all Image Mimetypes
27 */
29 require_once(FileManagerUtility::getPath().'/Upload.php');
30 require_once(FileManagerUtility::getPath().'/Image.php');
32 class FileManager {
34 private $path = null,
35 $length = null,
36 $basedir = null,
37 $basename = null,
38 $options,
39 $post,
40 $get;
42 public function __construct($options){
43 $this->options = array_merge(array(
44 'directory' => '../../Gallery',
45 'assetBasePath' => '../Assets',
46 'dateFormat' => 'j M Y - H:i',
47 'maxUploadSize' => 1024*1024*3,
48 'upload' => false,
49 'destroy' => false,
50 'safe' => true,
51 'filter' => null,
52 ), $options);
54 $this->basedir = realpath($this->options['directory']);
55 $this->basename = pathinfo($this->basedir, PATHINFO_BASENAME).'/';
56 $this->path = realpath($this->options['directory'].'/../');
57 $this->length = strlen($this->path);
59 header('Expires: Fri, 01 Jan 1990 00:00:00 GMT');
60 header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
62 $this->get = $_GET;
63 $this->post = $_POST;
64 }
66 public function fireEvent($event){
67 $event = $event ? 'on'.ucfirst($event) : null;
68 if(!$event || !method_exists($this, $event)) $event = 'onView';
70 $this->{$event}();
71 }
73 protected function onView(){
74 $dir = $this->getDir(!empty($this->post['directory']) ? $this->post['directory'] : null);
75 $files = ($files = glob($dir.'/*')) ? $files : array();
77 if($dir!=$this->basedir) array_unshift($files, $dir.'/..');
78 natcasesort($files);
79 foreach($files as $file){
80 $mime = $this->getMimeType($file);
81 if($this->options['filter'] && $mime!='text/directory' && !FileManagerUtility::startsWith($mime, $this->options['filter']))
82 continue;
84 $out[is_dir($file) ? 0 : 1][] = array(
85 'name' => pathinfo($file, PATHINFO_BASENAME),
86 'date' => date($this->options['dateFormat'], filemtime($file)),
87 'mime' => $this->getMimeType($file),
88 'icon' => $this->getIcon($this->normalize($file)),
89 'size' => filesize($file),
90 );
91 }
93 echo json_encode(array(
94 'path' => $this->getPath($dir),
95 'dir' => array(
96 'name' => pathinfo($dir, PATHINFO_BASENAME),
97 'date' => date($this->options['dateFormat'], filemtime($dir)),
98 'mime' => 'text/directory',
99 'icon' => 'dir',
100 ),
101 'files' => array_merge(!empty($out[0]) ? $out[0] : array(), !empty($out[1]) ? $out[1] : array()),
102 ));
103 }
105 protected function onDetail(){
106 if(empty($this->post['directory']) || empty($this->post['file'])) return;
108 $file = realpath($this->path.'/'.$this->post['directory'].'/'.$this->post['file']);
109 if(!$this->checkFile($file)) return;
111 require_once(FileManagerUtility::getPath().'/Assets/getid3/getid3.php');
113 $url = $this->normalize(substr($file, strlen($this->path)+1));
114 $mime = $this->getMimeType($file);
115 $content = null;
116 if(FileManagerUtility::startsWith($mime, 'image/')){
117 $size = getimagesize($file);
118 $content = '<img src="'.$url.'" class="preview" alt="" />
119 <h2>${more}</h2>
120 <dl>
121 <dt>${width}</dt><dd>'.$size[0].'px</dd>
122 <dt>${height}</dt><dd>'.$size[1].'px</dd>
123 </dl>';
124 }elseif(FileManagerUtility::startsWith($mime, 'text/') || $mime=='application/x-javascript'){
125 $filecontent = file_get_contents($file, null, null, 0, 300);
126 if(!FileManagerUtility::isBinary($filecontent)) $content = '<div class="textpreview">'.nl2br(str_replace(array('$', "\t"), array('&#36;', '&nbsp;&nbsp;'), htmlentities($filecontent))).'</div>';
127 }elseif($mime=='application/zip'){
128 $out = array(array(), array());
129 $getid3 = new getID3();
130 $getid3->Analyze($file);
131 foreach($getid3->info['zip']['files'] as $name => $size){
132 $icon = is_array($size) ? 'dir' : $this->getIcon($name);
133 $out[$icon=='dir' ? 0 : 1][$name] = '<li><a><img src="'.$this->options['assetBasePath'].'/Icons/'.$icon.'.png" alt="" /> '.$name.'</a></li>';
134 }
135 natcasesort($out[0]);
136 natcasesort($out[1]);
137 $content = '<ul>'.implode(array_merge($out[0], $out[1])).'</ul>';
138 }elseif(FileManagerUtility::startsWith($mime, 'audio/')){
139 $getid3 = new getID3();
140 $getid3->Analyze($file);
142 $content = '<div class="object">
143 <object type="application/x-shockwave-flash" data="'.$this->options['assetBasePath'].'/dewplayer.swf?mp3='.rawurlencode($url).'&volume=30" width="200" height="20">
144 <param name="movie" value="'.$this->options['assetBasePath'].'/dewplayer.swf?mp3='.rawurlencode($url).'&volume=30" />
145 </object>
146 </div>
147 <h2>${more}</h2>
148 <dl>
149 <dt>${title}</dt><dd>'.$getid3->info['comments']['title'][0].'</dd>
150 <dt>${artist}</dt><dd>'.$getid3->info['comments']['artist'][0].'</dd>
151 <dt>${album}</dt><dd>'.$getid3->info['comments']['album'][0].'</dd>
152 <dt>${length}</dt><dd>'.$getid3->info['playtime_string'].'</dd>
153 <dt>${bitrate}</dt><dd>'.round($getid3->info['bitrate']/1000).'kbps</dd>
154 </dl>';
155 }
157 echo json_encode(array(
158 'content' => $content ? $content : '<div class="margin">
159 ${nopreview}<br/><button value="'.$url.'">${download}</button>
160 </div>',
161 ));
162 }
164 protected function onDestroy(){
165 if(!$this->options['destroy'] || empty($this->post['directory']) || empty($this->post['file'])) return;
167 $file = realpath($this->path.'/'.$this->post['directory'].'/'.$this->post['file']);
168 if(!$this->checkFile($file)) return;
170 $this->unlink($file);
172 echo json_encode(array(
173 'content' => 'destroyed',
174 ));
175 }
177 protected function onCreate(){
178 if(empty($this->post['directory']) || empty($this->post['file'])) return;
180 $file = $this->getName($this->post['file'], $this->getDir($this->post['directory']));
181 if(!$file) return;
183 mkdir($file);
185 $this->onView();
186 }
188 protected function onUpload(){
189 try{
190 if(!$this->options['upload'])
191 throw new FileManagerException('disabled');
192 if(empty($this->get['directory']) || (function_exists('UploadIsAuthenticated') && !UploadIsAuthenticated($this->get)))
193 throw new FileManagerException('authenticated');
195 $dir = $this->getDir($this->get['directory']);
196 $name = pathinfo((Upload::exists('Filedata')) ? $this->getName($_FILES['Filedata']['name'], $dir) : null, PATHINFO_FILENAME);
197 $file = Upload::move('Filedata', $dir.'/', array(
198 'name' => $name,
199 'extension' => $this->options['safe'] && $name && in_array(strtolower(pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION)), array('exe', 'dll', 'php', 'php3', 'php4', 'php5', 'phps')) ? 'txt' : null,
200 'size' => $this->options['maxUploadSize'],
201 'mimes' => $this->getAllowedMimeTypes(),
202 ));
204 if(FileManagerUtility::startsWith(Upload::mime($file), 'image/') && !empty($this->get['resize'])){
205 $img = new Image($file);
206 $size = $img->getSize();
207 if($size['width']>800) $img->resize(800)->save();
208 elseif($size['height']>600) $img->resize(null, 600)->save();
209 }
211 echo json_encode(array(
212 'status' => 1,
213 'name' => pathinfo($file, PATHINFO_BASENAME),
214 ));
215 }catch(UploadException $e){
216 echo json_encode(array(
217 'status' => 0,
218 'error' => class_exists('ValidatorException') ? $e->getMessage() : '${upload.'.$e->getMessage().'}', // This is for Styx :)
219 ));
220 }catch(FileManagerException $e){
221 echo json_encode(array(
222 'status' => 0,
223 'error' => '${upload.'.$e->getMessage().'}',
224 ));
225 }
226 }
228 /* This method is used by both move and rename */
229 protected function onMove(){
230 if(empty($this->post['directory']) || empty($this->post['file'])) return;
232 $rename = empty($this->post['newDirectory']) && !empty($this->post['name']);
233 $dir = $this->getDir($this->post['directory']);
234 $file = realpath($dir.'/'.$this->post['file']);
236 $is_dir = is_dir($file);
237 if(!$this->checkFile($file) || (!$rename && $is_dir))
238 return;
240 if($rename || $is_dir){
241 if(empty($this->post['name'])) return;
242 $newname = $this->getName($this->post['name'], $dir);
243 $fn = 'rename';
244 }else{
245 $newname = $this->getName(pathinfo($file, PATHINFO_FILENAME), $this->getDir($this->post['newDirectory']));
246 $fn = !empty($this->post['copy']) ? 'copy' : 'rename';
247 }
249 if(!$newname) return;
251 $ext = pathinfo($file, PATHINFO_EXTENSION);
252 if($ext) $newname .= '.'.$ext;
253 $fn($file, $newname);
255 echo json_encode(array(
256 'name' => pathinfo($this->normalize($newname), PATHINFO_BASENAME),
257 ));
258 }
260 protected function unlink($file){
261 $file = realpath($file);
262 if($this->basedir==$file || strlen($this->basedir)>=strlen($file))
263 return;
265 if(is_dir($file)){
266 $files = glob($file.'/*');
267 if(is_array($files))
268 foreach($files as $f)
269 $this->unlink($f);
271 rmdir($file);
272 }else{
273 try{ if($this->checkFile($file)) unlink($file); }catch(Exception $e){}
274 }
275 }
277 protected function getName($file, $dir){
278 $files = array();
279 foreach((array)glob($dir.'/*') as $f)
280 $files[] = pathinfo($f, PATHINFO_FILENAME);
282 $pathinfo = pathinfo($file);
283 $file = $dir.'/'.FileManagerUtility::pagetitle($pathinfo['filename'], $files).(!empty($pathinfo['extension']) ? '.'.$pathinfo['extension'] : null);
285 return !$file || !FileManagerUtility::startsWith($file, $this->basedir) || file_exists($file) ? null : $file;
286 }
288 protected function getIcon($file){
289 if(FileManagerUtility::endsWith($file, '/..')) return 'dir_up';
290 else if(is_dir($file)) return 'dir';
292 $ext = pathinfo($file, PATHINFO_EXTENSION);
293 return ($ext && file_exists(realpath($this->options['assetBasePath'].'/Icons/'.$ext.'.png'))) ? $ext : 'default';
294 }
296 protected function getMimeType($file){
297 return is_dir($file) ? 'text/directory' : Upload::mime($file);
298 }
300 protected function getDir($dir){
301 $dir = realpath($this->path.'/'.(FileManagerUtility::startsWith($dir, $this->basename) ? $dir : $this->basename));
302 return $this->checkFile($dir) ? $dir : $this->basedir;
303 }
305 protected function getPath($file){
306 $file = $this->normalize(substr($file, $this->length));
307 return substr($file, FileManagerUtility::startsWith($file, '/') ? 1 : 0);
308 }
310 protected function checkFile($file){
311 $mimes = $this->getAllowedMimeTypes();
312 $hasFilter = $this->options['filter'] && count($mimes);
313 if($hasFilter) array_push($mimes, 'text/directory');
314 return !(!$file || !FileManagerUtility::startsWith($file, $this->basedir) || !file_exists($file) || ($hasFilter && !in_array($this->getMimeType($file), $mimes)));
315 }
317 protected function normalize($file){
318 return preg_replace('/\\\|\/{2,}/', '/', $file);
319 }
321 protected function getAllowedMimeTypes(){
322 $filter = $this->options['filter'];
324 if(!$filter) return null;
325 if(!FileManagerUtility::endsWith($filter, '/')) return array($filter);
327 static $mimes;
328 if(!$mimes) $mimes = parse_ini_file(FileManagerUtility::getPath().'/MimeTypes.ini');
330 foreach($mimes as $mime)
331 if(FileManagerUtility::startsWith($mime, $filter))
332 $mimeTypes[] = strtolower($mime);
334 return $mimeTypes;
335 }
337 }
339 class FileManagerException extends Exception {}
341 /* Stripped-down version of some Styx PHP Framework-Functionality bundled with this FileBrowser. Styx is located at: http://styx.og5.net */
342 class FileManagerUtility {
344 public static function endsWith($string, $look){
345 return strrpos($string, $look)===strlen($string)-strlen($look);
346 }
348 public static function startsWith($string, $look){
349 return strpos($string, $look)===0;
350 }
352 public static function pagetitle($data, $options = array()){
353 static $regex;
354 if(!$regex){
355 $regex = array(
356 explode(' ', 'Æ æ Œ œ ß Ü ü Ö ö Ä ä À Á Â Ã Ä Å &#260; &#258; Ç &#262; &#268; &#270; &#272; Ð È É Ê Ë &#280; &#282; &#286; Ì Í Î Ï &#304; &#321; &#317; &#313; Ñ &#323; &#327; Ò Ó Ô Õ Ö Ø &#336; &#340; &#344; Š &#346; &#350; &#356; &#354; Ù Ú Û Ü &#366; &#368; Ý Ž &#377; &#379; à á â ã ä å &#261; &#259; ç &#263; &#269; &#271; &#273; è é ê ë &#281; &#283; &#287; ì í î ï &#305; &#322; &#318; &#314; ñ &#324; &#328; ð ò ó ô õ ö ø &#337; &#341; &#345; &#347; š &#351; &#357; &#355; ù ú û ü &#367; &#369; ý ÿ ž &#378; &#380;'),
357 explode(' ', 'Ae ae Oe oe ss Ue ue Oe oe Ae ae A A A A A A A A C C C D D D E E E E E E G I I I I I L L L N N N O O O O O O O R R S S S T T U U U U U U Y Z Z Z a a a a a a a a c c c d d e e e e e e g i i i i i l l l n n n o o o o o o o o r r s s s t t u u u u u u y y z z z'),
358 );
360 $regex[0][] = '"';
361 $regex[0][] = "'";
362 }
364 $data = trim(substr(preg_replace('/(?:[^A-z0-9]|_|\^)+/i', '_', str_replace($regex[0], $regex[1], $data)), 0, 64), '_');
365 return !empty($options) ? self::checkTitle($data, $options) : $data;
366 }
368 protected static function checkTitle($data, $options = array(), $i = 0){
369 if(!is_array($options)) return $data;
371 foreach($options as $content)
372 if($content && strtolower($content)==strtolower($data.($i ? '_'.$i : '')))
373 return self::checkTitle($data, $options, ++$i);
375 return $data.($i ? '_'.$i : '');
376 }
378 public static function isBinary($str){
379 $array = array(0, 255);
380 for($i = 0; $i < strlen($str); $i++)
381 if(in_array(ord($str[$i]), $array)) return true;
383 return false;
384 }
386 public static function getPath(){
387 static $path;
388 return $path ? $path : $path = pathinfo(__FILE__, PATHINFO_DIRNAME);
389 }