File.class.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * file upload functions
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. if (! defined('PHPMYADMIN')) {
  9. exit;
  10. }
  11. /**
  12. * File wrapper class
  13. *
  14. * @todo when uploading a file into a blob field, should we also consider using
  15. * chunks like in import? UPDATE `table` SET `field` = `field` + [chunk]
  16. *
  17. * @package PhpMyAdmin
  18. */
  19. class PMA_File
  20. {
  21. /**
  22. * @var string the temporary file name
  23. * @access protected
  24. */
  25. var $_name = null;
  26. /**
  27. * @var string the content
  28. * @access protected
  29. */
  30. var $_content = null;
  31. /**
  32. * @var string the error message
  33. * @access protected
  34. */
  35. var $_error_message = '';
  36. /**
  37. * @var bool whether the file is temporary or not
  38. * @access protected
  39. */
  40. var $_is_temp = false;
  41. /**
  42. * @var string type of compression
  43. * @access protected
  44. */
  45. var $_compression = null;
  46. /**
  47. * @var integer
  48. */
  49. var $_offset = 0;
  50. /**
  51. * @var integer size of chunk to read with every step
  52. */
  53. var $_chunk_size = 32768;
  54. /**
  55. * @var resource file handle
  56. */
  57. var $_handle = null;
  58. /**
  59. * @var boolean whether to decompress content before returning
  60. */
  61. var $_decompress = false;
  62. /**
  63. * @var string charset of file
  64. */
  65. var $_charset = null;
  66. /**
  67. * constructor
  68. *
  69. * @param boolean|string $name file name or false
  70. *
  71. * @access public
  72. */
  73. public function __construct($name = false)
  74. {
  75. if ($name) {
  76. $this->setName($name);
  77. }
  78. }
  79. /**
  80. * destructor
  81. *
  82. * @see PMA_File::cleanUp()
  83. * @access public
  84. */
  85. public function __destruct()
  86. {
  87. $this->cleanUp();
  88. }
  89. /**
  90. * deletes file if it is temporary, usually from a moved upload file
  91. *
  92. * @access public
  93. * @return boolean success
  94. */
  95. public function cleanUp()
  96. {
  97. if ($this->isTemp()) {
  98. return $this->delete();
  99. }
  100. return true;
  101. }
  102. /**
  103. * deletes the file
  104. *
  105. * @access public
  106. * @return boolean success
  107. */
  108. public function delete()
  109. {
  110. return unlink($this->getName());
  111. }
  112. /**
  113. * checks or sets the temp flag for this file
  114. * file objects with temp flags are deleted with object destruction
  115. *
  116. * @param boolean $is_temp sets the temp flag
  117. *
  118. * @return boolean PMA_File::$_is_temp
  119. * @access public
  120. */
  121. public function isTemp($is_temp = null)
  122. {
  123. if (null !== $is_temp) {
  124. $this->_is_temp = (bool) $is_temp;
  125. }
  126. return $this->_is_temp;
  127. }
  128. /**
  129. * accessor
  130. *
  131. * @param string $name file name
  132. *
  133. * @return void
  134. * @access public
  135. */
  136. public function setName($name)
  137. {
  138. $this->_name = trim($name);
  139. }
  140. /**
  141. * Gets file content
  142. *
  143. * @param boolean $as_binary whether to return content as binary
  144. * @param integer $offset starting offset
  145. * @param integer $length length
  146. *
  147. * @return mixed the binary file content as a string,
  148. * or false if no content
  149. *
  150. * @access public
  151. */
  152. public function getContent($as_binary = true, $offset = 0, $length = null)
  153. {
  154. if (null === $this->_content) {
  155. if ($this->isUploaded() && ! $this->checkUploadedFile()) {
  156. return false;
  157. }
  158. if (! $this->isReadable()) {
  159. return false;
  160. }
  161. if (function_exists('file_get_contents')) {
  162. $this->_content = file_get_contents($this->getName());
  163. } elseif ($size = filesize($this->getName())) {
  164. $this->_content = fread(fopen($this->getName(), 'rb'), $size);
  165. }
  166. }
  167. if (! empty($this->_content) && $as_binary) {
  168. return '0x' . bin2hex($this->_content);
  169. }
  170. if (null !== $length) {
  171. return substr($this->_content, $offset, $length);
  172. } elseif ($offset > 0) {
  173. return substr($this->_content, $offset);
  174. }
  175. return $this->_content;
  176. }
  177. /**
  178. * Whether file is uploaded.
  179. *
  180. * @access public
  181. *
  182. * @return bool
  183. */
  184. public function isUploaded()
  185. {
  186. return is_uploaded_file($this->getName());
  187. }
  188. /**
  189. * accessor
  190. *
  191. * @access public
  192. * @return string PMA_File::$_name
  193. */
  194. public function getName()
  195. {
  196. return $this->_name;
  197. }
  198. /**
  199. * Initializes object from uploaded file.
  200. *
  201. * @param string $name name of file uploaded
  202. *
  203. * @return boolean success
  204. * @access public
  205. */
  206. public function setUploadedFile($name)
  207. {
  208. $this->setName($name);
  209. if (! $this->isUploaded()) {
  210. $this->setName(null);
  211. $this->_error_message = __('File was not an uploaded file.');
  212. return false;
  213. }
  214. return true;
  215. }
  216. /**
  217. * Loads uploaded file from table change request.
  218. *
  219. * @param string $key the md5 hash of the column name
  220. * @param string $rownumber number of row to process
  221. *
  222. * @return boolean success
  223. * @access public
  224. */
  225. public function setUploadedFromTblChangeRequest($key, $rownumber)
  226. {
  227. if (! isset($_FILES['fields_upload'])
  228. || empty($_FILES['fields_upload']['name']['multi_edit'][$rownumber][$key])
  229. ) {
  230. return false;
  231. }
  232. $file = PMA_File::fetchUploadedFromTblChangeRequestMultiple(
  233. $_FILES['fields_upload'],
  234. $rownumber,
  235. $key
  236. );
  237. // check for file upload errors
  238. switch ($file['error']) {
  239. // we do not use the PHP constants here cause not all constants
  240. // are defined in all versions of PHP - but the correct constants names
  241. // are given as comment
  242. case 0: //UPLOAD_ERR_OK:
  243. return $this->setUploadedFile($file['tmp_name']);
  244. break;
  245. case 4: //UPLOAD_ERR_NO_FILE:
  246. break;
  247. case 1: //UPLOAD_ERR_INI_SIZE:
  248. $this->_error_message = __('The uploaded file exceeds the upload_max_filesize directive in php.ini.');
  249. break;
  250. case 2: //UPLOAD_ERR_FORM_SIZE:
  251. $this->_error_message = __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.');
  252. break;
  253. case 3: //UPLOAD_ERR_PARTIAL:
  254. $this->_error_message = __('The uploaded file was only partially uploaded.');
  255. break;
  256. case 6: //UPLOAD_ERR_NO_TMP_DIR:
  257. $this->_error_message = __('Missing a temporary folder.');
  258. break;
  259. case 7: //UPLOAD_ERR_CANT_WRITE:
  260. $this->_error_message = __('Failed to write file to disk.');
  261. break;
  262. case 8: //UPLOAD_ERR_EXTENSION:
  263. $this->_error_message = __('File upload stopped by extension.');
  264. break;
  265. default:
  266. $this->_error_message = __('Unknown error in file upload.');
  267. } // end switch
  268. return false;
  269. }
  270. /**
  271. * strips some dimension from the multi-dimensional array from $_FILES
  272. *
  273. * <code>
  274. * $file['name']['multi_edit'][$rownumber][$key] = [value]
  275. * $file['type']['multi_edit'][$rownumber][$key] = [value]
  276. * $file['size']['multi_edit'][$rownumber][$key] = [value]
  277. * $file['tmp_name']['multi_edit'][$rownumber][$key] = [value]
  278. * $file['error']['multi_edit'][$rownumber][$key] = [value]
  279. *
  280. * // becomes:
  281. *
  282. * $file['name'] = [value]
  283. * $file['type'] = [value]
  284. * $file['size'] = [value]
  285. * $file['tmp_name'] = [value]
  286. * $file['error'] = [value]
  287. * </code>
  288. *
  289. * @param array $file the array
  290. * @param string $rownumber number of row to process
  291. * @param string $key key to process
  292. *
  293. * @return array
  294. * @access public
  295. * @static
  296. */
  297. public function fetchUploadedFromTblChangeRequestMultiple(
  298. $file, $rownumber, $key
  299. ) {
  300. $new_file = array(
  301. 'name' => $file['name']['multi_edit'][$rownumber][$key],
  302. 'type' => $file['type']['multi_edit'][$rownumber][$key],
  303. 'size' => $file['size']['multi_edit'][$rownumber][$key],
  304. 'tmp_name' => $file['tmp_name']['multi_edit'][$rownumber][$key],
  305. 'error' => $file['error']['multi_edit'][$rownumber][$key],
  306. );
  307. return $new_file;
  308. }
  309. /**
  310. * sets the name if the file to the one selected in the tbl_change form
  311. *
  312. * @param string $key the md5 hash of the column name
  313. * @param string $rownumber number of row to process
  314. *
  315. * @return boolean success
  316. * @access public
  317. */
  318. public function setSelectedFromTblChangeRequest($key, $rownumber = null)
  319. {
  320. if (! empty($_REQUEST['fields_uploadlocal']['multi_edit'][$rownumber][$key])
  321. && is_string($_REQUEST['fields_uploadlocal']['multi_edit'][$rownumber][$key])
  322. ) {
  323. // ... whether with multiple rows ...
  324. return $this->setLocalSelectedFile(
  325. $_REQUEST['fields_uploadlocal']['multi_edit'][$rownumber][$key]
  326. );
  327. } else {
  328. return false;
  329. }
  330. }
  331. /**
  332. * Returns possible error message.
  333. *
  334. * @access public
  335. * @return string error message
  336. */
  337. public function getError()
  338. {
  339. return $this->_error_message;
  340. }
  341. /**
  342. * Checks whether there was any error.
  343. *
  344. * @access public
  345. * @return boolean whether an error occurred or not
  346. */
  347. public function isError()
  348. {
  349. return ! empty($this->_error_message);
  350. }
  351. /**
  352. * checks the superglobals provided if the tbl_change form is submitted
  353. * and uses the submitted/selected file
  354. *
  355. * @param string $key the md5 hash of the column name
  356. * @param string $rownumber number of row to process
  357. *
  358. * @return boolean success
  359. * @access public
  360. */
  361. public function checkTblChangeForm($key, $rownumber)
  362. {
  363. if ($this->setUploadedFromTblChangeRequest($key, $rownumber)) {
  364. // well done ...
  365. $this->_error_message = '';
  366. return true;
  367. } elseif ($this->setSelectedFromTblChangeRequest($key, $rownumber)) {
  368. // well done ...
  369. $this->_error_message = '';
  370. return true;
  371. }
  372. // all failed, whether just no file uploaded/selected or an error
  373. return false;
  374. }
  375. /**
  376. * Sets named file to be read from UploadDir.
  377. *
  378. * @param string $name file name
  379. *
  380. * @return boolean success
  381. * @access public
  382. */
  383. public function setLocalSelectedFile($name)
  384. {
  385. if (empty($GLOBALS['cfg']['UploadDir'])) {
  386. return false;
  387. }
  388. $this->setName(
  389. PMA_Util::userDir($GLOBALS['cfg']['UploadDir']) . PMA_securePath($name)
  390. );
  391. if (! $this->isReadable()) {
  392. $this->_error_message = __('File could not be read!');
  393. $this->setName(null);
  394. return false;
  395. }
  396. return true;
  397. }
  398. /**
  399. * Checks whether file can be read.
  400. *
  401. * @access public
  402. * @return boolean whether the file is readable or not
  403. */
  404. public function isReadable()
  405. {
  406. // suppress warnings from being displayed, but not from being logged
  407. // any file access outside of open_basedir will issue a warning
  408. ob_start();
  409. $is_readable = is_readable($this->getName());
  410. ob_end_clean();
  411. return $is_readable;
  412. }
  413. /**
  414. * If we are on a server with open_basedir, we must move the file
  415. * before opening it. The FAQ 1.11 explains how to create the "./tmp"
  416. * directory - if needed
  417. *
  418. * @todo move check of $cfg['TempDir'] into PMA_Config?
  419. * @access public
  420. * @return boolean whether uploaded fiel is fine or not
  421. */
  422. public function checkUploadedFile()
  423. {
  424. if ($this->isReadable()) {
  425. return true;
  426. }
  427. if (empty($GLOBALS['cfg']['TempDir'])
  428. || ! is_writable($GLOBALS['cfg']['TempDir'])
  429. ) {
  430. // cannot create directory or access, point user to FAQ 1.11
  431. $this->_error_message = __('Error moving the uploaded file, see [doc@faq1-11]FAQ 1.11[/doc].');
  432. return false;
  433. }
  434. $new_file_to_upload = tempnam(
  435. realpath($GLOBALS['cfg']['TempDir']),
  436. basename($this->getName())
  437. );
  438. // suppress warnings from being displayed, but not from being logged
  439. // any file access outside of open_basedir will issue a warning
  440. ob_start();
  441. $move_uploaded_file_result = move_uploaded_file(
  442. $this->getName(),
  443. $new_file_to_upload
  444. );
  445. ob_end_clean();
  446. if (! $move_uploaded_file_result) {
  447. $this->_error_message = __('Error while moving uploaded file.');
  448. return false;
  449. }
  450. $this->setName($new_file_to_upload);
  451. $this->isTemp(true);
  452. if (! $this->isReadable()) {
  453. $this->_error_message = __('Cannot read (moved) upload file.');
  454. return false;
  455. }
  456. return true;
  457. }
  458. /**
  459. * Detects what compression the file uses
  460. *
  461. * @todo move file read part into readChunk() or getChunk()
  462. * @todo add support for compression plugins
  463. * @access protected
  464. * @return mixed false on error, otherwise string MIME type of
  465. * compression, none for none
  466. */
  467. protected function detectCompression()
  468. {
  469. // suppress warnings from being displayed, but not from being logged
  470. // f.e. any file access outside of open_basedir will issue a warning
  471. ob_start();
  472. $file = fopen($this->getName(), 'rb');
  473. ob_end_clean();
  474. if (! $file) {
  475. $this->_error_message = __('File could not be read!');
  476. return false;
  477. }
  478. /**
  479. * @todo
  480. * get registered plugins for file compression
  481. foreach (PMA_getPlugins($type = 'compression') as $plugin) {
  482. if ($plugin['classname']::canHandle($this->getName())) {
  483. $this->setCompressionPlugin($plugin);
  484. break;
  485. }
  486. }
  487. */
  488. $this->_compression = PMA_Util::getCompressionMimeType($file);
  489. return $this->_compression;
  490. }
  491. /**
  492. * Sets whether the content should be decompressed before returned
  493. *
  494. * @param boolean $decompress whether to decompres
  495. *
  496. * @return void
  497. */
  498. public function setDecompressContent($decompress)
  499. {
  500. $this->_decompress = (bool) $decompress;
  501. }
  502. /**
  503. * Returns the file handle
  504. *
  505. * @return resource file handle
  506. */
  507. public function getHandle()
  508. {
  509. if (null === $this->_handle) {
  510. $this->open();
  511. }
  512. return $this->_handle;
  513. }
  514. /**
  515. * Sets the file handle
  516. *
  517. * @param resource $handle file handle
  518. *
  519. * @return void
  520. */
  521. public function setHandle($handle)
  522. {
  523. $this->_handle = $handle;
  524. }
  525. /**
  526. * Sets error message for unsupported compression.
  527. *
  528. * @return void
  529. */
  530. public function errorUnsupported()
  531. {
  532. $this->_error_message = sprintf(
  533. __('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.'),
  534. $this->getCompression()
  535. );
  536. }
  537. /**
  538. * Attempts to open the file.
  539. *
  540. * @return bool
  541. */
  542. public function open()
  543. {
  544. if (! $this->_decompress) {
  545. $this->_handle = @fopen($this->getName(), 'r');
  546. }
  547. switch ($this->getCompression()) {
  548. case false:
  549. return false;
  550. case 'application/bzip2':
  551. if ($GLOBALS['cfg']['BZipDump'] && @function_exists('bzopen')) {
  552. $this->_handle = @bzopen($this->getName(), 'r');
  553. } else {
  554. $this->errorUnsupported();
  555. return false;
  556. }
  557. break;
  558. case 'application/gzip':
  559. if ($GLOBALS['cfg']['GZipDump'] && @function_exists('gzopen')) {
  560. $this->_handle = @gzopen($this->getName(), 'r');
  561. } else {
  562. $this->errorUnsupported();
  563. return false;
  564. }
  565. break;
  566. case 'application/zip':
  567. if ($GLOBALS['cfg']['ZipDump'] && @function_exists('zip_open')) {
  568. include_once './libraries/zip_extension.lib.php';
  569. $result = PMA_getZipContents($this->getName());
  570. if (! empty($result['error'])) {
  571. $this->_error_message = (string) PMA_Message::rawError($result['error']);
  572. return false;
  573. } else {
  574. $this->content_uncompressed = $result['data'];
  575. }
  576. unset($result);
  577. } else {
  578. $this->errorUnsupported();
  579. return false;
  580. }
  581. break;
  582. case 'none':
  583. $this->_handle = @fopen($this->getName(), 'r');
  584. break;
  585. default:
  586. $this->errorUnsupported();
  587. return false;
  588. break;
  589. }
  590. return true;
  591. }
  592. /**
  593. * Returns the character set of the file
  594. *
  595. * @return string character set of the file
  596. */
  597. public function getCharset()
  598. {
  599. return $this->_charset;
  600. }
  601. /**
  602. * Sets the character set of the file
  603. *
  604. * @param string $charset character set of the file
  605. *
  606. * @return void
  607. */
  608. public function setCharset($charset)
  609. {
  610. $this->_charset = $charset;
  611. }
  612. /**
  613. * Returns compression used by file.
  614. *
  615. * @return string MIME type of compression, none for none
  616. * @access public
  617. */
  618. public function getCompression()
  619. {
  620. if (null === $this->_compression) {
  621. return $this->detectCompression();
  622. }
  623. return $this->_compression;
  624. }
  625. /**
  626. * Returns the offset
  627. *
  628. * @return integer the offset
  629. */
  630. public function getOffset()
  631. {
  632. return $this->_offset;
  633. }
  634. /**
  635. * Returns the chunk size
  636. *
  637. * @return integer the chunk size
  638. */
  639. public function getChunkSize()
  640. {
  641. return $this->_chunk_size;
  642. }
  643. /**
  644. * Sets the chunk size
  645. *
  646. * @param integer $chunk_size the chunk size
  647. *
  648. * @return void
  649. */
  650. public function setChunkSize($chunk_size)
  651. {
  652. $this->_chunk_size = (int) $chunk_size;
  653. }
  654. /**
  655. * Returns the length of the content in the file
  656. *
  657. * @return integer the length of the file content
  658. */
  659. public function getContentLength()
  660. {
  661. return strlen($this->_content);
  662. }
  663. /**
  664. * Returns whether the end of the file has been reached
  665. *
  666. * @return boolean whether the end of the file has been reached
  667. */
  668. public function eof()
  669. {
  670. if ($this->getHandle()) {
  671. return feof($this->getHandle());
  672. } else {
  673. return ($this->getOffset() >= $this->getContentLength());
  674. }
  675. }
  676. }
  677. ?>