]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/upload_file.php
Release 6.4.0
[Github/sugarcrm.git] / include / upload_file.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
40  * Description:
41  ********************************************************************************/
42 require_once('include/externalAPI/ExternalAPIFactory.php');
43
44 /**
45  * @api
46  * Manage uploaded files
47  */
48 class UploadFile
49 {
50         var $field_name;
51         var $stored_file_name;
52         var $original_file_name;
53         var $temp_file_location;
54         var $use_soap = false;
55         var $file;
56         var $file_ext;
57         protected static $url = "upload/";
58
59         /**
60          * Upload errors
61          * @var array
62          */
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.',
69                         5 => 'UNKNOWN ERROR',
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.',
73                         );
74
75         /**
76          * Create upload file handler
77          * @param string $field_name Form field name
78          */
79         function UploadFile ($field_name = '')
80         {
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;
84         }
85
86         /**
87          * Setup for SOAP upload
88          * @param string $filename Name for the file
89          * @param string $file
90          */
91         function set_for_soap($filename, $file) {
92                 $this->stored_file_name = $filename;
93                 $this->use_soap = true;
94                 $this->file = $file;
95         }
96
97         /**
98          * Get URL for a document
99          * @deprecated
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
103          */
104         public static function get_url($stored_file_name, $bean_id)
105         {
106                 if ( empty($bean_id) && empty($stored_file_name) ) {
107             return self::$url;
108                 }
109
110                 return self::$url . $bean_id;
111         }
112
113         /**
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
117          */
118         public static function get_upload_url($document, $type = null)
119         {
120             if(empty($type)) {
121                 $type = $document->module_dir;
122             }
123             return "index.php?entryPoint=download&type=$type&id={$document->id}";
124         }
125
126         /**
127          * Try renaming a file to bean_id name
128          * @param string $filename
129          * @param string $bean_id
130          */
131         protected static function tryRename($filename, $bean_id)
132         {
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");
137             }
138                 return true;
139             }
140             return false;
141         }
142
143         /**
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
148          */
149         static public function get_file_path($stored_file_name, $bean_id, $skip_rename = false)
150         {
151                 global $locale;
152
153         // if the parameters are empty strings, just return back the upload_dir
154                 if ( empty($bean_id) && empty($stored_file_name) ) {
155             return "upload://";
156                 }
157
158                 if(!$skip_rename) {
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);
163                 }
164
165                 return "upload://$bean_id";
166         }
167
168         /**
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)
173          */
174         public static function duplicate_file($old_id, $new_id, $file_name)
175         {
176                 global $sugar_config;
177
178                 // current file system (GUID)
179                 $source = "upload://$old_id";
180
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)) {
187                                         // delete the old
188                                         if(!unlink($oldStyleSource)) {
189                                                 $GLOBALS['log']->error("upload_file could not unlink [ {$oldStyleSource} ]");
190                                         }
191                                 } else {
192                                         $GLOBALS['log']->error("upload_file could not copy [ {$oldStyleSource} ] to [ {$source} ]");
193                                 }
194                         }
195                 }
196
197                 $destination = "upload://$new_id";
198                 if(!copy($source, $destination)) {
199                         $GLOBALS['log']->error("upload_file could not copy [ {$source} ] to [ {$destination} ]");
200                 }
201         }
202
203         /**
204          * Get upload error from system
205          * @return string upload error
206          */
207         public function get_upload_error()
208         {
209             if(isset($this->field_name) && isset($_FILES[$this->field_name]['error'])) {
210                 return $_FILES[$this->field_name]['error'];
211             }
212             return false;
213         }
214
215         /**
216          * standard PHP file-upload security measures. all variables accessed in a global context
217          * @return bool True on success
218          */
219         public function confirm_upload()
220         {
221                 global $sugar_config;
222
223                 if(empty($this->field_name) || !isset($_FILES[$this->field_name])) {
224                     return false;
225                 }
226
227                 if($_FILES[$this->field_name]['error'] != UPLOAD_ERR_OK) {
228                     if($_FILES[$this->field_name]['error'] != UPLOAD_ERR_NO_FILE) {
229                 $GLOBALS['log']->error('File upload error: '.self::$filesError[$_FILES[$this->field_name]['error']]);
230                     }
231                     return false;
232                 }
233
234                 if(!is_uploaded_file($_FILES[$this->field_name]['tmp_name'])) {
235                         return false;
236                 } elseif($_FILES[$this->field_name]['size'] > $sugar_config['upload_maxsize']) {
237                     $GLOBALS['log']->fatal("ERROR: uploaded file was too big: max filesize: {$sugar_config['upload_maxsize']}");
238                         return false;
239                 }
240
241                 if(!UploadStream::writable()) {
242                     $GLOBALS['log']->fatal("ERROR: cannot write to upload directory");
243                         return false;
244                 }
245
246                 $this->mime_type = $this->getMime($_FILES[$this->field_name]);
247                 $this->stored_file_name = $this->create_stored_filename();
248                 $this->temp_file_location = $_FILES[$this->field_name]['tmp_name'];
249
250                 return true;
251         }
252
253         /**
254          * Guess MIME type for file
255          * @param string $filename
256          * @return string MIME type
257          */
258         function getMimeSoap($filename){
259
260                 if( function_exists( 'ext2mime' ) )
261                 {
262                         $mime = ext2mime($filename);
263                 }
264                 else
265                 {
266                         $mime = ' application/octet-stream';
267                 }
268                 return $mime;
269
270         }
271
272         /**
273          * Get MIME type for uploaded file
274          * @param array $_FILES_element $_FILES element required
275          * @return string MIME type
276          */
277         function getMime($_FILES_element)
278         {
279                 $filename = $_FILES_element['name'];
280         $file_ext = pathinfo($filename, PATHINFO_EXTENSION);
281
282         //If no file extension is available and the mime is octet-stream try to determine the mime type.
283         $recheckMime = empty($file_ext) && ($_FILES_element['type']  == 'application/octet-stream');
284
285                 if( $_FILES_element['type'] && !$recheckMime) {
286                         $mime = $_FILES_element['type'];
287                 } elseif( function_exists( 'mime_content_type' ) ) {
288                         $mime = mime_content_type( $_FILES_element['tmp_name'] );
289                 } elseif( function_exists( 'ext2mime' ) ) {
290                         $mime = ext2mime( $_FILES_element['name'] );
291                 } else {
292                         $mime = ' application/octet-stream';
293                 }
294                 return $mime;
295         }
296
297         /**
298          * gets note's filename
299          * @return string
300          */
301         function get_stored_file_name()
302         {
303                 return $this->stored_file_name;
304         }
305
306         /**
307          * creates a file's name for preparation for saving
308          * @return string
309          */
310         function create_stored_filename()
311         {
312                 global $sugar_config;
313
314                 if(!$this->use_soap) {
315                         $stored_file_name = $_FILES[$this->field_name]['name'];
316                         $this->original_file_name = $stored_file_name;
317
318                         /**
319                          * cn: bug 8056 - windows filesystems and IIS do not like utf8.  we are forced to urlencode() to ensure that
320                          * the file is linkable from the browser.  this will stay broken until we move to a db-storage system
321                          */
322                         if(is_windows()) {
323                                 // create a non UTF-8 name encoding
324                                 // 176 + 36 char guid = windows' maximum filename length
325                                 $end = (strlen($stored_file_name) > 176) ? 176 : strlen($stored_file_name);
326                                 $stored_file_name = substr($stored_file_name, 0, $end);
327                                 $this->original_file_name = $_FILES[$this->field_name]['name'];
328                         }
329                     $stored_file_name = str_replace("\\", "", $stored_file_name);
330                 } else {
331                         $stored_file_name = $this->stored_file_name;
332                         $this->original_file_name = $stored_file_name;
333                 }
334
335                 $this->file_ext = pathinfo($stored_file_name, PATHINFO_EXTENSION);
336         // cn: bug 6347 - fix file extension detection
337         foreach($sugar_config['upload_badext'] as $badExt) {
338             if(strtolower($this->file_ext) == strtolower($badExt)) {
339                 $stored_file_name .= ".txt";
340                 $this->file_ext="txt";
341                 break; // no need to look for more
342             }
343         }
344                 return $stored_file_name;
345         }
346
347         /**
348          * moves uploaded temp file to permanent save location
349          * @param string bean_id ID of parent bean
350          * @return bool True on success
351          */
352         function final_move($bean_id)
353         {
354             $destination = $bean_id;
355             if(substr($destination, 0, 9) != "upload://") {
356             $destination = "upload://$bean_id";
357             }
358         if($this->use_soap) {
359                 if(!file_put_contents($destination, $this->file)){
360                     $GLOBALS['log']->fatal("ERROR: can't save file to $destination");
361                 return false;
362                 }
363                 } else {
364                         if(!UploadStream::move_uploaded_file($_FILES[$this->field_name]['tmp_name'], $destination)) {
365                             $GLOBALS['log']->fatal("ERROR: can't move_uploaded_file to $destination. You should try making the directory writable by the webserver");
366                 return false;
367                         }
368                 }
369                 return true;
370         }
371
372         /**
373          * Upload document to external service
374          * @param SugarBean $bean Related bean
375          * @param string $bean_id
376          * @param string $doc_type
377          * @param string $file_name
378          * @param string $mime_type
379          */
380         function upload_doc($bean, $bean_id, $doc_type, $file_name, $mime_type)
381         {
382                 if(!empty($doc_type)&&$doc_type!='Sugar') {
383                         global $sugar_config;
384                 $destination = $this->get_upload_path($bean_id);
385                 sugar_rename($destination, str_replace($bean_id, $bean_id.'_'.$file_name, $destination));
386                 $new_destination = $this->get_upload_path($bean_id.'_'.$file_name);
387
388                     try{
389                 $this->api = ExternalAPIFactory::loadAPI($doc_type);
390
391                 if ( isset($this->api) && $this->api !== false ) {
392                     $result = $this->api->uploadDoc(
393                         $bean,
394                         $new_destination,
395                         $file_name,
396                         $mime_type
397                         );
398                 } else {
399                     $result['success'] = FALSE;
400                     // FIXME: Translate
401                     $GLOBALS['log']->error("Could not load the requested API (".$doc_type.")");
402                     $result['errorMessage'] = 'Could not find a proper API';
403                 }
404             }catch(Exception $e){
405                 $result['success'] = FALSE;
406                 $result['errorMessage'] = $e->getMessage();
407                 $GLOBALS['log']->error("Caught exception: (".$e->getMessage().") ");
408             }
409             if ( !$result['success'] ) {
410                 sugar_rename($new_destination, str_replace($bean_id.'_'.$file_name, $bean_id, $new_destination));
411                 $bean->doc_type = 'Sugar';
412                 // FIXME: Translate
413                 if ( ! is_array($_SESSION['user_error_message']) )
414                     $_SESSION['user_error_message'] = array();
415
416                 $error_message = isset($result['errorMessage']) ? $result['errorMessage'] : $GLOBALS['app_strings']['ERR_EXTERNAL_API_SAVE_FAIL'];
417                 $_SESSION['user_error_message'][] = $error_message;
418
419             }
420             else {
421                 unlink($new_destination);
422             }
423         }
424
425         }
426
427         /**
428          * returns the path with file name to save an uploaded file
429          * @param string bean_id ID of the parent bean
430          * @return string
431          */
432         function get_upload_path($bean_id)
433         {
434                 $file_name = $bean_id;
435
436                 // cn: bug 8056 - mbcs filename in urlencoding > 212 chars in Windows fails
437                 $end = (strlen($file_name) > 212) ? 212 : strlen($file_name);
438                 $ret_file_name = substr($file_name, 0, $end);
439
440                 return "upload://$ret_file_name";
441         }
442
443         /**
444          * deletes a file
445          * @param string bean_id ID of the parent bean
446          * @param string file_name File's name
447          */
448         static public function unlink_file($bean_id,$file_name = '')
449         {
450             if(file_exists("upload://$bean_id$file_name")) {
451             return unlink("upload://$bean_id$file_name");
452             }
453     }
454
455     /**
456      * Get upload file location prefix
457      * @return string prefix
458      */
459     public function get_upload_dir()
460     {
461         return "upload://";
462     }
463
464     /**
465      * Return real FS path of the file
466      * @param string $path
467      */
468     public static function realpath($path)
469     {
470        if(substr($path, 0, 9) == "upload://") {
471            $path = UploadStream::path($path);
472        }
473        $ret = realpath($path);
474        return $ret?$ret:$path;
475     }
476
477     /**
478      * Return path of uploaded file relative to uploads dir
479      * @param string $path
480      */
481     public static function relativeName($path)
482     {
483         if(substr($path, 0, 9) == "upload://") {
484             $path = substr($path, 9);
485         }
486         return $path;
487     }
488 }
489
490 /**
491  * @internal
492  * Upload file stream handler
493  */
494 class UploadStream
495 {
496     const STREAM_NAME = "upload";
497     protected static $upload_dir;
498
499     /**
500      * Get upload directory
501      * @return string
502      */
503     public static function getDir()
504     {
505         if(empty(self::$upload_dir)) {
506             self::$upload_dir = rtrim($GLOBALS['sugar_config']['upload_dir'], '/\\');
507             if(empty(self::$upload_dir)) {
508                 self::$upload_dir = "upload";
509             }
510             if(!file_exists(self::$upload_dir)) {
511                 sugar_mkdir(self::$upload_dir, 0755, true);
512             }
513         }
514         return self::$upload_dir;
515     }
516
517     /**
518      * Check if upload dir is writable
519      * @return bool
520      */
521     public static function writable()
522     {
523         return is_writable(self::getDir());
524     }
525
526     /**
527      * Register the stream
528      */
529     public function register()
530     {
531         stream_register_wrapper(self::STREAM_NAME, __CLASS__);
532     }
533
534     /**
535      * Get real FS path of the upload stream file
536      * @param string $path Upload stream path (with upload://)
537      * @return string FS path
538      */
539     public static function path($path)
540     {
541         $path = substr($path, strlen(self::STREAM_NAME)+3); // cut off upload://
542         $path = str_replace("\\", "/", $path); // canonicalize path
543         if($path == ".." || substr($path, 0, 3) == "../" || substr($path, -3, 3) == "/.." || strstr($path, "/../")) {
544                 $GLOBALS['log']->fatal("Invalid uploaded file name supplied: $path");
545                 return null;
546         }
547         return self::getDir()."/".$path;
548     }
549
550     /**
551      * Ensure upload subdir exists
552      * @param string $path Upload stream path (with upload://)
553      * @param bool $writable
554      * @return boolean
555      */
556     public static function ensureDir($path, $writable = true)
557     {
558         $path = self::path($path);
559         if(!is_dir($path)) {
560            return sugar_mkdir($path, 0755, true);
561         }
562         return true;
563     }
564
565     public function dir_closedir()
566     {
567         closedir($this->dirp);
568     }
569
570     public function dir_opendir ($path, $options )
571     {
572         $this->dirp = opendir(self::path($path));
573         return !empty($this->dirp);
574     }
575
576     public function dir_readdir()
577     {
578         return readdir($this->dirp);
579     }
580
581     public function dir_rewinddir()
582     {
583         return rewinddir($this->dirp);
584     }
585
586     public function mkdir($path, $mode, $options)
587     {
588         return mkdir(self::path($path), $mode, ($options&STREAM_MKDIR_RECURSIVE) != 0);
589     }
590
591     public function rename($path_from, $path_to)
592     {
593         return rename(self::path($path_from), self::path($path_to));
594     }
595
596     public function rmdir($path, $options)
597     {
598         return rmdir(self::path($path));
599     }
600
601     public function stream_cast ($cast_as)
602     {
603         return $this->fp;
604     }
605
606     public function stream_close ()
607     {
608         fclose($this->fp);
609         return true;
610     }
611
612     public function stream_eof ()
613     {
614         return feof($this->fp);
615     }
616    public function stream_flush ()
617     {
618         return fflush($this->fp);
619     }
620
621     public function stream_lock($operation)
622     {
623         return flock($this->fp, $operation);
624     }
625
626     public function stream_open($path, $mode)
627     {
628         $fullpath = self::path($path);
629         if(empty($fullpath)) return false;
630         if($mode == 'r') {
631             $this->fp = fopen($fullpath, $mode);
632         } else {
633             // if we will be writing, try to transparently create the directory
634             $this->fp = @fopen($fullpath, $mode);
635             if(!$this->fp && !file_exists(dirname($fullpath))) {
636                 mkdir(dirname($fullpath), 0755, true);
637                 $this->fp = fopen($fullpath, $mode);
638             }
639         }
640         return !empty($this->fp);
641     }
642
643     public function stream_read($count)
644     {
645         return fread($this->fp, $count);
646     }
647
648     public function stream_seek($offset, $whence = SEEK_SET)
649     {
650         return fseek($this->fp, $offset, $whence) == 0;
651     }
652
653     public function stream_set_option($option, $arg1, $arg2)
654     {
655         return true;
656     }
657
658     public function stream_stat()
659     {
660         return fstat($this->fp);
661     }
662
663     public function stream_tell()
664     {
665         return ftell($this->fp);
666     }
667     public function stream_write($data)
668     {
669         return fwrite($this->fp, $data);
670     }
671
672     public function unlink($path)
673     {
674         unlink(self::path($path));
675         return true;
676     }
677
678     public function url_stat($path, $flags)
679     {
680         return @stat(self::path($path));
681     }
682
683     public static function move_uploaded_file($upload, $path)
684     {
685         return move_uploaded_file($upload, self::path($path));
686     }
687 }
688