]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/utils/file_utils.php
Release 6.4.0
[Github/sugarcrm.git] / include / utils / file_utils.php
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-2011 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
38
39 require_once('include/utils/array_utils.php');
40 require_once('include/utils/sugar_file_utils.php');
41
42 /**
43  * Convert all \ to / in path, remove multiple '/'s and '/./'
44  * @param string $path
45  * @return string
46  */
47 function clean_path( $path )
48 {
49     // clean directory/file path with a functional equivalent
50     $appendpath = '';
51     if ( is_windows() && strlen($path) >= 2 && $path[0].$path[1] == "\\\\" ) {
52         $path = substr($path,2);
53         $appendpath = "\\\\";
54     }
55     $path = str_replace( "\\", "/", $path );
56     $path = str_replace( "//", "/", $path );
57     $path = str_replace( "/./", "/", $path );
58     return( $appendpath.$path );
59 }
60
61 function create_cache_directory($file)
62 {
63     $paths = explode('/',$file);
64     $dir = rtrim($GLOBALS['sugar_config']['cache_dir'], '/\\');
65     if(!file_exists($dir))
66     {
67         sugar_mkdir($dir, 0775);
68     }
69     for($i = 0; $i < sizeof($paths) - 1; $i++)
70     {
71         $dir .= '/' . $paths[$i];
72         if(!file_exists($dir))
73         {
74             sugar_mkdir($dir, 0775);
75         }
76     }
77     return $dir . '/'. $paths[sizeof($paths) - 1];
78 }
79
80 function get_module_dir_list()
81 {
82         $modules = array();
83         $path = 'modules';
84         $d = dir($path);
85         while($entry = $d->read())
86         {
87                 if($entry != '..' && $entry != '.')
88                 {
89                         if(is_dir($path. '/'. $entry))
90                         {
91                                 $modules[$entry] = $entry;
92                         }
93                 }
94         }
95         return $modules;
96 }
97
98 function mk_temp_dir( $base_dir, $prefix="" )
99 {
100     $temp_dir = tempnam( $base_dir, $prefix );
101     if( !$temp_dir || !unlink( $temp_dir ) )
102     {
103         return( false );
104     }
105
106     if( sugar_mkdir( $temp_dir ) ){
107         return( $temp_dir );
108     }
109
110     return( false );
111 }
112
113 function remove_file_extension( $filename )
114 {
115     return( substr( $filename, 0, strrpos($filename, ".") ) );
116 }
117
118 function write_array_to_file( $the_name, $the_array, $the_file, $mode="w", $header='' )
119 {
120     if(!empty($header) && ($mode != 'a' || !file_exists($the_file))){
121                 $the_string = $header;
122         }else{
123         $the_string =   "<?php\n" .
124                     '// created: ' . date('Y-m-d H:i:s') . "\n";
125         }
126     $the_string .=  "\$$the_name = " .
127                     var_export_helper( $the_array ) .
128                     ";";
129
130     return sugar_file_put_contents($the_file, $the_string, LOCK_EX) !== false;
131 }
132
133 function write_encoded_file( $soap_result, $write_to_dir, $write_to_file="" )
134 {
135     // this function dies when encountering an error -- use with caution!
136     // the path/file is returned upon success
137
138
139
140     if( $write_to_file == "" )
141     {
142         $write_to_file = $write_to_dir . "/" . $soap_result['filename'];
143     }
144
145     $file = $soap_result['data'];
146     $write_to_file = str_replace( "\\", "/", $write_to_file );
147
148     $dir_to_make = dirname( $write_to_file );
149     if( !is_dir( $dir_to_make ) )
150     {
151         mkdir_recursive( $dir_to_make );
152     }
153     $fh = sugar_fopen( $write_to_file, "wb" );
154     fwrite( $fh, base64_decode( $file ) );
155     fclose( $fh );
156
157     if( md5_file( $write_to_file ) != $soap_result['md5'] )
158     {
159         die( "MD5 error after writing file $write_to_file" );
160     }
161     return( $write_to_file );
162 }
163
164 function create_custom_directory($file)
165 {
166     $paths = explode('/',$file);
167     $dir = 'custom';
168     if(!file_exists($dir))
169     {
170         sugar_mkdir($dir, 0755);
171     }
172     for($i = 0; $i < sizeof($paths) - 1; $i++)
173     {
174         $dir .= '/' . $paths[$i];
175         if(!file_exists($dir))
176         {
177             sugar_mkdir($dir, 0755);
178         }
179     }
180     return $dir . '/'. $paths[sizeof($paths) - 1];
181 }
182
183 /**
184  * This function will recursively generates md5s of files and returns an array of all md5s.
185  *
186  * @param       $path The path of the root directory to scan - must end with '/'
187  * @param       $ignore_dirs array of filenames/directory names to ignore running md5 on - default 'cache' and 'upload'
188  * @result      $md5_array an array containing path as key and md5 as value
189  */
190 function generateMD5array($path, $ignore_dirs = array('cache', 'upload'))
191 {
192         $dh  = opendir($path);
193         while (false !== ($filename = readdir($dh)))
194         {
195                 $current_dir_content[] = $filename;
196         }
197
198         // removes the ignored directories
199         $current_dir_content = array_diff($current_dir_content, $ignore_dirs);
200
201         sort($current_dir_content);
202         $md5_array = array();
203
204         foreach($current_dir_content as $file)
205         {
206                 // make sure that it's not dir '.' or '..'
207                 if(strcmp($file, ".") && strcmp($file, ".."))
208                 {
209                         if(is_dir($path.$file))
210                         {
211                                 // For testing purposes - uncomment to see all files and md5s
212                                 //echo "<BR>Dir:  ".$path.$file."<br>";
213                                 //generateMD5array($path.$file."/");
214
215                                 $md5_array += generateMD5array($path.$file."/", $ignore_dirs);
216                         }
217                         else
218                         {
219                                 // For testing purposes - uncomment to see all files and md5s
220                                 //echo "   File: ".$path.$file."<br>";
221                                 //echo md5_file($path.$file)."<BR>";
222
223                                 $md5_array[$path.$file] = md5_file($path.$file);
224                         }
225                 }
226         }
227
228         return $md5_array;
229
230 }
231
232 /**
233  * Function to compare two directory structures and return the items in path_a that didn't match in path_b
234  *
235  * @param       $path_a The path of the first root directory to scan - must end with '/'
236  * @param       $path_b The path of the second root directory to scan - must end with '/'
237  * @param       $ignore_dirs array of filenames/directory names to ignore running md5 on - default 'cache' and 'upload'
238  * @result      array containing all the md5s of everything in $path_a that didn't have a match in $path_b
239  */
240 function md5DirCompare($path_a, $path_b, $ignore_dirs = array('cache', 'upload'))
241 {
242         $md5array_a = generateMD5array($path_a, $ignore_dirs);
243         $md5array_b = generateMD5array($path_b, $ignore_dirs);
244
245         $result = array_diff($md5array_a, $md5array_b);
246
247         return $result;
248 }
249
250 /**
251  * Function to retrieve all file names of matching pattern in a directory (and it's subdirectories)
252  * example: getFiles($arr, './modules', '.+/EditView.php/'); // grabs all EditView.phps
253  * @param array $arr return array to populate matches
254  * @param string $dir directory to look in [ USE ./ in front of the $dir! ]
255  * @param regex $pattern optional pattern to match against
256  */
257 function getFiles(&$arr, $dir, $pattern = null) {
258         if(!is_dir($dir))return;
259         $d = dir($dir);
260         while($e =$d->read()){
261                 if(substr($e, 0, 1) == '.')continue;
262                 $file = $dir . '/' . $e;
263                 if(is_dir($file)){
264                         getFiles($arr, $file, $pattern);
265                 }else{
266                         if(empty($pattern)) $arr[] = $file;
267                 else if(preg_match($pattern, $file))
268                 $arr[] = $file;
269                 }
270         }
271 }
272
273 /**
274  * Function to split up large files for download
275  * used in download.php
276  * @param string $filename
277  * @param int $retbytes
278  */
279 function readfile_chunked($filename,$retbytes=true)
280 {
281         $chunksize = 1*(1024*1024); // how many bytes per chunk
282         $buffer = '';
283         $cnt = 0;
284         $handle = sugar_fopen($filename, 'rb');
285         if ($handle === false)
286         {
287             return false;
288         }
289         while (!feof($handle))
290         {
291             $buffer = fread($handle, $chunksize);
292             echo $buffer;
293             flush();
294             if ($retbytes)
295             {
296                 $cnt += strlen($buffer);
297             }
298         }
299             $status = fclose($handle);
300         if ($retbytes && $status)
301         {
302             return $cnt; // return num. bytes delivered like readfile() does.
303         }
304         return $status;
305 }
306 /**
307  * Renames a file. If $new_file already exists, it will first unlink it and then rename it.
308  * used in SugarLogger.php
309  * @param string $old_filename
310  * @param string $new_filename
311  */
312 function sugar_rename( $old_filename, $new_filename){
313         if (empty($old_filename) || empty($new_filename)) return false;
314         $success = false;
315         if(file_exists($new_filename)) {
316         unlink($new_filename);
317         $success = rename($old_filename, $new_filename);
318         }
319         else {
320                 $success = rename($old_filename, $new_filename);
321         }
322
323         return $success;
324 }
325
326 function fileToHash($file){
327                 $hash = md5($file);
328                 $_SESSION['file2Hash'][$hash] = $file;
329                 return $hash;
330         }
331
332 function hashToFile($hash){
333                 if(!empty($_SESSION['file2Hash'][$hash])){
334                         return $_SESSION['file2Hash'][$hash];
335                 }
336                 return false;
337 }
338
339
340
341 /**
342  * get_file_extension
343  * This function returns the file extension portion of a given filename
344  *
345  * @param $filename String of filename to return extension
346  * @param $string_to_lower boolean value indicating whether or not to return value as lowercase, true by default
347  *
348  * @return extension String value, blank if no extension found
349  */
350 function get_file_extension($filename, $string_to_lower=true)
351 {
352     if(strpos($filename, '.') !== false)
353     {
354        return $string_to_lower ? strtolower(array_pop(explode('.',$filename))) : array_pop(explode('.',$filename));
355     }
356
357     return '';
358 }
359
360
361 /**
362  * get_mime_content_type_from_filename
363  * This function is similar to mime_content_type, but does not require a real
364  * file or path location.  Instead, the function merely checks the filename
365  * extension and returns a best guess mime content type.
366  *
367  * @param $filename String of filename to return mime content type
368  * @return mime content type as String value (defaults to 'application/octet-stream' for filenames with extension, empty otherwise)
369  *
370  */
371 function get_mime_content_type_from_filename($filename)
372 {
373         if(strpos($filename, '.') !== false)
374         {
375         $mime_types = array(
376             'txt' => 'text/plain',
377             'htm' => 'text/html',
378             'html' => 'text/html',
379             'php' => 'text/html',
380             'css' => 'text/css',
381             'js' => 'application/javascript',
382             'json' => 'application/json',
383             'xml' => 'application/xml',
384             'swf' => 'application/x-shockwave-flash',
385             'flv' => 'video/x-flv',
386
387             // images
388             'png' => 'image/png',
389             'jpe' => 'image/jpeg',
390             'jpeg' => 'image/jpeg',
391             'jpg' => 'image/jpeg',
392             'gif' => 'image/gif',
393             'bmp' => 'image/bmp',
394             'ico' => 'image/vnd.microsoft.icon',
395             'tiff' => 'image/tiff',
396             'tif' => 'image/tiff',
397             'svg' => 'image/svg+xml',
398             'svgz' => 'image/svg+xml',
399
400             // archives
401             'zip' => 'application/zip',
402             'rar' => 'application/x-rar-compressed',
403             'exe' => 'application/x-msdownload',
404             'msi' => 'application/x-msdownload',
405             'cab' => 'application/vnd.ms-cab-compressed',
406
407             // audio/video
408             'mp3' => 'audio/mpeg',
409             'qt' => 'video/quicktime',
410             'mov' => 'video/quicktime',
411
412             // adobe
413             'pdf' => 'application/pdf',
414             'psd' => 'image/vnd.adobe.photoshop',
415             'ai' => 'application/postscript',
416             'eps' => 'application/postscript',
417             'ps' => 'application/postscript',
418
419             // ms office
420             'doc' => 'application/msword',
421             'rtf' => 'application/rtf',
422             'xls' => 'application/vnd.ms-excel',
423             'ppt' => 'application/vnd.ms-powerpoint',
424
425             // open office
426             'odt' => 'application/vnd.oasis.opendocument.text',
427             'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
428         );
429
430         $ext = strtolower(array_pop(explode('.',$filename)));
431         if (array_key_exists($ext, $mime_types)) {
432             return $mime_types[$ext];
433         }
434
435         return 'application/octet-stream';
436         }
437
438     return '';
439 }
440
441 function cleanFileName($name)
442 {
443     return preg_replace('/[^\w-._]+/i', '', $name);
444 }