PageRenderTime 23ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/plugins/UsefulFunctions/library/functions.file.php

https://github.com/DMeganoski/Gallery-Designer
PHP | 261 lines | 250 code | 7 blank | 4 comment | 21 complexity | 24e67d6dac4057281706601e4df7d2c4 MD5 | raw file
  1. <?php
  2. /**
  3. *
  4. */
  5. if (!function_exists('CompileFile')) {
  6. function CompileFile($File = Null, $bSave = False) {
  7. static $RequiredFiles = array();
  8. if (is_null($File)){
  9. $Return = $RequiredFiles;
  10. $RequiredFiles = array();
  11. return $Return;
  12. }
  13. if ($bSave != False) {
  14. $NewFileContent = '';
  15. $Files = array_values(CompileFile());
  16. foreach ($Files as $N => $FilePath) {
  17. $FileData = array_map('rtrim', file($FilePath));
  18. $Count = count($FileData);
  19. for ($i = 0; $i < $Count; $i++) {
  20. $String = $FileData[$i];
  21. if (strpos($String, 'require') === 0
  22. || in_array($String, array('<?php', '?>'))) unset($FileData[$i]);
  23. }
  24. $BaseName = pathinfo($FilePath, PATHINFO_BASENAME);
  25. $FirstLine = "\n/* " . str_pad(" $BaseName ", 72, '=', STR_PAD_LEFT) . "*/\n";
  26. $NewFileContent .= $FirstLine;
  27. $NewFileContent .= implode("\n", $FileData);
  28. }
  29. return file_put_contents($File, "<?php\n".$NewFileContent);
  30. }
  31. $RealPath = realpath($File);
  32. if (!$RealPath) throw new Exception('No such file '.$File);
  33. //if (count($RequiredFiles) == 0) $RequiredFiles[] = $RealPath;
  34. $Hash = Crc32File($RealPath);
  35. $RequiredFiles[$Hash] = $RealPath;
  36. $Content = file_get_contents($RealPath);
  37. $AllTokens = token_get_all($Content);
  38. foreach ($AllTokens as $N => $TokenArray) {
  39. list($TokenID) = $TokenArray;
  40. $String = ArrayValue(1, $TokenArray);
  41. if (!is_int($TokenID) || !in_array(token_name($TokenID), array('T_REQUIRE', 'T_REQUIRE_ONCE'))) continue;
  42. $PrevTokenString = ArrayValue(1, $AllTokens[$N-1]);
  43. $PrevTokenString = str_replace("\r", '', $PrevTokenString);
  44. if ($PrevTokenString !== "\n") continue;
  45. $OtherTokens = array_slice($AllTokens, $N);
  46. $FileTokens = array();
  47. foreach ($OtherTokens as $M => $Tk) {
  48. if (count($Tk) == 1 && $Tk[0] == ';') {
  49. $FileTokens = array_slice($OtherTokens, 0, $M);
  50. break;
  51. }
  52. }
  53. if (count($FileTokens) == 0) throw new Exception('FileTokens not found.');
  54. $TheFile = False;
  55. foreach(array_reverse($FileTokens) as $Tk){
  56. if (is_int($Tk[0]) && token_name($Tk[0]) == 'T_CONSTANT_ENCAPSED_STRING') {
  57. $TheFile = $Tk[1];
  58. $TheFile = trim($TheFile, '"\'/\\');
  59. break;
  60. }
  61. }
  62. if (!$TheFile) throw Exception('No string file found.');
  63. $DirnameFileConstruct = dirname($RealPath);
  64. $TheFile = $DirnameFileConstruct . DS . $TheFile;
  65. $RealFile = realpath($TheFile);
  66. if (!$RealFile) throw new Exception(sprintf('Invalid path `%1$s`.', $TheFile));
  67. $Hash = Crc32File($RealFile);
  68. if (!array_key_exists($Hash, $RequiredFiles)) {
  69. CompileFile($RealFile);
  70. $RequiredFiles[$Hash] = $RealFile;
  71. }
  72. }
  73. }
  74. }
  75. /**
  76. * Calculates the crc32 checksum of a file
  77. */
  78. if (!function_exists('Crc32File')) {
  79. function Crc32File($File) {
  80. return crc32( sha1_file($File) );
  81. }
  82. }
  83. /**
  84. *
  85. */
  86. if (!function_exists('GenerateCleanTargetName')) {
  87. function GenerateCleanTargetName($TargetFolder, $Name, $Extension = '', $TempFile = False, $bForceOverwriteExisting = False) {
  88. if ($Extension == '') {
  89. $Extension = pathinfo($Name, 4);
  90. $Name = pathinfo($Name, 8);
  91. }
  92. $Extension = Gdn_Format::Clean($Extension);
  93. $BaseName = Gdn_Format::Clean($Name);
  94. // check for file with same name
  95. $TestName = $BaseName;
  96. $TargetFile = $TargetFolder . DS . $TestName . '.' . $Extension;
  97. if (!file_exists($TargetFile)) return $TargetFile;
  98. $IsSameFile = ($TempFile != False && file_exists($TempFile) && Crc32File($TempFile) == Crc32File($TargetFile));
  99. if ($IsSameFile || $bForceOverwriteExisting) return $TargetFile;
  100. $Count = 0;
  101. do {
  102. $TestName = $BaseName.'-'.strtolower(RandomString(rand(1, 5)));
  103. $TargetFile = $TargetFolder . DS . $TestName . '.' . $Extension;
  104. // make sure that iteration will end
  105. if (++$Count > 250) throw new Exception('Cannot generate unique name for file.');
  106. } while (file_exists($TargetFile));
  107. return $TargetFile;
  108. }
  109. }
  110. /**
  111. *
  112. */
  113. if (!function_exists('UploadFile')) {
  114. function UploadFile($TargetFolder, $InputName, $Options = False) {
  115. /* if (is_array($InputName)) {
  116. $Options = $InputName;
  117. $InputName = $TargetFolder;
  118. }*/
  119. $FileName = ArrayValue('name', ArrayValue($InputName, $_FILES));
  120. if ($FileName == '') return; // no upload, return null
  121. // options
  122. $AllowFileExtension = ArrayValue('AllowFileExtension', $Options);
  123. // TODO: $Overwrite is not used yet
  124. $CanOverwrite = ArrayValue('Overwrite', $Options, False);
  125. $CreateTargetFolder = ArrayValue('CreateTargetFolder', $Options, True);
  126. $WebTarget = ArrayValue('WebTarget', $Options);
  127. if ($CreateTargetFolder === True) {
  128. if (!file_exists($TargetFolder)) mkdir($TargetFolder, 0777, True);
  129. if (!is_writable($TargetFolder)) throw new Exception(sprintf('Directory (%s) is not writable.', $TargetFolder));
  130. }
  131. $Upload = new Gdn_Upload();
  132. if ($AllowFileExtension != False) {
  133. if (!is_array($AllowFileExtension)) $AllowFileExtension = SplitString($AllowFileExtension);
  134. foreach ($AllowFileExtension as $Extension) $Upload->AllowFileExtension($Extension);
  135. }
  136. $IsMultipleUpload = is_array($FileName);
  137. $Count = ($IsMultipleUpload) ? count($FileName) : 1;
  138. $OriginalFiles = $_FILES;
  139. $Result = array();
  140. for($i = 0; $i < $Count; $i++){
  141. if ($IsMultipleUpload != False) {
  142. $_FILES[$InputName] = array();
  143. foreach(array('name', 'type', 'tmp_name', 'error', 'size') as $Key) {
  144. $Value = GetValueR($InputName.'.'.$Key.'.'.$i, $OriginalFiles);
  145. SetValue($Key, $_FILES[$InputName], $Value);
  146. }
  147. } else $FileName = array($FileName);
  148. $TempFile = $Upload->ValidateUpload($InputName);
  149. $TargetFile = GenerateCleanTargetName($TargetFolder, $FileName[$i], '', $TempFile, $CanOverwrite);
  150. // 2.0.18 screwed Gdn_Upload::SaveAs()
  151. //$Upload->SaveAs($TempFile, $TargetFile);
  152. if (!move_uploaded_file($TempFile, $TargetFile))
  153. throw new Exception(sprintf(T('Failed to move uploaded file to target destination (%s).'), $TargetFile));
  154. if ($WebTarget != False) $File = str_replace(DS, '/', $TargetFile);
  155. elseif (array_key_exists('WithTargetFolder', $Options)) $File = $TargetFile;
  156. else $File = pathinfo($TargetFile, PATHINFO_BASENAME);
  157. $Result[] = $File;
  158. }
  159. $_FILES = $OriginalFiles;
  160. if ($IsMultipleUpload) return $Result;
  161. return $File;
  162. }
  163. }
  164. # http://php.net/manual/en/function.readdir.php
  165. /**
  166. *
  167. */
  168. if (!function_exists('ProcessDirectory')) {
  169. function ProcessDirectory($Directory, $Options = False){
  170. $bRecursive = $Options;
  171. /*if(Is_Bool($Options)) $bRecursive = $Options;
  172. elseif(Is_Numeric($Options)) $IntDeep = $Options; // 0 - unlim
  173. elseif(Is_Array($Options)){
  174. $IntDeep = ArrayValue('Deep', $Options, '0');
  175. $bRecursive = ArrayValue('Recursive', $Options, False);
  176. }*/
  177. if (!is_dir($Directory)) return False;
  178. $List = array();
  179. $Handle = opendir($Directory);
  180. while(False !== ($File = ReadDir($Handle))){
  181. $Path = $Directory.DS.$File;
  182. if ($File == '.' || $File == '..' || !file_exists($Path)) continue;
  183. if (is_dir($Path) && $bRecursive) {
  184. $NextDirectory = ProcessDirectory($Path, True);
  185. if (is_array($NextDirectory)) $List = array_merge($List, $NextDirectory);
  186. } else {
  187. $Entry = new StdClass();
  188. $Entry->Filename = $File;
  189. $Entry->Directory = $Directory;
  190. $Entry->Modtime = filemtime($Path);
  191. if (!is_dir($Path)) { // files
  192. $Entry->Size = FileSize($Path);
  193. } else { // directories
  194. $Entry->IsWritable = Is_Writable($Path);
  195. $Entry->bDirectory = True;
  196. }
  197. $List[] = $Entry;
  198. }
  199. }
  200. closedir($Handle);
  201. return $List;
  202. }
  203. }
  204. /**
  205. Recursive remove directory that remove non empty dirs recursively.
  206. It enters every directory, removes every file starting from the given path.
  207. Note: Gdn_FileSystem::RemoveFolder()
  208. */
  209. if (!function_exists('RecursiveRemoveDirectory')) {
  210. function RecursiveRemoveDirectory($Path){
  211. // Gdn_FileSysytem::RemoveFolder($Path)
  212. $Directory = new RecursiveDirectoryIterator($Path);
  213. // Remove all files
  214. foreach(new RecursiveIteratorIterator($Directory) as $File) unlink($File);
  215. // Remove all subdirectories
  216. foreach($Directory as $SubDirectory){
  217. // If a subdirectory can't be removed, it's because it has subdirectories, so recursiveRemoveDirectory is called again passing the subdirectory as path
  218. // @ suppress the warning message
  219. if (!@rmdir($SubDirectory)) RecursiveRemoveDirectory($SubDirectory);
  220. }
  221. // Remove main directory
  222. return rmdir($Path);
  223. }
  224. }
  225. /**
  226. * Returns file extension
  227. */
  228. if (!function_exists('FileExtension')) {
  229. function FileExtension($Basename) {
  230. return strtolower(pathinfo($Basename, 4));
  231. }
  232. }