]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/utils/file_utils.php
Release 6.1.5
[Github/sugarcrm.git] / include / utils / file_utils.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM 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                     ";\n?>\n";
124
125     if( $fh = @sugar_fopen( $the_file, $mode ) )
126     {
127         fputs( $fh, $the_string);
128         fclose( $fh );
129         return( true );
130     }
131     else
132     {
133         return( false );
134     }
135
136 }
137
138 function write_encoded_file( $soap_result, $write_to_dir, $write_to_file="" )
139 {
140     // this function dies when encountering an error -- use with caution!
141     // the path/file is returned upon success
142
143     
144
145     if( $write_to_file == "" )
146     {
147         $write_to_file = $write_to_dir . "/" . $soap_result['filename'];
148     }
149
150     $file = $soap_result['data'];
151     $write_to_file = str_replace( "\\", "/", $write_to_file );
152
153     $dir_to_make = dirname( $write_to_file );
154     if( !is_dir( $dir_to_make ) )
155     {
156         mkdir_recursive( $dir_to_make );
157     }
158     $fh = sugar_fopen( $write_to_file, "wb" );
159     fwrite( $fh, base64_decode( $file ) );
160     fclose( $fh );
161
162     if( md5_file( $write_to_file ) != $soap_result['md5'] )
163     {
164         die( "MD5 error after writing file $write_to_file" );
165     }
166     return( $write_to_file );
167 }
168
169 function create_custom_directory($file)
170 {
171     $paths = explode('/',$file);
172     $dir = 'custom';
173     if(!file_exists($dir))
174     {
175         sugar_mkdir($dir, 0755);
176     }
177     for($i = 0; $i < sizeof($paths) - 1; $i++)
178     {
179         $dir .= '/' . $paths[$i];
180         if(!file_exists($dir))
181         {
182             sugar_mkdir($dir, 0755);
183         }
184     }
185     return $dir . '/'. $paths[sizeof($paths) - 1];
186 }
187
188 /**
189  * This function will recursively generates md5s of files and returns an array of all md5s.
190  *
191  * @param       $path The path of the root directory to scan - must end with '/'
192  * @param       $ignore_dirs array of filenames/directory names to ignore running md5 on - default 'cache' and 'upload'
193  * @result      $md5_array an array containing path as key and md5 as value
194  */
195 function generateMD5array($path, $ignore_dirs = array('cache', 'upload'))
196 {
197         $dh  = opendir($path);
198         while (false !== ($filename = readdir($dh)))
199         {
200                 $current_dir_content[] = $filename;
201         }
202
203         // removes the ignored directories
204         $current_dir_content = array_diff($current_dir_content, $ignore_dirs);
205
206         sort($current_dir_content);
207         $md5_array = array();
208
209         foreach($current_dir_content as $file)
210         {
211                 // make sure that it's not dir '.' or '..'
212                 if(strcmp($file, ".") && strcmp($file, ".."))
213                 {
214                         if(is_dir($path.$file))
215                         {
216                                 // For testing purposes - uncomment to see all files and md5s
217                                 //echo "<BR>Dir:  ".$path.$file."<br>";
218                                 //generateMD5array($path.$file."/");
219
220                                 $md5_array += generateMD5array($path.$file."/", $ignore_dirs);
221                         }
222                         else
223                         {
224                                 // For testing purposes - uncomment to see all files and md5s
225                                 //echo "   File: ".$path.$file."<br>";
226                                 //echo md5_file($path.$file)."<BR>";
227
228                                 $md5_array[$path.$file] = md5_file($path.$file);
229                         }
230                 }
231         }
232
233         return $md5_array;
234
235 }
236
237 /**
238  * Function to compare two directory structures and return the items in path_a that didn't match in path_b
239  *
240  * @param       $path_a The path of the first root directory to scan - must end with '/'
241  * @param       $path_b The path of the second root directory to scan - must end with '/'
242  * @param       $ignore_dirs array of filenames/directory names to ignore running md5 on - default 'cache' and 'upload'
243  * @result      array containing all the md5s of everything in $path_a that didn't have a match in $path_b
244  */
245 function md5DirCompare($path_a, $path_b, $ignore_dirs = array('cache', 'upload'))
246 {
247         $md5array_a = generateMD5array($path_a, $ignore_dirs);
248         $md5array_b = generateMD5array($path_b, $ignore_dirs);
249
250         $result = array_diff($md5array_a, $md5array_b);
251
252         return $result;
253 }
254
255 /**
256  * Function to retrieve all file names of matching pattern in a directory (and it's subdirectories)
257  * example: getFiles($arr, './modules', '.+/EditView.php/'); // grabs all EditView.phps
258  * @param array $arr return array to populate matches
259  * @param string $dir directory to look in [ USE ./ in front of the $dir! ]
260  * @param regex $pattern optional pattern to match against
261  */
262 function getFiles(&$arr, $dir, $pattern = null) {
263         if(!is_dir($dir))return;
264         $d = dir($dir);
265         while($e =$d->read()){
266                 if(substr($e, 0, 1) == '.')continue;
267                 $file = $dir . '/' . $e;
268                 if(is_dir($file)){
269                         getFiles($arr, $file, $pattern);
270                 }else{
271                         if(empty($pattern)) $arr[] = $file;
272                 else if(preg_match($pattern, $file))
273                 $arr[] = $file;
274                 }
275         }
276 }
277
278 /**
279  * Function to split up large files for download
280  * used in download.php
281  * @param string $filename
282  * @param int $retbytes
283  */
284 function readfile_chunked($filename,$retbytes=true)
285 {
286         $chunksize = 1*(1024*1024); // how many bytes per chunk
287         $buffer = '';
288         $cnt = 0;
289         $handle = sugar_fopen($filename, 'rb');
290         if ($handle === false)
291         {
292             return false;
293         }
294         while (!feof($handle))
295         {
296             $buffer = fread($handle, $chunksize);
297             echo $buffer;
298             flush();
299             if ($retbytes)
300             {
301                 $cnt += strlen($buffer);
302             }
303         }
304             $status = fclose($handle);
305         if ($retbytes && $status)
306         {
307             return $cnt; // return num. bytes delivered like readfile() does.
308         }
309         return $status;
310 }
311 /**
312  * Renames a file. If $new_file already exists, it will first unlink it and then rename it.
313  * used in SugarLogger.php
314  * @param string $old_filename
315  * @param string $new_filename
316  */
317 function sugar_rename( $old_filename, $new_filename){
318         if (empty($old_filename) || empty($new_filename)) return false;
319         $success = false;
320         if(file_exists($new_filename)) {
321         unlink($new_filename);
322         $success = rename($old_filename, $new_filename);
323         }
324         else {
325                 $success = rename($old_filename, $new_filename);
326         }
327
328         return $success;
329 }
330
331 function fileToHash($file){
332                 $hash = md5($file);
333                 $_SESSION['file2Hash'][$hash] = $file;
334                 return $hash;
335         }
336         
337 function hashToFile($hash){
338                 if(!empty($_SESSION['file2Hash'][$hash])){
339                         return $_SESSION['file2Hash'][$hash];
340                 }
341                 return false;
342 }
343         
344
345 function cleanFileName($name)
346 {
347     return preg_replace('/[^\w-._]+/i', '', $name);
348 }
349
350 ?>