Translation update done using Pootle.
[phpmyadmin/ammar_yasir.git] / libraries / File.class.php
blob4fd33422579a69b8b67faab7dcf6a8d46d886cfd
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * file upload functions
6 * @package phpMyAdmin
7 */
9 /**
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]
14 * @package phpMyAdmin
16 class PMA_File
18 /**
19 * @var string the temporary file name
20 * @access protected
22 var $_name = null;
24 /**
25 * @var string the content
26 * @access protected
28 var $_content = null;
30 /**
31 * @var string the error message
32 * @access protected
34 var $_error_message = '';
36 /**
37 * @var bool whether the file is temporary or not
38 * @access protected
40 var $_is_temp = false;
42 /**
43 * @var string type of compression
44 * @access protected
46 var $_compression = null;
48 /**
49 * @var integer
51 var $_offset = 0;
53 /**
54 * @var integer size of chunk to read with every step
56 var $_chunk_size = 32768;
58 /**
59 * @var resource file handle
61 var $_handle = null;
63 /**
64 * @var boolean whether to decompress content before returning
66 var $_decompress = false;
68 /**
69 * @var string charset of file
71 var $_charset = null;
73 /**
74 * @staticvar string most recent BLOB repository reference
76 static $_recent_bs_reference = NULL;
78 /**
79 * constructor
81 * @access public
82 * @uses PMA_File::setName()
83 * @param string $name file name
85 function __construct($name = false)
87 if ($name) {
88 $this->setName($name);
92 /**
93 * destructor
95 * @see PMA_File::cleanUp()
96 * @access public
97 * @uses PMA_File::cleanUp()
99 function __destruct()
101 $this->cleanUp();
105 * deletes file if it is temporary, usally from a moved upload file
107 * @access public
108 * @uses PMA_File::delet()
109 * @uses PMA_File::isTemp()
110 * @return boolean success
112 function cleanUp()
114 if ($this->isTemp()) {
115 return $this->delete();
118 return true;
122 * deletes the file
124 * @access public
125 * @uses PMA_File::getName()
126 * @uses unlink()
127 * @return boolean success
129 function delete()
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
138 * @access public
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;
153 * accessor
155 * @access public
156 * @uses PMA_File::$_name
157 * @param string $name file name
159 function setName($name)
161 $this->_name = trim($name);
165 * @access public
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()
173 * @uses filesize()
174 * @uses fread()
175 * @uses fopen()
176 * @uses bin2hex()
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()) {
183 return false;
186 if (! $this->isReadable()) {
187 return false;
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;
211 * @access public
212 * @uses PMA_File::getName()
213 * @uses is_uploaded_file()
215 function isUploaded()
217 return is_uploaded_file($this->getName());
221 * accessor
223 * @access public
224 * @uses PMA_File::$name as return value
225 * @return string PMA_File::$_name
227 function getName()
229 return $this->_name;
233 * @todo replace error message with localized string
234 * @access public
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';
248 return false;
251 return true;
255 * @access public
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
261 * @uses $_FILES
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])) {
269 return false;
271 $file = PMA_File::fetchUploadedFromTblChangeRequestMultiple($_FILES['fields_upload'], $rownumber, $key);
273 // for blobstreaming
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
281 if ($is_bs_upload) {
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'];
293 return FALSE;
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']);
306 break;
307 case 4: //UPLOAD_ERR_NO_FILE:
308 break;
309 case 1: //UPLOAD_ERR_INI_SIZE:
310 $this->_error_message = __('The uploaded file exceeds the upload_max_filesize directive in php.ini.');
311 break;
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.');
314 break;
315 case 3: //UPLOAD_ERR_PARTIAL:
316 $this->_error_message = __('The uploaded file was only partially uploaded.');
317 break;
318 case 6: //UPLOAD_ERR_NO_TMP_DIR:
319 $this->_error_message = __('Missing a temporary folder.');
320 break;
321 case 7: //UPLOAD_ERR_CANT_WRITE:
322 $this->_error_message = __('Failed to write file to disk.');
323 break;
324 case 8: //UPLOAD_ERR_EXTENSION:
325 $this->_error_message = __('File upload stopped by extension.');
326 break;
327 default:
328 $this->_error_message = __('Unknown error in file upload.');
329 } // end switch
331 return false;
335 * strips some dimension from the multi-dimensional array from $_FILES
337 * <code>
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]
344 * // becomes:
346 * $file['name'] = [value]
347 * $file['type'] = [value]
348 * $file['size'] = [value]
349 * $file['tmp_name'] = [value]
350 * $file['error'] = [value]
351 * </code>
353 * @todo re-check if requirements changes to PHP >= 4.2.0
354 * @access public
355 * @static
356 * @param array $file the array
357 * @param string $rownumber
358 * @param string $key
359 * @return array
361 function fetchUploadedFromTblChangeRequestMultiple($file, $rownumber, $key)
363 $new_file = array(
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],
371 return $new_file;
375 * sets the name if the file to the one selected in the tbl_change form
377 * @access public
378 * @uses $_REQUEST
379 * @uses PMA_File::setLocalSelectedFile()
380 * @uses is_string()
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 ...
390 // for blobstreaming
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
399 if ($is_bs_upload) {
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);
409 // fileinfo exists
410 if ($finfo) {
411 // pass in filename to fileinfo and close fileinfo handle after
412 $tmp_file_type = finfo_file($finfo, $tmp_filename);
413 finfo_close($finfo);
415 } else {
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'];
426 return FALSE;
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]);
433 } else {
434 return false;
439 * @access public
440 * @uses PMA_File->$_error_message as return value
441 * @return string error message
443 function getError()
445 return $this->_error_message;
449 * @access public
450 * @uses PMA_File->$_error_message to check it
451 * @return boolean whether an error occured or not
453 function isError()
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
462 * @access public
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)) {
472 // well done ...
473 $this->_error_message = '';
474 return true;
475 } elseif ($this->setSelectedFromTblChangeRequest($key, $rownumber)) {
476 // well done ...
477 $this->_error_message = '';
478 return true;
480 // all failed, whether just no file uploaded/selected or an error
482 return false;
487 * @access public
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);
503 return false;
506 return true;
510 * @access public
511 * @uses PMA_File::getName()
512 * @uses is_readable()
513 * @uses ob_start()
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
521 ob_start();
522 $is_readable = is_readable($this->getName());
523 ob_end_clean();
524 return $is_readable;
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?
534 * @access public
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
541 * @uses is_dir()
542 * @uses mkdir()
543 * @uses chmod()
544 * @uses is_writable()
545 * @uses basename()
546 * @uses move_uploaded_file()
547 * @uses ob_start()
548 * @uses ob_end_clean()
549 * @return boolean whether uploaded fiel is fine or not
551 function checkUploadedFile()
553 if ($this->isReadable()) {
554 return true;
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]');
560 return false;
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
567 ob_start();
568 $move_uploaded_file_result = move_uploaded_file($this->getName(), $new_file_to_upload);
569 ob_end_clean();
570 if (! $move_uploaded_file_result) {
571 $this->_error_message = 'error while moving uploaded file';
572 return false;
575 $this->setName($new_file_to_upload);
576 $this->isTemp(true);
578 if (! $this->isReadable()) {
579 $this->_error_message = 'cannot read (moved) upload file';
580 return false;
583 return true;
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()
593 * @uses fopen()
594 * @uses fread()
595 * @uses strlen()
596 * @uses fclose()
597 * @uses chr()
598 * @uses substr()
599 * @access protected
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
606 ob_start();
607 $file = fopen($this->getName(), 'rb');
608 ob_end_clean();
610 if (! $file) {
611 $this->_error_message = __('File could not be read');
612 return false;
616 * @todo
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);
622 break;
627 $test = fread($file, 4);
628 $len = strlen($test);
629 fclose($file);
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';
637 } else {
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;
652 function getHandle()
654 if (null === $this->_handle) {
655 $this->open();
657 return $this->_handle;
660 function setHandle($handle)
662 $this->_handle = $handle;
668 function open()
670 if (! $this->_decompress) {
671 $this->_handle = @fopen($this->getName(), 'r');
674 switch ($this->getCompression()) {
675 case false:
676 return false;
677 case 'application/bzip2':
678 if ($GLOBALS['cfg']['BZipDump'] && @function_exists('bzopen')) {
679 $this->_handle = @bzopen($this->getName(), 'r');
680 } else {
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());
682 return false;
684 break;
685 case 'application/gzip':
686 if ($GLOBALS['cfg']['GZipDump'] && @function_exists('gzopen')) {
687 $this->_handle = @gzopen($this->getName(), 'r');
688 } else {
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());
690 return false;
692 break;
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']);
699 return false;
700 } else {
701 $this->content_uncompressed = $result['data'];
703 unset($result);
704 } else {
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());
706 return false;
708 break;
709 case 'none':
710 $this->_handle = @fopen($this->getName(), 'r');
711 break;
712 default:
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());
714 return false;
715 break;
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
735 * @access public
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
750 * @return boolean
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());
772 } else {
773 $size = $this->getChunkSize();
776 // $result = $this->handler->getNextChunk($size);
777 $result = '';
778 switch ($this->getCompression()) {
779 case 'application/bzip2':
780 $result = '';
781 while (strlen($result) < $size - 8192 && ! feof($this->getHandle())) {
782 $result .= bzread($this->getHandle(), $size);
784 break;
785 case 'application/gzip':
786 $result = gzread($this->getHandle(), $size);
787 break;
788 case 'application/zip':
790 * if getNextChunk() is used some day,
791 * replace this code by code similar to the one
792 * in open()
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!');
799 return false;
800 } elseif ($import_handle->GetError(0) != 0) {
801 $this->_error_message = __('Error in ZIP archive:')
802 . ' ' . $import_handle->GetErrorMsg(0);
803 return false;
804 } else {
805 $result = $import_handle->GetData(0);
808 break;
809 case 'none':
810 $result = fread($this->getHandle(), $size);
811 break;
812 default:
813 return false;
816 echo $size . ' - ';
817 echo strlen($result) . ' - ';
818 echo (@$GLOBALS['__len__'] += strlen($result)) . ' - ';
819 echo $this->_error_message;
820 echo '<hr />';
822 if ($GLOBALS['charset_conversion']) {
823 $result = PMA_convert_string($this->getCharset(), $GLOBALS['charset'], $result);
824 } else {
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) {
833 // UTF-8
834 if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
835 $result = substr($result, 3);
836 // UTF-16 BE, LE
837 } elseif (strncmp($result, "\xFE\xFF", 2) == 0
838 || strncmp($result, "\xFF\xFE", 2) == 0) {
839 $result = substr($result, 2);
844 $this->_offset += $size;
845 if (0 === $result) {
846 return true;
848 return $result;
851 function getOffset()
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);
871 function eof()
873 if ($this->getHandle()) {
874 return feof($this->getHandle());
875 } else {
876 return ($this->getOffset() >= $this->getContentLength());
882 * sets reference to most recent BLOB repository reference
884 * @access public
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
895 * @access public
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;
903 return $ref;