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

/core/helpers/File.php

http://kancms.googlecode.com/
PHP | 390 lines | 217 code | 80 blank | 93 comment | 79 complexity | 6c800c47aa270ab3000806222deb5230 MD5 | raw file
Possible License(s): BSD-2-Clause, GPL-2.0, LGPL-2.1
  1. <?php
  2. if( !defined('CORE_PATH')) die("Access Denied");
  3. class File extends Helper {
  4. public function __construct() {
  5. }
  6. /**
  7. * Uploads a single file to the server
  8. */
  9. function uploadFile($dirname = NULL, $filename = NULL, $mime_types = NULL) {
  10. if( isset($_FILES['uploadfile']) && is_array($_FILES['uploadfile']['name']) ) {
  11. $this->uploadFiles($dirname, $filename, $mime_types);
  12. return;
  13. }
  14. $fileType = $_FILES['uploadfile']['type'];
  15. # list of permitted file types, this is only images but documents can be added
  16. //$permitted = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/svg+xml');
  17. $typeOk = true; # with the correct type the file will be uploaded or rejected.
  18. /*foreach ($permitted as $type) {
  19. if ($type == $fileType) {
  20. $typeOk = true;
  21. break;
  22. }
  23. }*/
  24. # if typeOk upload the file
  25. if ($typeOk) {
  26. if( isset($dirname) && $dirname != "" ) {
  27. // attempt to create the target directory if it does not exist
  28. @mkdir($dirname, 0775, true);
  29. // check if the directory was created or already exists
  30. if( file_exists($dirname) ) {
  31. // throw if directory is not writable
  32. if( !is_writable($dirname) ) {
  33. return array('type' => 'error', 'message' => 'Upload Directory Is Not Writable');
  34. }
  35. // determine the extension of the uploaded file
  36. $ext = substr($_FILES['uploadfile']['name'], strrpos($_FILES['uploadfile']['name'], "."));
  37. // append the file extension if not already part of the uploaded file name
  38. if( stristr($filename, $ext) === FALSE ) {
  39. $filename = $filename . $ext;
  40. }
  41. // determine the name of the destination file
  42. $destName = is_string($filename) && $filename != "" ? $dirname . $filename : $dirname . $_FILES['uploadfile']['name'];
  43. // if already present inform
  44. if( file_exists($destName) ) {
  45. return array('type' => 'error', 'message' => 'File Already Exists');
  46. }
  47. // upload move uploaded file to destination
  48. else {
  49. move_uploaded_file($_FILES['uploadfile']['tmp_name'], $destName );
  50. }
  51. // inform of success
  52. return array('type' => 'success', 'file' => $destName, 'fileType' => $fileType);
  53. }
  54. else {
  55. return array('type' => 'error', 'message' => 'Upload Directory Does Not Exist');
  56. }
  57. } else {
  58. // get the file data
  59. $file_contents = file_get_contents($_FILES['uploadfile']['tmp_name']);
  60. return array('type' => 'success', 'data' => $file_contents, 'file_type' => $fileType);
  61. }
  62. }
  63. return false;
  64. }
  65. /**
  66. * Uploads Multiple Files to the servers
  67. */
  68. function uploadFiles($dirname = NULL, $filename_orig = NULL, $mime_types = NULL) {
  69. # list of permitted file types, this is only images but documents can be added
  70. //$permitted = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/svg+xml');
  71. if( isset($dirname) && $dirname != "" ) {
  72. // attempt to create the target directory if it does not exist
  73. @mkdir($dirname, 0775, true);
  74. // check if the directory was created or already exists
  75. if( file_exists($dirname) ) {
  76. // throw if directory is not writable
  77. if( !is_writable($dirname) ) {
  78. return array('type' => 'error', 'message' => 'Upload Directory Is Not Writable');
  79. }
  80. // get number of uploaded files
  81. $uploaded = count($_FILES['uploadfile']['name']);
  82. $files = array(); $fileTypes = array();
  83. for($i = 0; $i < $uploaded; $i++) {
  84. $fileType = $_FILES['uploadfile']['type'][$i];
  85. $typeOk = true; # with the correct type the file will be uploaded or rejected.
  86. /*foreach ($permitted as $type) {
  87. if ($type == $fileType) {
  88. $typeOk = true;
  89. break;
  90. }
  91. }*/
  92. # if typeOk upload the file
  93. if ($typeOk) {
  94. // determine the extension of the uploaded file
  95. $ext = substr($_FILES['uploadfile']['name'][$i], strrpos($_FILES['uploadfile']['name'][$i], "."));
  96. $filename = $filename_orig;
  97. // append the file extension if not already part of the uploaded file name
  98. if( stristr($filename_orig, $ext) === FALSE ) {
  99. $filename = $filename_orig . "_$i" . $ext;
  100. }
  101. // determine the name of the destination file
  102. $destName = is_string($filename) && $filename != "" ? ($dirname . $filename) : $dirname . $_FILES['uploadfile']['name'][$i];
  103. // if already present inform
  104. if( !file_exists($destName) ) {
  105. move_uploaded_file($_FILES['uploadfile']['tmp_name'][$i], $destName );
  106. $files[] = $destName;
  107. $fileTypes[] = $fileType;
  108. }
  109. }
  110. }
  111. // inform of success
  112. return array('type' => 'success', 'file' => $files, 'fileType' => $fileTypes);
  113. }
  114. else {
  115. return array('type' => 'error', 'message' => 'Upload Directory Does Not Exist');
  116. }
  117. }
  118. return false;
  119. }
  120. public function deleteFile($file) {
  121. if( !file_exists($file) ) {
  122. return;
  123. }
  124. try {
  125. unlink($file);
  126. } catch(Exception $e) {
  127. echo $e;
  128. }
  129. }
  130. public function deleteDirectory($dirname) {
  131. // Sanity check
  132. if (!file_exists($dirname) ) {
  133. return false;
  134. }
  135. // Simple delete for a file
  136. if (is_file($dirname)) {
  137. return unlink($dirname);
  138. }
  139. // Loop through the folder
  140. $dir = dir($dirname);
  141. while (false !== $entry = $dir->read()) {
  142. // Skip pointers
  143. if ($entry == '.' || $entry == '..') {
  144. continue;
  145. }
  146. // Recurse
  147. $this->deleteDirectory("$dirname/$entry");
  148. }
  149. // Clean up
  150. $dir->close();
  151. return rmdir($dirname);
  152. }
  153. public function extractZipArchive($filePath, $destFolder = '') {
  154. // create object
  155. $zip = new ZipArchive() ;
  156. // open archive
  157. if ($zip->open( $filePath ) !== TRUE) {
  158. die ('Could not open archive');
  159. }
  160. // if the destFolder is not supplied, then we'll need to extract the file to
  161. // same directory.
  162. if( $destFolder == '') {
  163. $destFolder = dirname($filePath);
  164. }
  165. // extract contents to destination directory
  166. $zip->extractTo($destFolder);
  167. // close archive
  168. $zip->close();
  169. }
  170. /**
  171. * Copy file or folder from source to destination, it can do
  172. * recursive copy as well and is very smart
  173. * It recursively creates the dest file or directory path if there weren't exists
  174. * Situtaions :
  175. * - Src:/home/test/file.txt ,Dst:/home/test/b ,Result:/home/test/b -> If source was file copy file.txt name with b as name to destination
  176. * - Src:/home/test/file.txt ,Dst:/home/test/b/ ,Result:/home/test/b/file.txt -> If source was file Creates b directory if does not exsits and copy file.txt into it
  177. * - Src:/home/test ,Dst:/home/ ,Result:/home/test/** -> If source was directory copy test directory and all of its content into dest
  178. * - Src:/home/test/ ,Dst:/home/ ,Result:/home/**-> if source was direcotry copy its content to dest
  179. * - Src:/home/test ,Dst:/home/test2 ,Result:/home/test2/** -> if source was directoy copy it and its content to dest with test2 as name
  180. * - Src:/home/test/ ,Dst:/home/test2 ,Result:->/home/test2/** if source was directoy copy it and its content to dest with test2 as name
  181. * @todo
  182. * - Should have rollback technique so it can undo the copy when it wasn't successful
  183. * - Auto destination technique should be possible to turn off
  184. * - Supporting callback function
  185. * - May prevent some issues on shared enviroments : http://us3.php.net/umask
  186. * @param $source //file or folder
  187. * @param $dest ///file or folder
  188. * @param $options //folderPermission,filePermission
  189. * @return boolean
  190. */
  191. public function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755))
  192. {
  193. $result=false;
  194. if (is_file($source)) {
  195. if ($dest[strlen($dest)-1]=='/') {
  196. if (!file_exists($dest)) {
  197. cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
  198. }
  199. $__dest=$dest."/".basename($source);
  200. } else {
  201. $__dest=$dest;
  202. }
  203. $result=copy($source, $__dest);
  204. chmod($__dest,$options['filePermission']);
  205. } elseif(is_dir($source)) {
  206. if ($dest[strlen($dest)-1]=='/') {
  207. if ($source[strlen($source)-1]=='/') {
  208. //Copy only contents
  209. } else {
  210. //Change parent itself and its contents
  211. $dest=$dest.basename($source);
  212. @mkdir($dest);
  213. chmod($dest,$options['filePermission']);
  214. }
  215. } else {
  216. if ($source[strlen($source)-1]=='/') {
  217. //Copy parent directory with new name and all its content
  218. @mkdir($dest,$options['folderPermission']);
  219. chmod($dest,$options['filePermission']);
  220. } else {
  221. //Copy parent directory with new name and all its content
  222. @mkdir($dest,$options['folderPermission']);
  223. chmod($dest,$options['filePermission']);
  224. }
  225. }
  226. $dirHandle=opendir($source);
  227. while($file=readdir($dirHandle))
  228. {
  229. if($file!="." && $file!="..")
  230. {
  231. if(!is_dir($source."/".$file)) {
  232. $__dest=$dest."/".$file;
  233. } else {
  234. $__dest=$dest."/".$file;
  235. }
  236. //echo "$source/$file ||| $__dest<br />";
  237. $result = $this->smartCopy($source."/".$file, $__dest, $options);
  238. }
  239. }
  240. closedir($dirHandle);
  241. } else {
  242. $result=false;
  243. }
  244. return $result;
  245. }
  246. public function encodeUrlParam ( $string ) {
  247. $string = trim($string);
  248. if ( ctype_digit($string) ) {
  249. return $string;
  250. } else {
  251. // replace accented chars
  252. $accents = '/&([A-Za-z]{1,2})(grave|acute|circ|cedil|uml|lig);/';
  253. $string_encoded = htmlentities($string,ENT_NOQUOTES,'UTF-8');
  254. $string = preg_replace($accents,'$1',$string_encoded);
  255. // clean out the rest
  256. $replace = array('([\40])','([^a-zA-Z0-9-])','(-{2,})');
  257. $with = array('-','','-');
  258. $string = preg_replace($replace,$with,$string);
  259. }
  260. return strtolower($string);
  261. }
  262. function generateThumb( $imagePath, $outputDir, $thumbWidth = 150 ) {
  263. if( !file_exists($outputDir) && !mkdir($outputDir, 0777, true) ) {
  264. return;
  265. }
  266. /*if( fileperms($outputDir) != 0777 ) {
  267. @chmod($outputDir, 0777);
  268. }*/
  269. // get image file path information
  270. $info = pathinfo($imagePath);
  271. $img = NULL;
  272. // load image and get image size
  273. if ( strtolower($info['extension']) == 'jpg' ) {
  274. $img = imagecreatefromjpeg( $imagePath );
  275. } else if ( strtolower($info['extension']) == 'gif' ) {
  276. $img = imagecreatefromgif( $imagePath );
  277. } else if ( strtolower($info['extension']) == 'png' ) {
  278. $img = imagecreatefrompng( $imagePath );
  279. }
  280. $width = imagesx( $img );
  281. $height = imagesy( $img );
  282. // calculate thumbnail size
  283. $new_width = $thumbWidth;
  284. $new_height = floor( $height * ( $thumbWidth / $width ) );
  285. if( $new_width < $width || $new_height < $height) {
  286. // create a new temporary image
  287. $tmp_img = imagecreatetruecolor( $new_width, $new_height );
  288. if ( strtolower($info['extension']) == 'png' ) {
  289. // work on image transparency
  290. imagealphablending($tmp_img, false);
  291. imagesavealpha($tmp_img, true);
  292. }
  293. // copy and resize old image into new image
  294. imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
  295. // save thumbnail into a file
  296. $fpath = "{$outputDir}{$info['basename']}";
  297. if ( strtolower($info['extension']) == 'jpg' ) {
  298. imagejpeg( $tmp_img, "{$outputDir}{$info['basename']}");
  299. } else if ( strtolower($info['extension']) == 'gif' ) {
  300. imagegif( $tmp_img, "{$outputDir}{$info['basename']}");
  301. } else if ( strtolower($info['extension']) == 'png' ) {
  302. imagepng( $tmp_img, "{$outputDir}{$info['basename']}");
  303. }
  304. return $fpath;
  305. } else {
  306. return $imagePath;
  307. }
  308. }
  309. }
  310. ?>