PageRenderTime 51ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/include/utils/file_utils.php

https://bitbucket.org/cviolette/sugarcrm
PHP | 475 lines | 311 code | 50 blank | 114 comment | 42 complexity | 4ed4e1602b833c7241d445dc65e54bbd MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, BSD-3-Clause
  1. <?php
  2. if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
  3. /*********************************************************************************
  4. * SugarCRM Community Edition is a customer relationship management program developed by
  5. * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
  6. *
  7. * This program is free software; you can redistribute it and/or modify it under
  8. * the terms of the GNU Affero General Public License version 3 as published by the
  9. * Free Software Foundation with the addition of the following permission added
  10. * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
  11. * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
  12. * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
  13. *
  14. * This program is distributed in the hope that it will be useful, but WITHOUT
  15. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  16. * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
  17. * details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public License along with
  20. * this program; if not, see http://www.gnu.org/licenses or write to the Free
  21. * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  22. * 02110-1301 USA.
  23. *
  24. * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
  25. * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
  26. *
  27. * The interactive user interfaces in modified source and object code versions
  28. * of this program must display Appropriate Legal Notices, as required under
  29. * Section 5 of the GNU Affero General Public License version 3.
  30. *
  31. * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
  32. * these Appropriate Legal Notices must retain the display of the "Powered by
  33. * SugarCRM" logo. If the display of the logo is not reasonably feasible for
  34. * technical reasons, the Appropriate Legal Notices must display the words
  35. * "Powered by SugarCRM".
  36. ********************************************************************************/
  37. require_once('include/utils/array_utils.php');
  38. require_once('include/utils/sugar_file_utils.php');
  39. /**
  40. * Convert all \ to / in path, remove multiple '/'s and '/./'
  41. * @param string $path
  42. * @return string
  43. */
  44. function clean_path( $path )
  45. {
  46. // clean directory/file path with a functional equivalent
  47. $appendpath = '';
  48. if ( is_windows() && strlen($path) >= 2 && $path[0].$path[1] == "\\\\" ) {
  49. $path = substr($path,2);
  50. $appendpath = "\\\\";
  51. }
  52. $path = str_replace( "\\", "/", $path );
  53. $path = str_replace( "//", "/", $path );
  54. $path = str_replace( "/./", "/", $path );
  55. return( $appendpath.$path );
  56. }
  57. function create_cache_directory($file)
  58. {
  59. $paths = explode('/',$file);
  60. $dir = rtrim($GLOBALS['sugar_config']['cache_dir'], '/\\');
  61. if(!file_exists($dir))
  62. {
  63. sugar_mkdir($dir, 0775);
  64. }
  65. for($i = 0; $i < sizeof($paths) - 1; $i++)
  66. {
  67. $dir .= '/' . $paths[$i];
  68. if(!file_exists($dir))
  69. {
  70. sugar_mkdir($dir, 0775);
  71. }
  72. }
  73. return $dir . '/'. $paths[sizeof($paths) - 1];
  74. }
  75. function get_module_dir_list()
  76. {
  77. $modules = array();
  78. $path = 'modules';
  79. $d = dir($path);
  80. while($entry = $d->read())
  81. {
  82. if($entry != '..' && $entry != '.')
  83. {
  84. if(is_dir($path. '/'. $entry))
  85. {
  86. $modules[$entry] = $entry;
  87. }
  88. }
  89. }
  90. return $modules;
  91. }
  92. function mk_temp_dir( $base_dir, $prefix="" )
  93. {
  94. $temp_dir = tempnam( $base_dir, $prefix );
  95. if( !$temp_dir || !unlink( $temp_dir ) )
  96. {
  97. return( false );
  98. }
  99. if( sugar_mkdir( $temp_dir ) ){
  100. return( $temp_dir );
  101. }
  102. return( false );
  103. }
  104. function remove_file_extension( $filename )
  105. {
  106. return( substr( $filename, 0, strrpos($filename, ".") ) );
  107. }
  108. function write_array_to_file( $the_name, $the_array, $the_file, $mode="w", $header='' )
  109. {
  110. if(!empty($header) && ($mode != 'a' || !file_exists($the_file))){
  111. $the_string = $header;
  112. }else{
  113. $the_string = "<?php\n" .
  114. '// created: ' . date('Y-m-d H:i:s') . "\n";
  115. }
  116. $the_string .= "\$$the_name = " .
  117. var_export_helper( $the_array ) .
  118. ";";
  119. return sugar_file_put_contents($the_file, $the_string, LOCK_EX) !== false;
  120. }
  121. function write_encoded_file( $soap_result, $write_to_dir, $write_to_file="" )
  122. {
  123. // this function dies when encountering an error -- use with caution!
  124. // the path/file is returned upon success
  125. if( $write_to_file == "" )
  126. {
  127. $write_to_file = $write_to_dir . "/" . $soap_result['filename'];
  128. }
  129. $file = $soap_result['data'];
  130. $write_to_file = str_replace( "\\", "/", $write_to_file );
  131. $dir_to_make = dirname( $write_to_file );
  132. if( !is_dir( $dir_to_make ) )
  133. {
  134. mkdir_recursive( $dir_to_make );
  135. }
  136. $fh = sugar_fopen( $write_to_file, "wb" );
  137. fwrite( $fh, base64_decode( $file ) );
  138. fclose( $fh );
  139. if( md5_file( $write_to_file ) != $soap_result['md5'] )
  140. {
  141. die( "MD5 error after writing file $write_to_file" );
  142. }
  143. return( $write_to_file );
  144. }
  145. function create_custom_directory($file)
  146. {
  147. $paths = explode('/',$file);
  148. $dir = 'custom';
  149. if(!file_exists($dir))
  150. {
  151. sugar_mkdir($dir, 0755);
  152. }
  153. for($i = 0; $i < sizeof($paths) - 1; $i++)
  154. {
  155. $dir .= '/' . $paths[$i];
  156. if(!file_exists($dir))
  157. {
  158. sugar_mkdir($dir, 0755);
  159. }
  160. }
  161. return $dir . '/'. $paths[sizeof($paths) - 1];
  162. }
  163. /**
  164. * This function will recursively generates md5s of files and returns an array of all md5s.
  165. *
  166. * @param $path The path of the root directory to scan - must end with '/'
  167. * @param $ignore_dirs array of filenames/directory names to ignore running md5 on - default 'cache' and 'upload'
  168. * @result $md5_array an array containing path as key and md5 as value
  169. */
  170. function generateMD5array($path, $ignore_dirs = array('cache', 'upload'))
  171. {
  172. $dh = opendir($path);
  173. while (false !== ($filename = readdir($dh)))
  174. {
  175. $current_dir_content[] = $filename;
  176. }
  177. // removes the ignored directories
  178. $current_dir_content = array_diff($current_dir_content, $ignore_dirs);
  179. sort($current_dir_content);
  180. $md5_array = array();
  181. foreach($current_dir_content as $file)
  182. {
  183. // make sure that it's not dir '.' or '..'
  184. if(strcmp($file, ".") && strcmp($file, ".."))
  185. {
  186. if(is_dir($path.$file))
  187. {
  188. // For testing purposes - uncomment to see all files and md5s
  189. //echo "<BR>Dir: ".$path.$file."<br>";
  190. //generateMD5array($path.$file."/");
  191. $md5_array += generateMD5array($path.$file."/", $ignore_dirs);
  192. }
  193. else
  194. {
  195. // For testing purposes - uncomment to see all files and md5s
  196. //echo " File: ".$path.$file."<br>";
  197. //echo md5_file($path.$file)."<BR>";
  198. $md5_array[$path.$file] = md5_file($path.$file);
  199. }
  200. }
  201. }
  202. return $md5_array;
  203. }
  204. /**
  205. * Function to compare two directory structures and return the items in path_a that didn't match in path_b
  206. *
  207. * @param $path_a The path of the first root directory to scan - must end with '/'
  208. * @param $path_b The path of the second root directory to scan - must end with '/'
  209. * @param $ignore_dirs array of filenames/directory names to ignore running md5 on - default 'cache' and 'upload'
  210. * @result array containing all the md5s of everything in $path_a that didn't have a match in $path_b
  211. */
  212. function md5DirCompare($path_a, $path_b, $ignore_dirs = array('cache', 'upload'))
  213. {
  214. $md5array_a = generateMD5array($path_a, $ignore_dirs);
  215. $md5array_b = generateMD5array($path_b, $ignore_dirs);
  216. $result = array_diff($md5array_a, $md5array_b);
  217. return $result;
  218. }
  219. /**
  220. * Function to retrieve all file names of matching pattern in a directory (and it's subdirectories)
  221. * example: getFiles($arr, './modules', '.+/EditView.php/'); // grabs all EditView.phps
  222. * @param array $arr return array to populate matches
  223. * @param string $dir directory to look in [ USE ./ in front of the $dir! ]
  224. * @param regex $pattern optional pattern to match against
  225. */
  226. function getFiles(&$arr, $dir, $pattern = null) {
  227. if(!is_dir($dir))return;
  228. $d = dir($dir);
  229. while($e =$d->read()){
  230. if(substr($e, 0, 1) == '.')continue;
  231. $file = $dir . '/' . $e;
  232. if(is_dir($file)){
  233. getFiles($arr, $file, $pattern);
  234. }else{
  235. if(empty($pattern)) $arr[] = $file;
  236. else if(preg_match($pattern, $file))
  237. $arr[] = $file;
  238. }
  239. }
  240. }
  241. /**
  242. * Function to split up large files for download
  243. * used in download.php
  244. * @param string $filename
  245. * @param int $retbytes
  246. */
  247. function readfile_chunked($filename,$retbytes=true)
  248. {
  249. $chunksize = 1*(1024*1024); // how many bytes per chunk
  250. $buffer = '';
  251. $cnt = 0;
  252. $handle = sugar_fopen($filename, 'rb');
  253. if ($handle === false)
  254. {
  255. return false;
  256. }
  257. while (!feof($handle))
  258. {
  259. $buffer = fread($handle, $chunksize);
  260. echo $buffer;
  261. flush();
  262. if ($retbytes)
  263. {
  264. $cnt += strlen($buffer);
  265. }
  266. }
  267. $status = fclose($handle);
  268. if ($retbytes && $status)
  269. {
  270. return $cnt; // return num. bytes delivered like readfile() does.
  271. }
  272. return $status;
  273. }
  274. /**
  275. * Renames a file. If $new_file already exists, it will first unlink it and then rename it.
  276. * used in SugarLogger.php
  277. * @param string $old_filename
  278. * @param string $new_filename
  279. */
  280. function sugar_rename( $old_filename, $new_filename){
  281. if (empty($old_filename) || empty($new_filename)) return false;
  282. $success = false;
  283. if(file_exists($new_filename)) {
  284. unlink($new_filename);
  285. $success = rename($old_filename, $new_filename);
  286. }
  287. else {
  288. $success = rename($old_filename, $new_filename);
  289. }
  290. return $success;
  291. }
  292. function fileToHash($file){
  293. $hash = md5($file);
  294. $_SESSION['file2Hash'][$hash] = $file;
  295. return $hash;
  296. }
  297. function hashToFile($hash){
  298. if(!empty($_SESSION['file2Hash'][$hash])){
  299. return $_SESSION['file2Hash'][$hash];
  300. }
  301. return false;
  302. }
  303. /**
  304. * get_file_extension
  305. * This function returns the file extension portion of a given filename
  306. *
  307. * @param $filename String of filename to return extension
  308. * @param $string_to_lower boolean value indicating whether or not to return value as lowercase, true by default
  309. *
  310. * @return extension String value, blank if no extension found
  311. */
  312. function get_file_extension($filename, $string_to_lower=true)
  313. {
  314. if(strpos($filename, '.') !== false)
  315. {
  316. return $string_to_lower ? strtolower(array_pop(explode('.',$filename))) : array_pop(explode('.',$filename));
  317. }
  318. return '';
  319. }
  320. /**
  321. * get_mime_content_type_from_filename
  322. * This function is similar to mime_content_type, but does not require a real
  323. * file or path location. Instead, the function merely checks the filename
  324. * extension and returns a best guess mime content type.
  325. *
  326. * @param $filename String of filename to return mime content type
  327. * @return mime content type as String value (defaults to 'application/octet-stream' for filenames with extension, empty otherwise)
  328. *
  329. */
  330. function get_mime_content_type_from_filename($filename)
  331. {
  332. if(strpos($filename, '.') !== false)
  333. {
  334. $mime_types = array(
  335. 'txt' => 'text/plain',
  336. 'htm' => 'text/html',
  337. 'html' => 'text/html',
  338. 'php' => 'text/html',
  339. 'css' => 'text/css',
  340. 'js' => 'application/javascript',
  341. 'json' => 'application/json',
  342. 'xml' => 'application/xml',
  343. 'swf' => 'application/x-shockwave-flash',
  344. 'flv' => 'video/x-flv',
  345. // images
  346. 'png' => 'image/png',
  347. 'jpe' => 'image/jpeg',
  348. 'jpeg' => 'image/jpeg',
  349. 'jpg' => 'image/jpeg',
  350. 'gif' => 'image/gif',
  351. 'bmp' => 'image/bmp',
  352. 'ico' => 'image/vnd.microsoft.icon',
  353. 'tiff' => 'image/tiff',
  354. 'tif' => 'image/tiff',
  355. 'svg' => 'image/svg+xml',
  356. 'svgz' => 'image/svg+xml',
  357. // archives
  358. 'zip' => 'application/zip',
  359. 'rar' => 'application/x-rar-compressed',
  360. 'exe' => 'application/x-msdownload',
  361. 'msi' => 'application/x-msdownload',
  362. 'cab' => 'application/vnd.ms-cab-compressed',
  363. // audio/video
  364. 'mp3' => 'audio/mpeg',
  365. 'qt' => 'video/quicktime',
  366. 'mov' => 'video/quicktime',
  367. // adobe
  368. 'pdf' => 'application/pdf',
  369. 'psd' => 'image/vnd.adobe.photoshop',
  370. 'ai' => 'application/postscript',
  371. 'eps' => 'application/postscript',
  372. 'ps' => 'application/postscript',
  373. // ms office
  374. 'doc' => 'application/msword',
  375. 'rtf' => 'application/rtf',
  376. 'xls' => 'application/vnd.ms-excel',
  377. 'ppt' => 'application/vnd.ms-powerpoint',
  378. // open office
  379. 'odt' => 'application/vnd.oasis.opendocument.text',
  380. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  381. );
  382. $ext = strtolower(array_pop(explode('.',$filename)));
  383. if (array_key_exists($ext, $mime_types)) {
  384. return $mime_types[$ext];
  385. }
  386. return 'application/octet-stream';
  387. }
  388. return '';
  389. }
  390. function createFTSLogicHook($filePath = 'application/Ext/LogicHooks/logichooks.ext.php')
  391. {
  392. $customFileLoc = create_custom_directory($filePath);
  393. $fp = sugar_fopen($customFileLoc, 'wb');
  394. $contents = <<<CIA
  395. <?php
  396. if (!isset(\$hook_array) || !is_array(\$hook_array)) {
  397. \$hook_array = array();
  398. }
  399. if (!isset(\$hook_array['after_save']) || !is_array(\$hook_array['after_save'])) {
  400. \$hook_array['after_save'] = array();
  401. }
  402. \$hook_array['after_save'][] = array(1, 'fts', 'include/SugarSearchEngine/SugarSearchEngineQueueManager.php', 'SugarSearchEngineQueueManager', 'populateIndexQueue');
  403. CIA;
  404. fwrite($fp,$contents);
  405. fclose($fp);
  406. }
  407. function cleanFileName($name)
  408. {
  409. return preg_replace('/[^\w-._]+/i', '', $name);
  410. }
  411. /**
  412. * Filter dir name to not contain path components - no slashes, no .., etc.
  413. * @param string $name
  414. * @return string
  415. */
  416. function cleanDirName($name)
  417. {
  418. return str_replace(array("\\", "/", "."), "", $name);
  419. }