2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * file upload functions
11 * @todo replace error messages with localized string
12 * @todo when uploading a file into a blob field, should we also consider using
13 * chunks like in import? UPDATE `table` SET `field` = `field` + [chunk]
19 * @var string the temporary file name
25 * @var string the content
31 * @var string the error message
34 var $_error_message = '';
37 * @var bool whether the file is temporary or not
40 var $_is_temp = false;
43 * @var string type of compression
46 var $_compression = null;
54 * @var integer size of chunk to read with every step
56 var $_chunk_size = 32768;
59 * @var resource file handle
64 * @var boolean whether to decompress content before returning
66 var $_decompress = false;
69 * @var string charset of file
74 * @staticvar string most recent BLOB repository reference
76 static $_recent_bs_reference = NULL;
82 * @uses PMA_File::setName()
83 * @param string $name file name
85 function __construct($name = false)
88 $this->setName($name);
95 * @see PMA_File::cleanUp()
97 * @uses PMA_File::cleanUp()
105 * deletes file if it is temporary, usally from a moved upload file
108 * @uses PMA_File::delet()
109 * @uses PMA_File::isTemp()
110 * @return boolean success
114 if ($this->isTemp()) {
115 return $this->delete();
125 * @uses PMA_File::getName()
127 * @return boolean success
131 return unlink($this->getName());
135 * checks or sets the temp flag for this file
136 * file objects with temp flags are deleted with object destruction
139 * @uses PMA_File::$_is_temp to set and read it
140 * @param boolean sets the temp flag
141 * @return boolean PMA_File::$_is_temp
143 function isTemp($is_temp = null)
145 if (null !== $is_temp) {
146 $this->_is_temp
= (bool) $is_temp;
149 return $this->_is_temp
;
156 * @uses PMA_File::$_name
157 * @param string $name file name
159 function setName($name)
161 $this->_name
= trim($name);
166 * @uses PMA_File::getName()
167 * @uses PMA_File::isUploaded()
168 * @uses PMA_File::checkUploadedFile()
169 * @uses PMA_File::isReadable()
170 * @uses PMA_File::$_content
171 * @uses function_exists()
172 * @uses file_get_contents()
177 * @return string binary file content
179 function getContent($as_binary = true, $offset = 0, $length = null)
181 if (null === $this->_content
) {
182 if ($this->isUploaded() && ! $this->checkUploadedFile()) {
186 if (! $this->isReadable()) {
190 if (function_exists('file_get_contents')) {
191 $this->_content
= file_get_contents($this->getName());
192 } elseif ($size = filesize($this->getName())) {
193 $this->_content
= fread(fopen($this->getName(), 'rb'), $size);
197 if (! empty($this->_content
) && $as_binary) {
198 return '0x' . bin2hex($this->_content
);
201 if (null !== $length) {
202 return substr($this->_content
, $offset, $length);
203 } elseif ($offset > 0) {
204 return substr($this->_content
, $offset);
207 return $this->_content
;
212 * @uses PMA_File::getName()
213 * @uses is_uploaded_file()
215 function isUploaded()
217 return is_uploaded_file($this->getName());
224 * @uses PMA_File::$name as return value
225 * @return string PMA_File::$_name
233 * @todo replace error message with localized string
235 * @uses PMA_File::isUploaded()
236 * @uses PMA_File::setName()
237 * @uses PMA_File::$_error_message
238 * @param string name of file uploaded
239 * @return boolean success
241 function setUploadedFile($name)
243 $this->setName($name);
245 if (! $this->isUploaded()) {
246 $this->setName(null);
247 $this->_error_message
= 'not an uploaded file';
256 * @uses PMA_File::fetchUploadedFromTblChangeRequestMultiple()
257 * @uses PMA_File::setUploadedFile()
258 * @uses PMA_File::setRecentBLOBReference()
259 * @uses curl_setopt_array()
260 * @uses PMA_File::$_error_message
262 * @param string $key the md5 hash of the column name
263 * @param string $rownumber
264 * @return boolean success
266 function setUploadedFromTblChangeRequest($key, $rownumber)
268 if (! isset($_FILES['fields_upload']) ||
empty($_FILES['fields_upload']['name']['multi_edit'][$rownumber][$key])) {
271 $file = PMA_File
::fetchUploadedFromTblChangeRequestMultiple($_FILES['fields_upload'], $rownumber, $key);
274 $is_bs_upload = FALSE;
276 // check if this field requires a repository upload
277 if (isset($_REQUEST['upload_blob_repo']['multi_edit'][$rownumber][$key])) {
278 $is_bs_upload = ($_REQUEST['upload_blob_repo']['multi_edit'][$rownumber][$key] == "on") ?
TRUE : FALSE;
280 // if request is an upload to the BLOB repository
282 $bs_db = $_REQUEST['db'];
283 $bs_table = $_REQUEST['table'];
284 $tmp_filename = $file['tmp_name'];
285 $tmp_file_type = $file['type'];
287 if (! $tmp_file_type) {
288 $tmp_file_type = NULL;
291 if (! $bs_db ||
! $bs_table) {
292 $this->_error_message
= $GLOBALS['strUploadErrorUnknown'];
295 $blob_url = PMA_BS_UpLoadFile($bs_db, $bs_table, $tmp_file_type, $tmp_filename);
296 PMA_File
::setRecentBLOBReference($blob_url);
297 } // end if ($is_bs_upload)
299 // check for file upload errors
300 switch ($file['error']) {
301 // we do not use the PHP constants here cause not all constants
302 // are defined in all versions of PHP - but the correct constants names
303 // are given as comment
304 case 0: //UPLOAD_ERR_OK:
305 return $this->setUploadedFile($file['tmp_name']);
307 case 4: //UPLOAD_ERR_NO_FILE:
309 case 1: //UPLOAD_ERR_INI_SIZE:
310 $this->_error_message
= __('The uploaded file exceeds the upload_max_filesize directive in php.ini.');
312 case 2: //UPLOAD_ERR_FORM_SIZE:
313 $this->_error_message
= __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.');
315 case 3: //UPLOAD_ERR_PARTIAL:
316 $this->_error_message
= __('The uploaded file was only partially uploaded.');
318 case 6: //UPLOAD_ERR_NO_TMP_DIR:
319 $this->_error_message
= __('Missing a temporary folder.');
321 case 7: //UPLOAD_ERR_CANT_WRITE:
322 $this->_error_message
= __('Failed to write file to disk.');
324 case 8: //UPLOAD_ERR_EXTENSION:
325 $this->_error_message
= __('File upload stopped by extension.');
328 $this->_error_message
= __('Unknown error in file upload.');
335 * strips some dimension from the multi-dimensional array from $_FILES
338 * $file['name']['multi_edit'][$rownumber][$key] = [value]
339 * $file['type']['multi_edit'][$rownumber][$key] = [value]
340 * $file['size']['multi_edit'][$rownumber][$key] = [value]
341 * $file['tmp_name']['multi_edit'][$rownumber][$key] = [value]
342 * $file['error']['multi_edit'][$rownumber][$key] = [value]
346 * $file['name'] = [value]
347 * $file['type'] = [value]
348 * $file['size'] = [value]
349 * $file['tmp_name'] = [value]
350 * $file['error'] = [value]
353 * @todo re-check if requirements changes to PHP >= 4.2.0
356 * @param array $file the array
357 * @param string $rownumber
361 function fetchUploadedFromTblChangeRequestMultiple($file, $rownumber, $key)
364 'name' => $file['name']['multi_edit'][$rownumber][$key],
365 'type' => $file['type']['multi_edit'][$rownumber][$key],
366 'size' => $file['size']['multi_edit'][$rownumber][$key],
367 'tmp_name' => $file['tmp_name']['multi_edit'][$rownumber][$key],
368 'error' => $file['error']['multi_edit'][$rownumber][$key],
375 * sets the name if the file to the one selected in the tbl_change form
379 * @uses PMA_File::setLocalSelectedFile()
381 * @param string $key the md5 hash of the column name
382 * @param string $rownumber
383 * @return boolean success
385 function setSelectedFromTblChangeRequest($key, $rownumber = null)
387 if (! empty($_REQUEST['fields_uploadlocal']['multi_edit'][$rownumber][$key])
388 && is_string($_REQUEST['fields_uploadlocal']['multi_edit'][$rownumber][$key])) {
389 // ... whether with multiple rows ...
391 $is_bs_upload = FALSE;
393 // check if this field requires a repository upload
394 if (isset($_REQUEST['upload_blob_repo']['multi_edit'][$rownumber][$key])) {
395 $is_bs_upload = ($_REQUEST['upload_blob_repo']['multi_edit'][$rownumber][$key] == "on") ?
TRUE : FALSE;
398 // is a request to upload file to BLOB repository using uploadDir mechanism
400 $bs_db = $_REQUEST['db'];
401 $bs_table = $_REQUEST['table'];
402 $tmp_filename = $GLOBALS['cfg']['UploadDir'] . '/' . $_REQUEST['fields_uploadlocal_' . $key]['multi_edit'][$rownumber];
404 // check if fileinfo library exists
405 if ($PMA_Config->get('FILEINFO_EXISTS')) {
406 // attempt to init fileinfo
407 $finfo = finfo_open(FILEINFO_MIME
);
411 // pass in filename to fileinfo and close fileinfo handle after
412 $tmp_file_type = finfo_file($finfo, $tmp_filename);
416 // no fileinfo library exists, use file command
417 $tmp_file_type = exec("file -bi " . escapeshellarg($tmp_filename));
420 if (! $tmp_file_type) {
421 $tmp_file_type = NULL;
424 if (! $bs_db ||
!$bs_table) {
425 $this->_error_message
= $GLOBALS['strUploadErrorUnknown'];
428 $blob_url = PMA_BS_UpLoadFile($bs_db, $bs_table, $tmp_file_type, $tmp_filename);
429 PMA_File
::setRecentBLOBReference($blob_url);
430 } // end if ($is_bs_upload)
432 return $this->setLocalSelectedFile($_REQUEST['fields_uploadlocal']['multi_edit'][$rownumber][$key]);
440 * @uses PMA_File->$_error_message as return value
441 * @return string error message
445 return $this->_error_message
;
450 * @uses PMA_File->$_error_message to check it
451 * @return boolean whether an error occured or not
455 return ! empty($this->_error_message
);
459 * checks the superglobals provided if the tbl_change form is submitted
460 * and uses the submitted/selected file
463 * @uses PMA_File::setUploadedFromTblChangeRequest()
464 * @uses PMA_File::setSelectedFromTblChangeRequest()
465 * @param string $key the md5 hash of the column name
466 * @param string $rownumber
467 * @return boolean success
469 function checkTblChangeForm($key, $rownumber)
471 if ($this->setUploadedFromTblChangeRequest($key, $rownumber)) {
473 $this->_error_message
= '';
475 } elseif ($this->setSelectedFromTblChangeRequest($key, $rownumber)) {
477 $this->_error_message
= '';
480 // all failed, whether just no file uploaded/selected or an error
488 * @uses PMA_File::setName()
489 * @uses PMA_securePath()
490 * @uses PMA_userDir()
491 * @uses $GLOBALS['cfg']['UploadDir']
492 * @param string $name
493 * @return boolean success
495 function setLocalSelectedFile($name)
497 if (empty($GLOBALS['cfg']['UploadDir'])) return false;
499 $this->setName(PMA_userDir($GLOBALS['cfg']['UploadDir']) . PMA_securePath($name));
500 if (! $this->isReadable()) {
501 $this->_error_message
= __('File could not be read');
502 $this->setName(null);
511 * @uses PMA_File::getName()
512 * @uses is_readable()
514 * @uses ob_end_clean()
515 * @return boolean whether the file is readable or not
517 function isReadable()
519 // suppress warnings from being displayed, but not from being logged
520 // any file access outside of open_basedir will issue a warning
522 $is_readable = is_readable($this->getName());
528 * If we are on a server with open_basedir, we must move the file
529 * before opening it. The FAQ 1.11 explains how to create the "./tmp"
530 * directory - if needed
532 * @todo replace error message with localized string
533 * @todo move check of $cfg['TempDir'] into PMA_Config?
535 * @uses $cfg['TempDir']
536 * @uses PMA_File::isReadable()
537 * @uses PMA_File::getName()
538 * @uses PMA_File::setName()
539 * @uses PMA_File::isTemp()
540 * @uses PMA_File::$_error_message
544 * @uses is_writable()
546 * @uses move_uploaded_file()
548 * @uses ob_end_clean()
549 * @return boolean whether uploaded fiel is fine or not
551 function checkUploadedFile()
553 if ($this->isReadable()) {
557 if (empty($GLOBALS['cfg']['TempDir']) ||
! is_writable($GLOBALS['cfg']['TempDir'])) {
558 // cannot create directory or access, point user to FAQ 1.11
559 $this->_error_message
= __('Error moving the uploaded file, see [a@./Documentation.html#faq1_11@Documentation]FAQ 1.11[/a]');
563 $new_file_to_upload = tempnam(realpath($GLOBALS['cfg']['TempDir']), basename($this->getName()));
565 // suppress warnings from being displayed, but not from being logged
566 // any file access outside of open_basedir will issue a warning
568 $move_uploaded_file_result = move_uploaded_file($this->getName(), $new_file_to_upload);
570 if (! $move_uploaded_file_result) {
571 $this->_error_message
= 'error while moving uploaded file';
575 $this->setName($new_file_to_upload);
578 if (! $this->isReadable()) {
579 $this->_error_message
= 'cannot read (moved) upload file';
587 * Detects what compression filse uses
589 * @todo move file read part into readChunk() or getChunk()
590 * @todo add support for compression plugins
591 * @uses PMA_File::$_compression to set it
592 * @uses PMA_File::getName()
600 * @return string MIME type of compression, none for none
602 function _detectCompression()
604 // suppress warnings from being displayed, but not from being logged
605 // f.e. any file access outside of open_basedir will issue a warning
607 $file = fopen($this->getName(), 'rb');
611 $this->_error_message
= __('File could not be read');
617 * get registered plugins for file compression
619 foreach (PMA_getPlugins($type = 'compression') as $plugin) {
620 if (call_user_func_array(array($plugin['classname'], 'canHandle'), array($this->getName()))) {
621 $this->setCompressionPlugin($plugin);
627 $test = fread($file, 4);
628 $len = strlen($test);
631 if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
632 $this->_compression
= 'application/gzip';
633 } elseif ($len >= 3 && substr($test, 0, 3) == 'BZh') {
634 $this->_compression
= 'application/bzip2';
635 } elseif ($len >= 4 && $test == "PK\003\004") {
636 $this->_compression
= 'application/zip';
638 $this->_compression
= 'none';
641 return $this->_compression
;
645 * whether the content should be decompressed before returned
647 function setDecompressContent($decompress)
649 $this->_decompress
= (bool) $decompress;
654 if (null === $this->_handle
) {
657 return $this->_handle
;
660 function setHandle($handle)
662 $this->_handle
= $handle;
670 if (! $this->_decompress
) {
671 $this->_handle
= @fopen
($this->getName(), 'r');
674 switch ($this->getCompression()) {
677 case 'application/bzip2':
678 if ($GLOBALS['cfg']['BZipDump'] && @function_exists
('bzopen')) {
679 $this->_handle
= @bzopen
($this->getName(), 'r');
681 $this->_error_message
= sprintf(__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.'), $this->getCompression());
685 case 'application/gzip':
686 if ($GLOBALS['cfg']['GZipDump'] && @function_exists
('gzopen')) {
687 $this->_handle
= @gzopen
($this->getName(), 'r');
689 $this->_error_message
= sprintf(__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.'), $this->getCompression());
693 case 'application/zip':
694 if ($GLOBALS['cfg']['ZipDump'] && @function_exists
('zip_open')) {
695 include_once './libraries/zip_extension.lib.php';
696 $result = PMA_getZipContents($this->getName());
697 if (! empty($result['error'])) {
698 $this->_error_message
= PMA_Message
::rawError($result['error']);
701 $this->content_uncompressed
= $result['data'];
705 $this->_error_message
= sprintf(__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.'), $this->getCompression());
710 $this->_handle
= @fopen
($this->getName(), 'r');
713 $this->_error_message
= sprintf(__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.'), $this->getCompression());
721 function getCharset()
723 return $this->_charset
;
726 function setCharset($charset)
728 $this->_charset
= $charset;
732 * @uses PMA_File::$_compression as return value
733 * @uses PMA_File::detectCompression()
734 * @return string MIME type of compression, none for none
737 function getCompression()
739 if (null === $this->_compression
) {
740 return $this->_detectCompression();
743 return $this->_compression
;
747 * advances the file pointer in the file handle by $length bytes/chars
749 * @param integer $length numbers of chars/bytes to skip
751 * @todo this function is unused
753 function advanceFilePointer($length)
755 while ($length > 0) {
756 // Disable read progresivity, otherwise we eat all memory!
757 $read_multiply = 1; // required?
758 $this->getNextChunk($length);
759 $length -= $this->getChunkSize();
764 * http://bugs.php.net/bug.php?id=29532
765 * bzip reads a maximum of 8192 bytes on windows systems
766 * @todo this function is unused
768 function getNextChunk($max_size = null)
770 if (null !== $max_size) {
771 $size = min($max_size, $this->getChunkSize());
773 $size = $this->getChunkSize();
776 // $result = $this->handler->getNextChunk($size);
778 switch ($this->getCompression()) {
779 case 'application/bzip2':
781 while (strlen($result) < $size - 8192 && ! feof($this->getHandle())) {
782 $result .= bzread($this->getHandle(), $size);
785 case 'application/gzip':
786 $result = gzread($this->getHandle(), $size);
788 case 'application/zip':
790 * if getNextChunk() is used some day,
791 * replace this code by code similar to the one
794 include_once './libraries/unzip.lib.php';
795 $import_handle = new SimpleUnzip();
796 $import_handle->ReadFile($this->getName());
797 if ($import_handle->Count() == 0) {
798 $this->_error_message = __('No files found inside ZIP archive!');
800 } elseif ($import_handle->GetError(0) != 0) {
801 $this->_error_message = __('Error in ZIP archive:')
802 . ' ' . $import_handle->GetErrorMsg(0);
805 $result = $import_handle->GetData(0);
810 $result = fread($this->getHandle(), $size);
817 echo strlen($result) . ' - ';
818 echo (@$GLOBALS['__len__'] +
= strlen($result)) . ' - ';
819 echo $this->_error_message
;
822 if ($GLOBALS['charset_conversion']) {
823 $result = PMA_convert_string($this->getCharset(), $GLOBALS['charset'], $result);
826 * Skip possible byte order marks (I do not think we need more
827 * charsets, but feel free to add more, you can use wikipedia for
828 * reference: <http://en.wikipedia.org/wiki/Byte_Order_Mark>)
830 * @todo BOM could be used for charset autodetection
832 if ($this->getOffset() === 0) {
834 if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
835 $result = substr($result, 3);
837 } elseif (strncmp($result, "\xFE\xFF", 2) == 0
838 ||
strncmp($result, "\xFF\xFE", 2) == 0) {
839 $result = substr($result, 2);
844 $this->_offset +
= $size;
853 return $this->_offset
;
856 function getChunkSize()
858 return $this->_chunk_size
;
861 function setChunkSize($chunk_size)
863 $this->_chunk_size
= (int) $chunk_size;
866 function getContentLength()
868 return strlen($this->_content
);
873 if ($this->getHandle()) {
874 return feof($this->getHandle());
876 return ($this->getOffset() >= $this->getContentLength());
882 * sets reference to most recent BLOB repository reference
885 * @param string - BLOB repository reference
887 static function setRecentBLOBReference($ref)
889 PMA_File
::$_recent_bs_reference = $ref;
893 * retrieves reference to most recent BLOB repository reference
896 * @return string - most recent BLOB repository reference
898 static function getRecentBLOBReference()
900 $ref = PMA_File
::$_recent_bs_reference;
901 PMA_File
::$_recent_bs_reference = NULL;