PageRenderTime 35ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/fileManager.php

https://github.com/pheeque/jquery.fileManager
PHP | 235 lines | 157 code | 30 blank | 48 comment | 45 complexity | a6f8ea49cd86c3389a7fde075292722c MD5 | raw file
  1. <?php
  2. /*
  3. * File Manager
  4. *
  5. * Copyright (c) 2010 Tom Kay - oridan82@gmail.com
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.*
  19. *
  20. */
  21. /*
  22. * Uncomment the line below to enable basic operation. By default this
  23. * will manage a folder called 'uploads' relative to this script's path.
  24. *
  25. * You can change this folder to anything you like. The script will not
  26. * allow managing of files outside of this path.
  27. *
  28. * Advanced users may wish to write a separate php script to control the
  29. * ajax features of the File Manager. Including callbacks for deleting
  30. * or renaming files.
  31. */
  32. //jqFileManager::ProcessAjax( dirname(__FILE__).'/uploads' );
  33. class jqFileManager {
  34. private static $data = array();
  35. static function GetRelativePath($path) {
  36. $path = self::ResolvePath($path);
  37. $pos = strpos($path,realpath($_SERVER['DOCUMENT_ROOT']));
  38. if ($pos === false) return $path;
  39. return '/'.ltrim(substr($path,$pos+strlen(realpath($_SERVER['DOCUMENT_ROOT']))),DIRECTORY_SEPARATOR);
  40. }
  41. static function GetPathFolder() {
  42. return self::GetRelativePath(dirname(__FILE__)).DIRECTORY_SEPARATOR;
  43. }
  44. static function GetPathSelf() {
  45. return self::GetRelativePath(__FILE__);
  46. }
  47. static function GetPathJS() {
  48. return self::GetPathFolder().'jquery.fileManager.js';
  49. }
  50. static function GetPathCSS() {
  51. return self::GetPathFolder().'jquery.fileManager.css';
  52. }
  53. static function ResolvePath($path) {
  54. $newpath = preg_replace('/[^\/]+\/\.\.\/?/', '', $path);
  55. if ($newpath != $path) $newpath = self::ResolvePath($newpath);
  56. return $newpath;
  57. }
  58. static function AddIcon($path, $title='',$folder=false) {
  59. self::$data[] = array('path'=>$path,'title'=>$title,'type'=>$folder);
  60. }
  61. static function ProcessAjax($rootPath,$deleteCallback=null,$renameCallback=null) {
  62. $pMod = array_key_exists('path',$_POST) ? $_POST['path'] : '';
  63. $path = $rootPath.'/'.trim($pMod,'/');
  64. $path = self::ResolvePath($path);
  65. $path = rtrim($path,'/');
  66. if (strpos($path,$rootPath)===FALSE) $path = $rootPath;
  67. if (!file_exists($path)) mkdir($path,octdec('0777'),true);
  68. if (isset($_FILES['file'])) return self::ProcessUpload($path);
  69. if (isset($_POST['delete'])) {
  70. $from = self::ResolvePath($path.'/'.$_POST['delete']);
  71. if (strpos($from,$rootPath)===FALSE) {
  72. echo 'alert("Can only perform operations within the root path");';
  73. return false;
  74. }
  75. if (!file_exists($from)) {
  76. echo 'alert("File or Folder no longer exists");';
  77. return false;
  78. }
  79. try {
  80. if (is_dir($from)) rmdir($from);
  81. else unlink($from);
  82. } catch (Exception $e) {
  83. echo 'alert("Cannot Delete. Folder may not be empty.");';
  84. return false;
  85. }
  86. return true;
  87. }
  88. if (array_key_exists('mFrom',$_POST) && array_key_exists('mTo',$_POST)) {
  89. $from = self::ResolvePath($path.'/'.$_POST['mFrom']);
  90. $to = self::ResolvePath($path.'/'.$_POST['mTo']);
  91. if (strpos($from,$rootPath)===FALSE || strpos($to,$rootPath)===FALSE) {
  92. echo 'alert("Can only perform operations within the root path");';
  93. return false;
  94. }
  95. if (file_exists($to)) {
  96. echo 'alert("Destination already exists");';
  97. return false;
  98. }
  99. try {
  100. rename($from,$to);
  101. } catch(Exception $e) {
  102. echo $e->getMessage();
  103. echo 'alert("Cannot move or rename.");';
  104. return false;
  105. }
  106. if (is_callable($renameCallback)) call_user_func($renameCallback,$from,$to);
  107. return true;
  108. }
  109. $glob = glob($path.'/{,.}*',GLOB_BRACE);
  110. $files = array_merge(array_filter($glob, 'is_dir'),array_filter($glob, 'is_file'));
  111. foreach ($files as $file) {
  112. $filename = basename($file);
  113. if ($filename === '..' || $filename === '.') continue;
  114. if (!is_dir($file) && array_key_exists('filter',$_POST) && !preg_match('/'.$_POST['filter'].'/i',$filename)) continue;
  115. self::AddIcon($filename,$filename,is_dir($file)?1:0);
  116. }
  117. // uPath is full path less rootpath less filename
  118. $uPath = substr(self::GetRelativePath($path),strlen(self::GetRelativePath($rootPath)));
  119. if (!$uPath) $uPath = '';
  120. die(json_encode(array('rootPath'=>self::GetRelativePath($rootPath),'path'=>$uPath,'files'=>self::$data)));
  121. }
  122. public static function ProcessUpload($path) {
  123. if (ob_get_level()) ob_end_clean();
  124. $destination = realpath($path);
  125. // HTTP headers for no cache etc
  126. header('Content-type: text/plain; charset=UTF-8');
  127. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  128. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  129. header("Cache-Control: no-store, no-cache, must-revalidate");
  130. header("Cache-Control: post-check=0, pre-check=0", false);
  131. header("Pragma: no-cache");
  132. // Settings
  133. $targetDir = $destination;// ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
  134. $cleanupTargetDir = false; // Remove old files
  135. $maxFileAge = 60 * 60; // Temp file age in seconds
  136. // 5 minutes execution time
  137. //set_time_limit(0);
  138. // usleep(5000);
  139. // Get parameters
  140. $chunk = array_key_exists('chunk',$_REQUEST) ? $_REQUEST["chunk"] : 0;
  141. $chunks = array_key_exists('chunks',$_REQUEST) ? $_REQUEST["chunks"] : 0;
  142. $fileName = array_key_exists('name',$_REQUEST) ? $_REQUEST["name"] : '';
  143. // Clean the fileName for security reasons
  144. $fileName = preg_replace('/[^\w\._]+/', '', $fileName);
  145. if (is_dir($targetDir . DIRECTORY_SEPARATOR . $fileName)) die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  146. // Create target dir
  147. if (!file_exists($targetDir)) {
  148. mkdir($targetDir);
  149. chmod($targetDir,0777);
  150. }
  151. // Remove old temp files
  152. if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
  153. while (($file = readdir($dir)) !== false) {
  154. $filePath = $targetDir . DIRECTORY_SEPARATOR . $file;
  155. // Remove temp files if they are older than the max age
  156. if (preg_match('/\\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge))
  157. unlink($filePath);
  158. }
  159. closedir($dir);
  160. } else
  161. die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
  162. $contentType = '';
  163. // Look for the content type header
  164. if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
  165. $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
  166. if (isset($_SERVER["CONTENT_TYPE"]))
  167. $contentType = $_SERVER["CONTENT_TYPE"];
  168. if (strpos($contentType, "multipart") !== false) {
  169. if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
  170. // Open temp file
  171. $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
  172. if ($out) {
  173. // Read binary input stream and append it to temp file
  174. $in = fopen($_FILES['file']['tmp_name'], "rb");
  175. if ($in) {
  176. while ($buff = fread($in, 4096))
  177. fwrite($out, $buff);
  178. } else
  179. die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  180. fclose($out);
  181. unlink($_FILES['file']['tmp_name']);
  182. } else
  183. die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  184. } else
  185. die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
  186. } else {
  187. // Open temp file
  188. $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
  189. if ($out) {
  190. // Read binary input stream and append it to temp file
  191. $in = fopen("php://input", "rb");
  192. if ($in) {
  193. while ($buff = fread($in, 4096))
  194. fwrite($out, $buff);
  195. } else
  196. die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
  197. fclose($out);
  198. } else
  199. die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  200. }
  201. // Return JSON-RPC response
  202. die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
  203. }
  204. }
  205. ?>