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 ********************************************************************************/
38 /*********************************************************************************
41 ********************************************************************************/
42 require_once('include/externalAPI/ExternalAPIFactory.php');
46 * Manage uploaded files
51 var $stored_file_name;
52 var $original_file_name;
53 var $temp_file_location;
54 var $use_soap = false;
57 protected static $url = "upload/";
63 protected static $filesError = array(
64 UPLOAD_ERR_OK => 'UPLOAD_ERR_OK - There is no error, the file uploaded with success.',
65 UPLOAD_ERR_INI_SIZE => 'UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini.',
66 UPLOAD_ERR_FORM_SIZE => 'UPLOAD_ERR_FORM_SIZE - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
67 UPLOAD_ERR_PARTIAL => 'UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.',
68 UPLOAD_ERR_NO_FILE => 'UPLOAD_ERR_NO_FILE - No file was uploaded.',
70 UPLOAD_ERR_NO_TMP_DIR => 'UPLOAD_ERR_NO_TMP_DIR - Missing a temporary folder.',
71 UPLOAD_ERR_CANT_WRITE => 'UPLOAD_ERR_CANT_WRITE - Failed to write file to disk.',
72 UPLOAD_ERR_EXTENSION => 'UPLOAD_ERR_EXTENSION - A PHP extension stopped the file upload.',
76 * Create upload file handler
77 * @param string $field_name Form field name
79 function UploadFile ($field_name = '')
81 // $field_name is the name of your passed file selector field in your form
82 // i.e., for Emails, it is "email_attachmentX" where X is 0-9
83 $this->field_name = $field_name;
87 * Setup for SOAP upload
88 * @param string $filename Name for the file
91 function set_for_soap($filename, $file) {
92 $this->stored_file_name = $filename;
93 $this->use_soap = true;
98 * Get URL for a document
100 * @param string stored_file_name File name in filesystem
101 * @param string bean_id note bean ID
102 * @return string path with file name
104 public static function get_url($stored_file_name, $bean_id)
106 if ( empty($bean_id) && empty($stored_file_name) ) {
110 return self::$url . $bean_id;
114 * Get URL of the uploaded file related to the document
115 * @param SugarBean $document
116 * @param string $type Type of the document, if different from $document
118 public static function get_upload_url($document, $type = null)
121 $type = $document->module_dir;
123 return "index.php?entryPoint=download&type=$type&id={$document->id}";
127 * Try renaming a file to bean_id name
128 * @param string $filename
129 * @param string $bean_id
131 protected static function tryRename($filename, $bean_id)
133 $fullname = "upload://$bean_id.$filename";
134 if(file_exists($fullname)) {
135 if(!rename($fullname, "upload://$bean_id")) {
136 $GLOBALS['log']->fatal("unable to rename file: $fullname => $bean_id");
144 * builds a URL path for an anchor tag
145 * @param string stored_file_name File name in filesystem
146 * @param string bean_id note bean ID
147 * @return string path with file name
149 static public function get_file_path($stored_file_name, $bean_id, $skip_rename = false)
153 // if the parameters are empty strings, just return back the upload_dir
154 if ( empty($bean_id) && empty($stored_file_name) ) {
159 self::tryRename(rawurlencode($stored_file_name), $bean_id) ||
160 self::tryRename(urlencode($stored_file_name), $bean_id) ||
161 self::tryRename($stored_file_name, $bean_id) ||
162 self::tryRename($locale->translateCharset( $stored_file_name, 'UTF-8', $locale->getExportCharset()), $bean_id);
165 return "upload://$bean_id";
169 * duplicates an already uploaded file in the filesystem.
170 * @param string old_id ID of original note
171 * @param string new_id ID of new (copied) note
172 * @param string filename Filename of file (deprecated)
174 public static function duplicate_file($old_id, $new_id, $file_name)
176 global $sugar_config;
178 // current file system (GUID)
179 $source = "upload://$old_id";
181 if(!file_exists($source)) {
182 // old-style file system (GUID.filename.extension)
183 $oldStyleSource = $source.$file_name;
184 if(file_exists($oldStyleSource)) {
185 // change to new style
186 if(copy($oldStyleSource, $source)) {
188 if(!unlink($oldStyleSource)) {
189 $GLOBALS['log']->error("upload_file could not unlink [ {$oldStyleSource} ]");
192 $GLOBALS['log']->error("upload_file could not copy [ {$oldStyleSource} ] to [ {$source} ]");
197 $destination = "upload://$new_id";
198 if(!copy($source, $destination)) {
199 $GLOBALS['log']->error("upload_file could not copy [ {$source} ] to [ {$destination} ]");
204 * Get upload error from system
205 * @return string upload error
207 public function get_upload_error()
209 if(isset($this->field_name) && isset($_FILES[$this->field_name]['error'])) {
210 return $_FILES[$this->field_name]['error'];
216 * standard PHP file-upload security measures. all variables accessed in a global context
217 * @return bool True on success
219 public function confirm_upload()
221 global $sugar_config;
223 if(empty($this->field_name) || !isset($_FILES[$this->field_name])) {
227 //check to see if there are any errors from upload
228 if($_FILES[$this->field_name]['error'] != UPLOAD_ERR_OK) {
229 if($_FILES[$this->field_name]['error'] != UPLOAD_ERR_NO_FILE) {
230 if($_FILES[$this->field_name]['error'] == UPLOAD_ERR_INI_SIZE) {
231 //log the error, the string produced will read something like:
232 //ERROR: There was an error during upload. Error code: 1 - UPLOAD_ERR_INI_SIZE - The uploaded file exceeds the upload_max_filesize directive in php.ini. upload_maxsize is 16
233 $errMess = string_format($GLOBALS['app_strings']['UPLOAD_ERROR_TEXT_SIZEINFO'],array($_FILES['filename_file']['error'], self::$filesError[$_FILES['filename_file']['error']],$sugar_config['upload_maxsize']));
234 $GLOBALS['log']->fatal($errMess);
236 //log the error, the string produced will read something like:
237 //ERROR: There was an error during upload. Error code: 3 - UPLOAD_ERR_PARTIAL - The uploaded file was only partially uploaded.
238 $errMess = string_format($GLOBALS['app_strings']['UPLOAD_ERROR_TEXT'],array($_FILES['filename_file']['error'], self::$filesError[$_FILES['filename_file']['error']]));
239 $GLOBALS['log']->fatal($errMess);
245 if(!is_uploaded_file($_FILES[$this->field_name]['tmp_name'])) {
247 } elseif($_FILES[$this->field_name]['size'] > $sugar_config['upload_maxsize']) {
248 $GLOBALS['log']->fatal("ERROR: uploaded file was too big: max filesize: {$sugar_config['upload_maxsize']}");
252 if(!UploadStream::writable()) {
253 $GLOBALS['log']->fatal("ERROR: cannot write to upload directory");
257 $this->mime_type = $this->getMime($_FILES[$this->field_name]);
258 $this->stored_file_name = $this->create_stored_filename();
259 $this->temp_file_location = $_FILES[$this->field_name]['tmp_name'];
265 * Guess MIME type for file
266 * @param string $filename
267 * @return string MIME type
269 function getMimeSoap($filename){
271 if( function_exists( 'ext2mime' ) )
273 $mime = ext2mime($filename);
277 $mime = ' application/octet-stream';
284 * Get MIME type for uploaded file
285 * @param array $_FILES_element $_FILES element required
286 * @return string MIME type
288 function getMime($_FILES_element)
290 $filename = $_FILES_element['name'];
291 $file_ext = pathinfo($filename, PATHINFO_EXTENSION);
293 //If no file extension is available and the mime is octet-stream try to determine the mime type.
294 $recheckMime = empty($file_ext) && ($_FILES_element['type'] == 'application/octet-stream');
296 if( $_FILES_element['type'] && !$recheckMime) {
297 $mime = $_FILES_element['type'];
298 } elseif( function_exists( 'mime_content_type' ) ) {
299 $mime = mime_content_type( $_FILES_element['tmp_name'] );
300 } elseif( function_exists( 'ext2mime' ) ) {
301 $mime = ext2mime( $_FILES_element['name'] );
303 $mime = ' application/octet-stream';
309 * gets note's filename
312 function get_stored_file_name()
314 return $this->stored_file_name;
318 * creates a file's name for preparation for saving
321 function create_stored_filename()
323 global $sugar_config;
325 if(!$this->use_soap) {
326 $stored_file_name = $_FILES[$this->field_name]['name'];
327 $this->original_file_name = $stored_file_name;
330 * cn: bug 8056 - windows filesystems and IIS do not like utf8. we are forced to urlencode() to ensure that
331 * the file is linkable from the browser. this will stay broken until we move to a db-storage system
334 // create a non UTF-8 name encoding
335 // 176 + 36 char guid = windows' maximum filename length
336 $end = (strlen($stored_file_name) > 176) ? 176 : strlen($stored_file_name);
337 $stored_file_name = substr($stored_file_name, 0, $end);
338 $this->original_file_name = $_FILES[$this->field_name]['name'];
340 $stored_file_name = str_replace("\\", "", $stored_file_name);
342 $stored_file_name = $this->stored_file_name;
343 $this->original_file_name = $stored_file_name;
346 $this->file_ext = pathinfo($stored_file_name, PATHINFO_EXTENSION);
347 // cn: bug 6347 - fix file extension detection
348 foreach($sugar_config['upload_badext'] as $badExt) {
349 if(strtolower($this->file_ext) == strtolower($badExt)) {
350 $stored_file_name .= ".txt";
351 $this->file_ext="txt";
352 break; // no need to look for more
355 return $stored_file_name;
359 * moves uploaded temp file to permanent save location
360 * @param string bean_id ID of parent bean
361 * @return bool True on success
363 function final_move($bean_id)
365 $destination = $bean_id;
366 if(substr($destination, 0, 9) != "upload://") {
367 $destination = "upload://$bean_id";
369 if($this->use_soap) {
370 if(!file_put_contents($destination, $this->file)){
371 $GLOBALS['log']->fatal("ERROR: can't save file to $destination");
375 if(!UploadStream::move_uploaded_file($_FILES[$this->field_name]['tmp_name'], $destination)) {
376 $GLOBALS['log']->fatal("ERROR: can't move_uploaded_file to $destination. You should try making the directory writable by the webserver");
384 * Upload document to external service
385 * @param SugarBean $bean Related bean
386 * @param string $bean_id
387 * @param string $doc_type
388 * @param string $file_name
389 * @param string $mime_type
391 function upload_doc($bean, $bean_id, $doc_type, $file_name, $mime_type)
393 if(!empty($doc_type)&&$doc_type!='Sugar') {
394 global $sugar_config;
395 $destination = $this->get_upload_path($bean_id);
396 sugar_rename($destination, str_replace($bean_id, $bean_id.'_'.$file_name, $destination));
397 $new_destination = $this->get_upload_path($bean_id.'_'.$file_name);
400 $this->api = ExternalAPIFactory::loadAPI($doc_type);
402 if ( isset($this->api) && $this->api !== false ) {
403 $result = $this->api->uploadDoc(
410 $result['success'] = FALSE;
412 $GLOBALS['log']->error("Could not load the requested API (".$doc_type.")");
413 $result['errorMessage'] = 'Could not find a proper API';
415 }catch(Exception $e){
416 $result['success'] = FALSE;
417 $result['errorMessage'] = $e->getMessage();
418 $GLOBALS['log']->error("Caught exception: (".$e->getMessage().") ");
420 if ( !$result['success'] ) {
421 sugar_rename($new_destination, str_replace($bean_id.'_'.$file_name, $bean_id, $new_destination));
422 $bean->doc_type = 'Sugar';
424 if ( ! is_array($_SESSION['user_error_message']) )
425 $_SESSION['user_error_message'] = array();
427 $error_message = isset($result['errorMessage']) ? $result['errorMessage'] : $GLOBALS['app_strings']['ERR_EXTERNAL_API_SAVE_FAIL'];
428 $_SESSION['user_error_message'][] = $error_message;
432 unlink($new_destination);
439 * returns the path with file name to save an uploaded file
440 * @param string bean_id ID of the parent bean
443 function get_upload_path($bean_id)
445 $file_name = $bean_id;
447 // cn: bug 8056 - mbcs filename in urlencoding > 212 chars in Windows fails
448 $end = (strlen($file_name) > 212) ? 212 : strlen($file_name);
449 $ret_file_name = substr($file_name, 0, $end);
451 return "upload://$ret_file_name";
456 * @param string bean_id ID of the parent bean
457 * @param string file_name File's name
459 static public function unlink_file($bean_id,$file_name = '')
461 if(file_exists("upload://$bean_id$file_name")) {
462 return unlink("upload://$bean_id$file_name");
467 * Get upload file location prefix
468 * @return string prefix
470 public function get_upload_dir()
476 * Return real FS path of the file
477 * @param string $path
479 public static function realpath($path)
481 if(substr($path, 0, 9) == "upload://") {
482 $path = UploadStream::path($path);
484 $ret = realpath($path);
485 return $ret?$ret:$path;
489 * Return path of uploaded file relative to uploads dir
490 * @param string $path
492 public static function relativeName($path)
494 if(substr($path, 0, 9) == "upload://") {
495 $path = substr($path, 9);
503 * Upload file stream handler
507 const STREAM_NAME = "upload";
508 protected static $upload_dir;
511 * Get upload directory
514 public static function getDir()
516 if(empty(self::$upload_dir)) {
517 self::$upload_dir = rtrim($GLOBALS['sugar_config']['upload_dir'], '/\\');
518 if(empty(self::$upload_dir)) {
519 self::$upload_dir = "upload";
521 if(!file_exists(self::$upload_dir)) {
522 sugar_mkdir(self::$upload_dir, 0755, true);
525 return self::$upload_dir;
529 * Check if upload dir is writable
532 public static function writable()
534 return is_writable(self::getDir());
538 * Register the stream
540 public function register()
542 stream_register_wrapper(self::STREAM_NAME, __CLASS__);
546 * Get real FS path of the upload stream file
547 * @param string $path Upload stream path (with upload://)
548 * @return string FS path
550 public static function path($path)
552 $path = substr($path, strlen(self::STREAM_NAME)+3); // cut off upload://
553 $path = str_replace("\\", "/", $path); // canonicalize path
554 if($path == ".." || substr($path, 0, 3) == "../" || substr($path, -3, 3) == "/.." || strstr($path, "/../")) {
555 $GLOBALS['log']->fatal("Invalid uploaded file name supplied: $path");
558 return self::getDir()."/".$path;
562 * Ensure upload subdir exists
563 * @param string $path Upload stream path (with upload://)
564 * @param bool $writable
567 public static function ensureDir($path, $writable = true)
569 $path = self::path($path);
571 return sugar_mkdir($path, 0755, true);
576 public function dir_closedir()
578 closedir($this->dirp);
581 public function dir_opendir ($path, $options )
583 $this->dirp = opendir(self::path($path));
584 return !empty($this->dirp);
587 public function dir_readdir()
589 return readdir($this->dirp);
592 public function dir_rewinddir()
594 return rewinddir($this->dirp);
597 public function mkdir($path, $mode, $options)
599 return mkdir(self::path($path), $mode, ($options&STREAM_MKDIR_RECURSIVE) != 0);
602 public function rename($path_from, $path_to)
604 return rename(self::path($path_from), self::path($path_to));
607 public function rmdir($path, $options)
609 return rmdir(self::path($path));
612 public function stream_cast ($cast_as)
617 public function stream_close ()
623 public function stream_eof ()
625 return feof($this->fp);
627 public function stream_flush ()
629 return fflush($this->fp);
632 public function stream_lock($operation)
634 return flock($this->fp, $operation);
637 public function stream_open($path, $mode)
639 $fullpath = self::path($path);
640 if(empty($fullpath)) return false;
642 $this->fp = fopen($fullpath, $mode);
644 // if we will be writing, try to transparently create the directory
645 $this->fp = @fopen($fullpath, $mode);
646 if(!$this->fp && !file_exists(dirname($fullpath))) {
647 mkdir(dirname($fullpath), 0755, true);
648 $this->fp = fopen($fullpath, $mode);
651 return !empty($this->fp);
654 public function stream_read($count)
656 return fread($this->fp, $count);
659 public function stream_seek($offset, $whence = SEEK_SET)
661 return fseek($this->fp, $offset, $whence) == 0;
664 public function stream_set_option($option, $arg1, $arg2)
669 public function stream_stat()
671 return fstat($this->fp);
674 public function stream_tell()
676 return ftell($this->fp);
678 public function stream_write($data)
680 return fwrite($this->fp, $data);
683 public function unlink($path)
685 unlink(self::path($path));
689 public function url_stat($path, $flags)
691 return @stat(self::path($path));
694 public static function move_uploaded_file($upload, $path)
696 return move_uploaded_file($upload, self::path($path));