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 a numeric key used to identify the different rows
263 * @param string $primary_key
264 * @return boolean success
266 function setUploadedFromTblChangeRequest($key, $primary = null)
268 if (! isset($_FILES['fields_upload_' . $key])) {
272 $file = $_FILES['fields_upload_' . $key];
274 if (null !== $primary) {
275 $file = PMA_File
::fetchUploadedFromTblChangeRequestMultiple($file, $primary);
279 $is_bs_upload = FALSE;
281 // check if this field requires a repository upload
282 if (isset($_REQUEST['upload_blob_repo_' . $key])) {
283 $is_bs_upload = ($_REQUEST['upload_blob_repo_' . $key]['multi_edit'][0] == "on") ?
TRUE : FALSE;
285 // if request is an upload to the BLOB repository
287 $bs_db = $_REQUEST['db'];
288 $bs_table = $_REQUEST['table'];
289 $tmp_filename = $file['tmp_name'];
290 $tmp_file_type = $file['type'];
292 if (! $tmp_file_type) {
293 $tmp_file_type = NULL;
296 if (! $bs_db ||
! $bs_table) {
297 $this->_error_message
= $GLOBALS['strUploadErrorUnknown'];
300 $blob_url = PMA_BS_UpLoadFile($bs_db, $bs_table, $tmp_file_type, $tmp_filename);
301 PMA_File
::setRecentBLOBReference($blob_url);
302 } // end if ($is_bs_upload)
304 // check for file upload errors
305 switch ($file['error']) {
306 // cybot_tm: we do not use the PHP constants here cause not all constants
307 // are defined in all versions of PHP - but the correct constants names
308 // are given as comment
309 case 0: //UPLOAD_ERR_OK:
310 return $this->setUploadedFile($file['tmp_name']);
312 case 4: //UPLOAD_ERR_NO_FILE:
314 case 1: //UPLOAD_ERR_INI_SIZE:
315 $this->_error_message
= __('The uploaded file exceeds the upload_max_filesize directive in php.ini.');
317 case 2: //UPLOAD_ERR_FORM_SIZE:
318 $this->_error_message
= __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.');
320 case 3: //UPLOAD_ERR_PARTIAL:
321 $this->_error_message
= __('The uploaded file was only partially uploaded.');
323 case 6: //UPLOAD_ERR_NO_TMP_DIR:
324 $this->_error_message
= __('Missing a temporary folder.');
326 case 7: //UPLOAD_ERR_CANT_WRITE:
327 $this->_error_message
= __('Failed to write file to disk.');
329 case 8: //UPLOAD_ERR_EXTENSION:
330 $this->_error_message
= __('File upload stopped by extension.');
333 $this->_error_message
= __('Unknown error in file upload.');
340 * strips some dimension from the multi-dimensional array from $_FILES
343 * $file['name']['multi_edit'][$primary] = [value]
344 * $file['type']['multi_edit'][$primary] = [value]
345 * $file['size']['multi_edit'][$primary] = [value]
346 * $file['tmp_name']['multi_edit'][$primary] = [value]
347 * $file['error']['multi_edit'][$primary] = [value]
351 * $file['name'] = [value]
352 * $file['type'] = [value]
353 * $file['size'] = [value]
354 * $file['tmp_name'] = [value]
355 * $file['error'] = [value]
358 * @todo re-check if requirements changes to PHP >= 4.2.0
361 * @param array $file the array
362 * @param string $primary
365 function fetchUploadedFromTblChangeRequestMultiple($file, $primary)
368 'name' => $file['name']['multi_edit'][$primary],
369 'type' => $file['type']['multi_edit'][$primary],
370 'size' => $file['size']['multi_edit'][$primary],
371 'tmp_name' => $file['tmp_name']['multi_edit'][$primary],
372 'error' => $file['error']['multi_edit'][$primary],
379 * sets the name if the file to the one selected in the tbl_change form
383 * @uses PMA_File::setLocalSelectedFile()
385 * @param string $key a numeric key used to identify the different rows
386 * @param string $primary_key
387 * @return boolean success
389 function setSelectedFromTblChangeRequest($key, $primary = null)
391 if (null !== $primary) {
392 if (! empty($_REQUEST['fields_uploadlocal_' . $key]['multi_edit'][$primary])
393 && is_string($_REQUEST['fields_uploadlocal_' . $key]['multi_edit'][$primary])) {
394 // ... whether with multiple rows ...
396 $is_bs_upload = FALSE;
398 // check if this field requires a repository upload
399 if (isset($_REQUEST['upload_blob_repo_' . $key])) {
400 $is_bs_upload = ($_REQUEST['upload_blob_repo_' . $key]['multi_edit'][0] == "on") ?
TRUE : FALSE;
403 // is a request to upload file to BLOB repository using uploadDir mechanism
405 $bs_db = $_REQUEST['db'];
406 $bs_table = $_REQUEST['table'];
407 $tmp_filename = $GLOBALS['cfg']['UploadDir'] . '/' . $_REQUEST['fields_uploadlocal_' . $key]['multi_edit'][$primary];
409 // check if fileinfo library exists
410 if ($PMA_Config->get('FILEINFO_EXISTS')) {
411 // attempt to init fileinfo
412 $finfo = finfo_open(FILEINFO_MIME
);
416 // pass in filename to fileinfo and close fileinfo handle after
417 $tmp_file_type = finfo_file($finfo, $tmp_filename);
421 // no fileinfo library exists, use file command
422 $tmp_file_type = exec("file -bi " . escapeshellarg($tmp_filename));
425 if (! $tmp_file_type) {
426 $tmp_file_type = NULL;
429 if (! $bs_db ||
!$bs_table) {
430 $this->_error_message
= $GLOBALS['strUploadErrorUnknown'];
433 $blob_url = PMA_BS_UpLoadFile($bs_db, $bs_table, $tmp_file_type, $tmp_filename);
434 PMA_File
::setRecentBLOBReference($blob_url);
435 } // end if ($is_bs_upload)
437 return $this->setLocalSelectedFile($_REQUEST['fields_uploadlocal_' . $key]['multi_edit'][$primary]);
441 } elseif (! empty($_REQUEST['fields_uploadlocal_' . $key])
442 && is_string($_REQUEST['fields_uploadlocal_' . $key])) {
444 $is_bs_upload = FALSE;
446 // check if this field requires a repository upload
447 if (isset($_REQUEST['upload_blob_repo_' . $key]))
448 $is_bs_upload = ($_REQUEST['upload_blob_repo_' . $key]['multi_edit'][0] == "on") ?
TRUE : FALSE;
450 // is a request to upload file to BLOB repository using uploadDir mechanism
453 // check if fileinfo library exists
454 if ($PMA_Config->get('FILEINFO_EXISTS'))
456 // attempt to init fileinfo
457 $finfo = finfo_open(FILEINFO_MIME
);
459 // if fileinfo exists
462 // pass in filename to fileinfo and close fileinfo handle after
463 $tmp_file_type = finfo_file($finfo, $tmp_filename);
467 else // no fileinfo library exists, use file command
468 $tmp_file_type = exec("file -bi " . escapeshellarg($tmp_filename));
471 $tmp_file_type = NULL;
473 $bs_db = $_REQUEST['db'];
474 $bs_table = $_REQUEST['table'];
475 if (!$bs_db ||
!$bs_table)
477 $this->_error_message
= $GLOBALS['strUploadErrorUnknown'];
480 $blob_url = PMA_BS_UpLoadFile($bs_db, $bs_table, $tmp_file_type, $tmp_filename);
481 PMA_File
::setRecentBLOBReference($blob_url);
483 } // end if ($is_bs_upload)
485 return $this->setLocalSelectedFile($_REQUEST['fields_uploadlocal_' . $key]);
493 * @uses PMA_File->$_error_message as return value
494 * @return string error message
498 return $this->_error_message
;
503 * @uses PMA_File->$_error_message to check it
504 * @return boolean whether an error occured or not
508 return ! empty($this->_error_message
);
512 * checks the superglobals provided if the tbl_change form is submitted
513 * and uses the submitted/selected file
516 * @uses PMA_File::setUploadedFromTblChangeRequest()
517 * @uses PMA_File::setSelectedFromTblChangeRequest()
518 * @param string $key a numeric key used to identify the different rows
519 * @param string $primary_key
520 * @return boolean success
522 function checkTblChangeForm($key, $primary_key)
524 if ($this->setUploadedFromTblChangeRequest($key, $primary_key)) {
526 $this->_error_message
= '';
529 } elseif ($this->setUploadedFromTblChangeRequest($key)) {
531 $this->_error_message = '';
534 } elseif ($this->setSelectedFromTblChangeRequest($key, $primary_key)) {
536 $this->_error_message
= '';
539 } elseif ($this->setSelectedFromTblChangeRequest($key)) {
541 $this->_error_message = '';
545 // all failed, whether just no file uploaded/selected or an error
553 * @uses PMA_File::setName()
554 * @uses PMA_securePath()
555 * @uses PMA_userDir()
556 * @uses $GLOBALS['cfg']['UploadDir']
557 * @param string $name
558 * @return boolean success
560 function setLocalSelectedFile($name)
562 if (empty($GLOBALS['cfg']['UploadDir'])) return false;
564 $this->setName(PMA_userDir($GLOBALS['cfg']['UploadDir']) . PMA_securePath($name));
565 if (! $this->isReadable()) {
566 $this->_error_message
= __('File could not be read');
567 $this->setName(null);
576 * @uses PMA_File::getName()
577 * @uses is_readable()
579 * @uses ob_end_clean()
580 * @return boolean whether the file is readable or not
582 function isReadable()
584 // suppress warnings from being displayed, but not from being logged
585 // any file access outside of open_basedir will issue a warning
587 $is_readable = is_readable($this->getName());
593 * If we are on a server with open_basedir, we must move the file
594 * before opening it. The FAQ 1.11 explains how to create the "./tmp"
595 * directory - if needed
597 * @todo replace error message with localized string
598 * @todo move check of $cfg['TempDir'] into PMA_Config?
600 * @uses $cfg['TempDir']
601 * @uses PMA_File::isReadable()
602 * @uses PMA_File::getName()
603 * @uses PMA_File::setName()
604 * @uses PMA_File::isTemp()
605 * @uses PMA_File::$_error_message
609 * @uses is_writable()
611 * @uses move_uploaded_file()
613 * @uses ob_end_clean()
614 * @return boolean whether uploaded fiel is fine or not
616 function checkUploadedFile()
618 if ($this->isReadable()) {
622 if (empty($GLOBALS['cfg']['TempDir']) ||
! is_writable($GLOBALS['cfg']['TempDir'])) {
623 // cannot create directory or access, point user to FAQ 1.11
624 $this->_error_message
= __('Error moving the uploaded file, see [a@./Documentation.html#faq1_11@Documentation]FAQ 1.11[/a]');
628 $new_file_to_upload = tempnam(realpath($GLOBALS['cfg']['TempDir']), basename($this->getName()));
630 // suppress warnings from being displayed, but not from being logged
631 // any file access outside of open_basedir will issue a warning
633 $move_uploaded_file_result = move_uploaded_file($this->getName(), $new_file_to_upload);
635 if (! $move_uploaded_file_result) {
636 $this->_error_message
= 'error while moving uploaded file';
640 $this->setName($new_file_to_upload);
643 if (! $this->isReadable()) {
644 $this->_error_message
= 'cannot read (moved) upload file';
652 * Detects what compression filse uses
654 * @todo move file read part into readChunk() or getChunk()
655 * @todo add support for compression plugins
656 * @uses PMA_File::$_compression to set it
657 * @uses PMA_File::getName()
665 * @return string MIME type of compression, none for none
667 function _detectCompression()
669 // suppress warnings from being displayed, but not from being logged
670 // f.e. any file access outside of open_basedir will issue a warning
672 $file = fopen($this->getName(), 'rb');
676 $this->_error_message
= __('File could not be read');
682 * get registered plugins for file compression
684 foreach (PMA_getPlugins($type = 'compression') as $plugin) {
685 if (call_user_func_array(array($plugin['classname'], 'canHandle'), array($this->getName()))) {
686 $this->setCompressionPlugin($plugin);
692 $test = fread($file, 4);
693 $len = strlen($test);
696 if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
697 $this->_compression
= 'application/gzip';
698 } elseif ($len >= 3 && substr($test, 0, 3) == 'BZh') {
699 $this->_compression
= 'application/bzip2';
700 } elseif ($len >= 4 && $test == "PK\003\004") {
701 $this->_compression
= 'application/zip';
703 $this->_compression
= 'none';
706 return $this->_compression
;
710 * whether the content should be decompressed before returned
712 function setDecompressContent($decompress)
714 $this->_decompress
= (bool) $decompress;
719 if (null === $this->_handle
) {
722 return $this->_handle
;
725 function setHandle($handle)
727 $this->_handle
= $handle;
735 if (! $this->_decompress
) {
736 $this->_handle
= @fopen
($this->getName(), 'r');
739 switch ($this->getCompression()) {
742 case 'application/bzip2':
743 if ($GLOBALS['cfg']['BZipDump'] && @function_exists
('bzopen')) {
744 $this->_handle
= @bzopen
($this->getName(), 'r');
746 $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());
750 case 'application/gzip':
751 if ($GLOBALS['cfg']['GZipDump'] && @function_exists
('gzopen')) {
752 $this->_handle
= @gzopen
($this->getName(), 'r');
754 $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());
758 case 'application/zip':
759 if ($GLOBALS['cfg']['ZipDump'] && @function_exists
('zip_open')) {
760 include_once './libraries/zip_extension.lib.php';
761 $result = PMA_getZipContents($this->getName());
762 if (! empty($result['error'])) {
763 $this->_error_message
= PMA_Message
::rawError($result['error']);
766 $this->content_uncompressed
= $result['data'];
770 $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());
775 $this->_handle
= @fopen
($this->getName(), 'r');
778 $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());
786 function getCharset()
788 return $this->_charset
;
791 function setCharset($charset)
793 $this->_charset
= $charset;
797 * @uses PMA_File::$_compression as return value
798 * @uses PMA_File::detectCompression()
799 * @return string MIME type of compression, none for none
802 function getCompression()
804 if (null === $this->_compression
) {
805 return $this->_detectCompression();
808 return $this->_compression
;
812 * advances the file pointer in the file handle by $length bytes/chars
814 * @param integer $length numbers of chars/bytes to skip
816 * @todo this function is unused
818 function advanceFilePointer($length)
820 while ($length > 0) {
821 // Disable read progresivity, otherwise we eat all memory!
822 $read_multiply = 1; // required?
823 $this->getNextChunk($length);
824 $length -= $this->getChunkSize();
829 * http://bugs.php.net/bug.php?id=29532
830 * bzip reads a maximum of 8192 bytes on windows systems
831 * @todo this function is unused
833 function getNextChunk($max_size = null)
835 if (null !== $max_size) {
836 $size = min($max_size, $this->getChunkSize());
838 $size = $this->getChunkSize();
841 // $result = $this->handler->getNextChunk($size);
843 switch ($this->getCompression()) {
844 case 'application/bzip2':
846 while (strlen($result) < $size - 8192 && ! feof($this->getHandle())) {
847 $result .= bzread($this->getHandle(), $size);
850 case 'application/gzip':
851 $result = gzread($this->getHandle(), $size);
853 case 'application/zip':
855 * if getNextChunk() is used some day,
856 * replace this code by code similar to the one
859 include_once './libraries/unzip.lib.php';
860 $import_handle = new SimpleUnzip();
861 $import_handle->ReadFile($this->getName());
862 if ($import_handle->Count() == 0) {
863 $this->_error_message = __('No files found inside ZIP archive!');
865 } elseif ($import_handle->GetError(0) != 0) {
866 $this->_error_message = __('Error in ZIP archive:')
867 . ' ' . $import_handle->GetErrorMsg(0);
870 $result = $import_handle->GetData(0);
875 $result = fread($this->getHandle(), $size);
882 echo strlen($result) . ' - ';
883 echo (@$GLOBALS['__len__'] +
= strlen($result)) . ' - ';
884 echo $this->_error_message
;
887 if ($GLOBALS['charset_conversion']) {
888 $result = PMA_convert_string($this->getCharset(), $GLOBALS['charset'], $result);
891 * Skip possible byte order marks (I do not think we need more
892 * charsets, but feel free to add more, you can use wikipedia for
893 * reference: <http://en.wikipedia.org/wiki/Byte_Order_Mark>)
895 * @todo BOM could be used for charset autodetection
897 if ($this->getOffset() === 0) {
899 if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
900 $result = substr($result, 3);
902 } elseif (strncmp($result, "\xFE\xFF", 2) == 0
903 ||
strncmp($result, "\xFF\xFE", 2) == 0) {
904 $result = substr($result, 2);
909 $this->_offset +
= $size;
918 return $this->_offset
;
921 function getChunkSize()
923 return $this->_chunk_size
;
926 function setChunkSize($chunk_size)
928 $this->_chunk_size
= (int) $chunk_size;
931 function getContentLength()
933 return strlen($this->_content
);
938 if ($this->getHandle()) {
939 return feof($this->getHandle());
941 return ($this->getOffset() >= $this->getContentLength());
947 * sets reference to most recent BLOB repository reference
950 * @param string - BLOB repository reference
952 static function setRecentBLOBReference($ref)
954 PMA_File
::$_recent_bs_reference = $ref;
958 * retrieves reference to most recent BLOB repository reference
961 * @return string - most recent BLOB repository reference
963 static function getRecentBLOBReference()
965 $ref = PMA_File
::$_recent_bs_reference;
966 PMA_File
::$_recent_bs_reference = NULL;