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