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.
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.
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
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
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.
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.
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 ********************************************************************************/
39 require_once('include/utils/array_utils.php');
40 require_once('include/utils/sugar_file_utils.php');
43 * Convert all \ to / in path, remove multiple '/'s and '/./'
47 function clean_path( $path )
49 // clean directory/file path with a functional equivalent
51 if ( is_windows() && strlen($path) >= 2 && $path[0].$path[1] == "\\\\" ) {
52 $path = substr($path,2);
55 $path = str_replace( "\\", "/", $path );
56 $path = str_replace( "//", "/", $path );
57 $path = str_replace( "/./", "/", $path );
58 return( $appendpath.$path );
61 function create_cache_directory($file)
63 $paths = explode('/',$file);
64 $dir = rtrim($GLOBALS['sugar_config']['cache_dir'], '/\\');
65 if(!file_exists($dir))
67 sugar_mkdir($dir, 0775);
69 for($i = 0; $i < sizeof($paths) - 1; $i++)
71 $dir .= '/' . $paths[$i];
72 if(!file_exists($dir))
74 sugar_mkdir($dir, 0775);
77 return $dir . '/'. $paths[sizeof($paths) - 1];
80 function get_module_dir_list()
85 while($entry = $d->read())
87 if($entry != '..' && $entry != '.')
89 if(is_dir($path. '/'. $entry))
91 $modules[$entry] = $entry;
98 function mk_temp_dir( $base_dir, $prefix="" )
100 $temp_dir = tempnam( $base_dir, $prefix );
101 if( !$temp_dir || !unlink( $temp_dir ) )
106 if( sugar_mkdir( $temp_dir ) ){
113 function remove_file_extension( $filename )
115 return( substr( $filename, 0, strrpos($filename, ".") ) );
118 function write_array_to_file( $the_name, $the_array, $the_file, $mode="w", $header='' )
120 if(!empty($header) && ($mode != 'a' || !file_exists($the_file))){
121 $the_string = $header;
123 $the_string = "<?php\n" .
124 '// created: ' . date('Y-m-d H:i:s') . "\n";
126 $the_string .= "\$$the_name = " .
127 var_export_helper( $the_array ) .
130 return sugar_file_put_contents($the_file, $the_string, LOCK_EX) !== false;
133 function write_encoded_file( $soap_result, $write_to_dir, $write_to_file="" )
135 // this function dies when encountering an error -- use with caution!
136 // the path/file is returned upon success
140 if( $write_to_file == "" )
142 $write_to_file = $write_to_dir . "/" . $soap_result['filename'];
145 $file = $soap_result['data'];
146 $write_to_file = str_replace( "\\", "/", $write_to_file );
148 $dir_to_make = dirname( $write_to_file );
149 if( !is_dir( $dir_to_make ) )
151 mkdir_recursive( $dir_to_make );
153 $fh = sugar_fopen( $write_to_file, "wb" );
154 fwrite( $fh, base64_decode( $file ) );
157 if( md5_file( $write_to_file ) != $soap_result['md5'] )
159 die( "MD5 error after writing file $write_to_file" );
161 return( $write_to_file );
164 function create_custom_directory($file)
166 $paths = explode('/',$file);
168 if(!file_exists($dir))
170 sugar_mkdir($dir, 0755);
172 for($i = 0; $i < sizeof($paths) - 1; $i++)
174 $dir .= '/' . $paths[$i];
175 if(!file_exists($dir))
177 sugar_mkdir($dir, 0755);
180 return $dir . '/'. $paths[sizeof($paths) - 1];
184 * This function will recursively generates md5s of files and returns an array of all md5s.
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
190 function generateMD5array($path, $ignore_dirs = array('cache', 'upload'))
192 $dh = opendir($path);
193 while (false !== ($filename = readdir($dh)))
195 $current_dir_content[] = $filename;
198 // removes the ignored directories
199 $current_dir_content = array_diff($current_dir_content, $ignore_dirs);
201 sort($current_dir_content);
202 $md5_array = array();
204 foreach($current_dir_content as $file)
206 // make sure that it's not dir '.' or '..'
207 if(strcmp($file, ".") && strcmp($file, ".."))
209 if(is_dir($path.$file))
211 // For testing purposes - uncomment to see all files and md5s
212 //echo "<BR>Dir: ".$path.$file."<br>";
213 //generateMD5array($path.$file."/");
215 $md5_array += generateMD5array($path.$file."/", $ignore_dirs);
219 // For testing purposes - uncomment to see all files and md5s
220 //echo " File: ".$path.$file."<br>";
221 //echo md5_file($path.$file)."<BR>";
223 $md5_array[$path.$file] = md5_file($path.$file);
233 * Function to compare two directory structures and return the items in path_a that didn't match in path_b
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
240 function md5DirCompare($path_a, $path_b, $ignore_dirs = array('cache', 'upload'))
242 $md5array_a = generateMD5array($path_a, $ignore_dirs);
243 $md5array_b = generateMD5array($path_b, $ignore_dirs);
245 $result = array_diff($md5array_a, $md5array_b);
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
257 function getFiles(&$arr, $dir, $pattern = null) {
258 if(!is_dir($dir))return;
260 while($e =$d->read()){
261 if(substr($e, 0, 1) == '.')continue;
262 $file = $dir . '/' . $e;
264 getFiles($arr, $file, $pattern);
266 if(empty($pattern)) $arr[] = $file;
267 else if(preg_match($pattern, $file))
274 * Function to split up large files for download
275 * used in download.php
276 * @param string $filename
277 * @param int $retbytes
279 function readfile_chunked($filename,$retbytes=true)
281 $chunksize = 1*(1024*1024); // how many bytes per chunk
284 $handle = sugar_fopen($filename, 'rb');
285 if ($handle === false)
289 while (!feof($handle))
291 $buffer = fread($handle, $chunksize);
296 $cnt += strlen($buffer);
299 $status = fclose($handle);
300 if ($retbytes && $status)
302 return $cnt; // return num. bytes delivered like readfile() does.
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
312 function sugar_rename( $old_filename, $new_filename){
313 if (empty($old_filename) || empty($new_filename)) return false;
315 if(file_exists($new_filename)) {
316 unlink($new_filename);
317 $success = rename($old_filename, $new_filename);
320 $success = rename($old_filename, $new_filename);
326 function fileToHash($file){
328 $_SESSION['file2Hash'][$hash] = $file;
332 function hashToFile($hash){
333 if(!empty($_SESSION['file2Hash'][$hash])){
334 return $_SESSION['file2Hash'][$hash];
343 * This function returns the file extension portion of a given filename
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
348 * @return extension String value, blank if no extension found
350 function get_file_extension($filename, $string_to_lower=true)
352 if(strpos($filename, '.') !== false)
354 return $string_to_lower ? strtolower(array_pop(explode('.',$filename))) : array_pop(explode('.',$filename));
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.
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)
371 function get_mime_content_type_from_filename($filename)
373 if(strpos($filename, '.') !== false)
376 'txt' => 'text/plain',
377 'htm' => 'text/html',
378 'html' => 'text/html',
379 'php' => 'text/html',
381 'js' => 'application/javascript',
382 'json' => 'application/json',
383 'xml' => 'application/xml',
384 'swf' => 'application/x-shockwave-flash',
385 'flv' => 'video/x-flv',
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',
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',
408 'mp3' => 'audio/mpeg',
409 'qt' => 'video/quicktime',
410 'mov' => 'video/quicktime',
413 'pdf' => 'application/pdf',
414 'psd' => 'image/vnd.adobe.photoshop',
415 'ai' => 'application/postscript',
416 'eps' => 'application/postscript',
417 'ps' => 'application/postscript',
420 'doc' => 'application/msword',
421 'rtf' => 'application/rtf',
422 'xls' => 'application/vnd.ms-excel',
423 'ppt' => 'application/vnd.ms-powerpoint',
426 'odt' => 'application/vnd.oasis.opendocument.text',
427 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
430 $ext = strtolower(array_pop(explode('.',$filename)));
431 if (array_key_exists($ext, $mime_types)) {
432 return $mime_types[$ext];
435 return 'application/octet-stream';
441 function createFTSLogicHook($filePath = 'application/Ext/LogicHooks/logichooks.ext.php')
443 $customFileLoc = create_custom_directory($filePath);
444 $fp = sugar_fopen($customFileLoc, 'wb');
447 if (!isset(\$hook_array) || !is_array(\$hook_array)) {
448 \$hook_array = array();
450 if (!isset(\$hook_array['after_save']) || !is_array(\$hook_array['after_save'])) {
451 \$hook_array['after_save'] = array();
453 \$hook_array['after_save'][] = array(1, 'fts', 'include/SugarSearchEngine/SugarSearchEngineQueueManager.php', 'SugarSearchEngineQueueManager', 'populateIndexQueue');
456 fwrite($fp,$contents);
461 function cleanFileName($name)
463 return preg_replace('/[^\w-._]+/i', '', $name);