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]
18 * @var string the temporary file name
24 * @var string the content
30 * @var string the error message
33 var $_error_message = '';
36 * @var bool whether the file is temporary or not
39 var $_is_temp = false;
42 * @var string type of compression
45 var $_compression = null;
53 * @var integer size of chunk to read with every step
55 var $_chunk_size = 32768;
58 * @var resource file handle
63 * @var boolean whether to decompress content before returning
65 var $_decompress = false;
68 * @var string charset of file
73 * old PHP 4 style constructor
75 * @see PMA_File::__construct()
76 * @uses PMA_File::__construct()
79 function PMA_File($name = false)
81 $this->__construct($name);
88 * @uses PMA_File::setName()
89 * @param string $name file name
91 function __construct($name = false)
94 $this->setName($name);
101 * @see PMA_File::cleanUp()
103 * @uses PMA_File::cleanUp()
105 function __destruct()
111 * deletes file if it is temporary, usally from a moved upload file
114 * @uses PMA_File::delet()
115 * @uses PMA_File::isTemp()
116 * @return boolean success
120 if ($this->isTemp()) {
121 return $this->delete();
131 * @uses PMA_File::getName()
133 * @return boolean success
137 return unlink($this->getName());
141 * checks or sets the temp flag for this file
142 * file objects with temp flags are deleted with object destruction
145 * @uses PMA_File::$_is_temp to set and read it
146 * @param boolean sets the temp flag
147 * @return boolean PMA_File::$_is_temp
149 function isTemp($is_temp = null)
151 if (null !== $is_temp) {
152 $this->_is_temp
= (bool) $is_temp;
155 return $this->_is_temp
;
162 * @uses PMA_File::$_name
163 * @param string $name file name
166 function setName($name)
168 $this->_name
= trim($name);
173 * @uses PMA_File::getName()
174 * @uses PMA_File::isUploaded()
175 * @uses PMA_File::checkUploadedFile()
176 * @uses PMA_File::isReadable()
177 * @uses PMA_File::$_content
178 * @uses function_exists()
179 * @uses file_get_contents()
184 * @return string binary file content
186 function getContent($as_binary = true, $offset = 0, $length = null)
188 if (null === $this->_content
) {
189 if ($this->isUploaded() && ! $this->checkUploadedFile()) {
193 if (! $this->isReadable()) {
197 if (function_exists('file_get_contents')) {
198 $this->_content
= file_get_contents($this->getName());
199 } elseif ($size = filesize($this->getName())) {
200 $this->_content
= fread(fopen($this->getName(), 'rb'), $size);
204 if (! empty($this->_content
) && $as_binary) {
205 return '0x' . bin2hex($this->_content
);
208 if (null !== $length) {
209 return substr($this->_content
, $offset, $length);
210 } elseif ($offset > 0) {
211 return substr($this->_content
, $offset);
214 return $this->_content
;
219 * @uses PMA_File::getName()
220 * @uses is_uploaded_file()
222 function isUploaded()
224 return is_uploaded_file($this->getName());
231 * @uses PMA_File::$name as return value
232 * @return string PMA_File::$_name
240 * @todo replace error message with localized string
242 * @uses PMA_File::isUploaded()
243 * @uses PMA_File::setName()
244 * @uses PMA_File::$_error_message
245 * @param string name of file uploaded
246 * @return boolean success
248 function setUploadedFile($name)
250 $this->setName($name);
252 if (! $this->isUploaded()) {
253 $this->setName(null);
254 $this->_error_message
= 'not an uploaded file';
263 * @uses PMA_File::fetchUploadedFromTblChangeRequestMultiple()
264 * @uses PMA_File::setUploadedFile()
265 * @uses PMA_File::$_error_message
266 * @uses $GLOBALS['strUploadErrorIniSize']
267 * @uses $GLOBALS['strUploadErrorFormSize']
268 * @uses $GLOBALS['strUploadErrorPartial']
269 * @uses $GLOBALS['strUploadErrorNoTempDir']
270 * @uses $GLOBALS['strUploadErrorCantWrite']
271 * @uses $GLOBALS['strUploadErrorExtension']
272 * @uses $GLOBALS['strUploadErrorUnknown']
274 * @param string $key a numeric key used to identify the different rows
275 * @param string $primary_key
276 * @return boolean success
278 function setUploadedFromTblChangeRequest($key, $primary = null)
280 if (! isset($_FILES['fields_upload_' . $key])) {
284 $file = $_FILES['fields_upload_' . $key];
285 if (null !== $primary) {
286 $file = PMA_File
::fetchUploadedFromTblChangeRequestMultiple($file, $primary);
289 // check for file upload errors
290 switch ($file['error']) {
291 // cybot_tm: we do not use the PHP constants here cause not all constants
292 // are defined in all versions of PHP - but the correct constants names
293 // are given as comment
294 case 0: //UPLOAD_ERR_OK:
295 return $this->setUploadedFile($file['tmp_name']);
297 case 4: //UPLOAD_ERR_NO_FILE:
299 case 1: //UPLOAD_ERR_INI_SIZE:
300 $this->_error_message
= $GLOBALS['strUploadErrorIniSize'];
302 case 2: //UPLOAD_ERR_FORM_SIZE:
303 $this->_error_message
= $GLOBALS['strUploadErrorFormSize'];
305 case 3: //UPLOAD_ERR_PARTIAL:
306 $this->_error_message
= $GLOBALS['strUploadErrorPartial'];
308 case 6: //UPLOAD_ERR_NO_TMP_DIR:
309 $this->_error_message
= $GLOBALS['strUploadErrorNoTempDir'];
311 case 7: //UPLOAD_ERR_CANT_WRITE:
312 $this->_error_message
= $GLOBALS['strUploadErrorCantWrite'];
314 case 8: //UPLOAD_ERR_EXTENSION:
315 $this->_error_message
= $GLOBALS['strUploadErrorExtension'];
318 $this->_error_message
= $GLOBALS['strUploadErrorUnknown'];
325 * strips some dimension from the multi-dimensional array from $_FILES
328 * $file['name']['multi_edit'][$primary] = [value]
329 * $file['type']['multi_edit'][$primary] = [value]
330 * $file['size']['multi_edit'][$primary] = [value]
331 * $file['tmp_name']['multi_edit'][$primary] = [value]
332 * $file['error']['multi_edit'][$primary] = [value]
336 * $file['name'] = [value]
337 * $file['type'] = [value]
338 * $file['size'] = [value]
339 * $file['tmp_name'] = [value]
340 * $file['error'] = [value]
343 * @todo re-check if requirements changes to PHP >= 4.2.0
346 * @param array $file the array
347 * @param string $primary
350 function fetchUploadedFromTblChangeRequestMultiple($file, $primary)
353 'name' => $file['name']['multi_edit'][$primary],
354 'type' => $file['type']['multi_edit'][$primary],
355 'size' => $file['size']['multi_edit'][$primary],
356 'tmp_name' => $file['tmp_name']['multi_edit'][$primary],
357 //'error' => $file['error']['multi_edit'][$primary],
360 // ['error'] exists since PHP 4.2.0
361 if (isset($file['error'])) {
362 $new_file['error'] = $file['error']['multi_edit'][$primary];
369 * sets the name if the file to the one selected in the tbl_change form
373 * @uses PMA_File::setLocalSelectedFile()
375 * @param string $key a numeric key used to identify the different rows
376 * @param string $primary_key
377 * @return boolean success
379 function setSelectedFromTblChangeRequest($key, $primary = null)
381 if (null !== $primary) {
382 if (! empty($_REQUEST['fields_uploadlocal_' . $key]['multi_edit'][$primary])
383 && is_string($_REQUEST['fields_uploadlocal_' . $key]['multi_edit'][$primary])) {
384 // ... whether with multiple rows ...
385 return $this->setLocalSelectedFile($_REQUEST['fields_uploadlocal_' . $key]['multi_edit'][$primary]);
389 } elseif (! empty($_REQUEST['fields_uploadlocal_' . $key])
390 && is_string($_REQUEST['fields_uploadlocal_' . $key])) {
391 return $this->setLocalSelectedFile($_REQUEST['fields_uploadlocal_' . $key]);
399 * @uses PMA_File->$_error_message as return value
400 * @return string error message
404 return $this->_error_message
;
409 * @uses PMA_File->$_error_message to check it
410 * @return boolean whether an error occured or not
414 return ! empty($this->_error_message
);
418 * checks the superglobals provided if the tbl_change form is submitted
419 * and uses the submitted/selected file
422 * @uses PMA_File::setUploadedFromTblChangeRequest()
423 * @uses PMA_File::setSelectedFromTblChangeRequest()
424 * @param string $key a numeric key used to identify the different rows
425 * @param string $primary_key
426 * @return boolean success
428 function checkTblChangeForm($key, $primary_key)
430 if ($this->setUploadedFromTblChangeRequest($key, $primary_key)) {
432 $this->_error_message
= '';
435 } elseif ($this->setUploadedFromTblChangeRequest($key)) {
437 $this->_error_message = '';
440 } elseif ($this->setSelectedFromTblChangeRequest($key, $primary_key)) {
442 $this->_error_message
= '';
445 } elseif ($this->setSelectedFromTblChangeRequest($key)) {
447 $this->_error_message = '';
451 // all failed, whether just no file uploaded/selected or an error
459 * @uses $GLOBALS['strFileCouldNotBeRead']
460 * @uses PMA_File::setName()
461 * @uses PMA_securePath()
462 * @uses PMA_userDir()
463 * @uses $GLOBALS['cfg']['UploadDir']
464 * @param string $name
465 * @return boolean success
467 function setLocalSelectedFile($name)
469 if (empty($GLOBALS['cfg']['UploadDir'])) return false;
471 $this->setName(PMA_userDir($GLOBALS['cfg']['UploadDir']) . PMA_securePath($name));
472 if (! $this->isReadable()) {
473 $this->_error_message
= $GLOBALS['strFileCouldNotBeRead'];
474 $this->setName(null);
483 * @uses PMA_File::getName()
484 * @uses is_readable()
486 * @uses ob_end_clean()
487 * @return boolean whether the file is readable or not
489 function isReadable()
491 // suppress warnings from being displayed, but not from being logged
492 // any file access outside of open_basedir will issue a warning
494 $is_readable = is_readable($this->getName());
500 * If we are on a server with open_basedir, we must move the file
501 * before opening it. The FAQ 1.11 explains how to create the "./tmp"
502 * directory - if needed
504 * @todo replace error message with localized string
505 * @todo move check of $cfg['TempDir'] into PMA_Config?
507 * @uses $cfg['TempDir']
508 * @uses $GLOBALS['strFieldInsertFromFileTempDirNotExists']
509 * @uses PMA_File::isReadable()
510 * @uses PMA_File::getName()
511 * @uses PMA_File::setName()
512 * @uses PMA_File::isTemp()
513 * @uses PMA_File::$_error_message
517 * @uses is_writable()
519 * @uses move_uploaded_file()
521 * @uses ob_end_clean()
522 * @return boolean whether uploaded fiel is fine or not
524 function checkUploadedFile()
526 if ($this->isReadable()) {
530 if (empty($GLOBALS['cfg']['TempDir']) ||
! is_writable($GLOBALS['cfg']['TempDir'])) {
531 // cannot create directory or access, point user to FAQ 1.11
532 $this->_error_message
= $GLOBALS['strFieldInsertFromFileTempDirNotExists'];
536 $new_file_to_upload = tempnam(realpath($GLOBALS['cfg']['TempDir']), basename($this->getName()));
538 // suppress warnings from being displayed, but not from being logged
539 // any file access outside of open_basedir will issue a warning
541 $move_uploaded_file_result = move_uploaded_file($this->getName(), $new_file_to_upload);
543 if (! $move_uploaded_file_result) {
544 $this->_error_message
= 'error while moving uploaded file';
548 $this->setName($new_file_to_upload);
551 if (! $this->isReadable()) {
552 $this->_error_message
= 'cannot read (moved) upload file';
560 * Detects what compression filse uses
562 * @todo move file read part into readChunk() or getChunk()
563 * @todo add support for compression plugins
564 * @uses $GLOBALS['strFileCouldNotBeRead']
565 * @uses PMA_File::$_compression to set it
566 * @uses PMA_File::getName()
574 * @return string MIME type of compression, none for none
576 function _detectCompression()
578 // suppress warnings from being displayed, but not from being logged
579 // f.e. any file access outside of open_basedir will issue a warning
581 $file = fopen($this->getName(), 'rb');
585 $this->_error_message
= $GLOBALS['strFileCouldNotBeRead'];
591 * get registered plugins for file compression
593 foreach (PMA_getPlugins($type = 'compression') as $plugin) {
594 if (call_user_func_array(array($plugin['classname'], 'canHandle'), array($this->getName()))) {
595 $this->setCompressionPlugin($plugin);
601 $test = fread($file, 4);
602 $len = strlen($test);
605 if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
606 $this->_compression
= 'application/gzip';
607 } elseif ($len >= 3 && substr($test, 0, 3) == 'BZh') {
608 $this->_compression
= 'application/bzip2';
609 } elseif ($len >= 4 && $test == "PK\003\004") {
610 $this->_compression
= 'application/zip';
612 $this->_compression
= 'none';
615 return $this->_compression
;
619 * whether the content should be decompressed before returned
621 function setDecompressContent($decompress)
623 $this->_decompress
= (bool) $decompress;
628 if (null === $this->_handle
) {
631 return $this->_handle
;
634 function setHandle($handle)
636 $this->_handle
= $handle;
644 if (! $this->_decompress
) {
645 $this->_handle
= @fopen
($this->getName(), 'r');
648 switch ($this->getCompression()) {
651 case 'application/bzip2':
652 if ($GLOBALS['cfg']['BZipDump'] && @function_exists
('bzopen')) {
653 $this->_handle
= @bzopen
($this->getName(), 'r');
655 $this->_error_message
= sprintf($GLOBALS['strUnsupportedCompressionDetected'], $this->getCompression());
659 case 'application/gzip':
660 if ($GLOBALS['cfg']['GZipDump'] && @function_exists
('gzopen')) {
661 $this->_handle
= @gzopen
($this->getName(), 'r');
663 $this->_error_message
= sprintf($GLOBALS['strUnsupportedCompressionDetected'], $this->getCompression());
667 case 'application/zip':
668 if ($GLOBALS['cfg']['GZipDump'] && @function_exists
('gzinflate')) {
669 include_once './libraries/unzip.lib.php';
670 $this->_handle
= new SimpleUnzip();
671 $this->_handle
->ReadFile($this->getName());
672 if ($this->_handle
->Count() == 0) {
673 $this->_error_message
= $GLOBALS['strNoFilesFoundInZip'];
675 } elseif ($this->_handle
->GetError(0) != 0) {
676 $this->_error_message
= $GLOBALS['strErrorInZipFile'] . ' ' . $this->_handle
->GetErrorMsg(0);
679 $this->content_uncompressed
= $this->_handle
->GetData(0);
681 // We don't need to store it further
682 $this->_handle
= null;
684 $this->_error_message
= sprintf($GLOBALS['strUnsupportedCompressionDetected'], $this->getCompression());
689 $this->_handle
= @fopen
($this->getName(), 'r');
692 $this->_error_message
= sprintf($GLOBALS['strUnsupportedCompressionDetected'], $this->getCompression());
700 function getCharset()
702 return $this->_charset
;
705 function setCharset($charset)
707 $this->_charset
= $charset;
711 * @uses PMA_File::$_compression as return value
712 * @uses PMA_File::detectCompression()
713 * @return string MIME type of compression, none for none
716 function getCompression()
718 if (null === $this->_compression
) {
719 return $this->_detectCompression();
722 return $this->_compression
;
726 * advances the file pointer in the file handle by $length bytes/chars
728 * @param integer $length numbers of chars/bytes to skip
731 function advanceFilePointer($length)
733 while ($length > 0) {
734 // Disable read progresivity, otherwise we eat all memory!
735 $read_multiply = 1; // required?
736 $this->getNextChunk($length);
737 $length -= $this->getChunkSize();
742 * http://bugs.php.net/bug.php?id=29532
743 * bzip reads a maximum of 8192 bytes on windows systems
746 function getNextChunk($max_size = null)
748 if (null !== $max_size) {
749 $size = min($max_size, $this->getChunkSize());
751 $size = $this->getChunkSize();
754 // $result = $this->handler->getNextChunk($size);
756 switch ($this->getCompression()) {
757 case 'application/bzip2':
759 while (strlen($result) < $size - 8192 && ! feof($this->getHandle())) {
760 $result .= bzread($this->getHandle(), $size);
763 case 'application/gzip':
764 $result = gzread($this->getHandle(), $size);
766 case 'application/zip':
767 include_once './libraries/unzip.lib.php';
768 $import_handle = new SimpleUnzip();
769 $import_handle->ReadFile($this->getName());
770 if ($import_handle->Count() == 0) {
771 $this->_error_message
= $GLOBALS['strNoFilesFoundInZip'];
773 } elseif ($import_handle->GetError(0) != 0) {
774 $this->_error_message
= $GLOBALS['strErrorInZipFile']
775 . ' ' . $import_handle->GetErrorMsg(0);
778 $result = $import_handle->GetData(0);
782 $result = fread($this->getHandle(), $size);
789 echo strlen($result) . ' - ';
790 echo (@$GLOBALS['__len__'] +
= strlen($result)) . ' - ';
791 echo $this->_error_message
;
794 if ($GLOBALS['charset_conversion']) {
795 $result = PMA_convert_string($this->getCharset(), $GLOBALS['charset'], $result);
798 * Skip possible byte order marks (I do not think we need more
799 * charsets, but feel free to add more, you can use wikipedia for
800 * reference: <http://en.wikipedia.org/wiki/Byte_Order_Mark>)
802 * @todo BOM could be used for charset autodetection
804 if ($this->getOffset() === 0) {
806 if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
807 $result = substr($result, 3);
809 } elseif (strncmp($result, "\xFE\xFF", 2) == 0
810 ||
strncmp($result, "\xFF\xFE", 2) == 0) {
811 $result = substr($result, 2);
816 $this->_offset +
= $size;
825 return $this->_offset
;
828 function getChunkSize()
830 return $this->_chunk_size
;
833 function setChunkSize($chunk_size)
835 $this->_chunk_size
= (int) $chunk_size;
838 function getContentLength()
840 return strlen($this->_content
);
845 if ($this->getHandle()) {
846 return feof($this->getHandle());
848 return ($this->getOffset() >= $this->getContentLength());