File.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 0.2.9
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Filesystem;
  16. use finfo;
  17. use SplFileInfo;
  18. /**
  19. * Convenience class for reading, writing and appending to files.
  20. */
  21. class File
  22. {
  23. /**
  24. * Folder object of the file
  25. *
  26. * @var \Cake\Filesystem\Folder
  27. * @link https://book.cakephp.org/3.0/en/core-libraries/file-folder.html
  28. */
  29. public $Folder;
  30. /**
  31. * File name
  32. *
  33. * @var string
  34. * https://book.cakephp.org/3.0/en/core-libraries/file-folder.html#Cake\Filesystem\File::$name
  35. */
  36. public $name;
  37. /**
  38. * File info
  39. *
  40. * @var array
  41. * https://book.cakephp.org/3.0/en/core-libraries/file-folder.html#Cake\Filesystem\File::$info
  42. */
  43. public $info = [];
  44. /**
  45. * Holds the file handler resource if the file is opened
  46. *
  47. * @var resource|null
  48. * https://book.cakephp.org/3.0/en/core-libraries/file-folder.html#Cake\Filesystem\File::$handle
  49. */
  50. public $handle;
  51. /**
  52. * Enable locking for file reading and writing
  53. *
  54. * @var bool|null
  55. * https://book.cakephp.org/3.0/en/core-libraries/file-folder.html#Cake\Filesystem\File::$lock
  56. */
  57. public $lock;
  58. /**
  59. * Path property
  60. *
  61. * Current file's absolute path
  62. *
  63. * @var string|null
  64. * https://book.cakephp.org/3.0/en/core-libraries/file-folder.html#Cake\Filesystem\File::$path
  65. */
  66. public $path;
  67. /**
  68. * Constructor
  69. *
  70. * @param string $path Path to file
  71. * @param bool $create Create file if it does not exist (if true)
  72. * @param int $mode Mode to apply to the folder holding the file
  73. * @link https://book.cakephp.org/3.0/en/core-libraries/file-folder.html#file-api
  74. */
  75. public function __construct($path, $create = false, $mode = 0755)
  76. {
  77. $splInfo = new SplFileInfo($path);
  78. $this->Folder = new Folder($splInfo->getPath(), $create, $mode);
  79. if (!is_dir($path)) {
  80. $this->name = ltrim($splInfo->getFilename(), DS);
  81. }
  82. $this->pwd();
  83. $create && !$this->exists() && $this->safe($path) && $this->create();
  84. }
  85. /**
  86. * Closes the current file if it is opened
  87. */
  88. public function __destruct()
  89. {
  90. $this->close();
  91. }
  92. /**
  93. * Creates the file.
  94. *
  95. * @return bool Success
  96. */
  97. public function create()
  98. {
  99. $dir = $this->Folder->pwd();
  100. if (is_dir($dir) && is_writable($dir) && !$this->exists()) {
  101. if (touch($this->path)) {
  102. return true;
  103. }
  104. }
  105. return false;
  106. }
  107. /**
  108. * Opens the current file with a given $mode
  109. *
  110. * @param string $mode A valid 'fopen' mode string (r|w|a ...)
  111. * @param bool $force If true then the file will be re-opened even if its already opened, otherwise it won't
  112. * @return bool True on success, false on failure
  113. */
  114. public function open($mode = 'r', $force = false)
  115. {
  116. if (!$force && is_resource($this->handle)) {
  117. return true;
  118. }
  119. if ($this->exists() === false && $this->create() === false) {
  120. return false;
  121. }
  122. $this->handle = fopen($this->path, $mode);
  123. return is_resource($this->handle);
  124. }
  125. /**
  126. * Return the contents of this file as a string.
  127. *
  128. * @param string|bool $bytes where to start
  129. * @param string $mode A `fread` compatible mode.
  130. * @param bool $force If true then the file will be re-opened even if its already opened, otherwise it won't
  131. * @return string|false string on success, false on failure
  132. */
  133. public function read($bytes = false, $mode = 'rb', $force = false)
  134. {
  135. if ($bytes === false && $this->lock === null) {
  136. return file_get_contents($this->path);
  137. }
  138. if ($this->open($mode, $force) === false) {
  139. return false;
  140. }
  141. if ($this->lock !== null && flock($this->handle, LOCK_SH) === false) {
  142. return false;
  143. }
  144. if (is_int($bytes)) {
  145. return fread($this->handle, $bytes);
  146. }
  147. $data = '';
  148. while (!feof($this->handle)) {
  149. $data .= fgets($this->handle, 4096);
  150. }
  151. if ($this->lock !== null) {
  152. flock($this->handle, LOCK_UN);
  153. }
  154. if ($bytes === false) {
  155. $this->close();
  156. }
  157. return trim($data);
  158. }
  159. /**
  160. * Sets or gets the offset for the currently opened file.
  161. *
  162. * @param int|bool $offset The $offset in bytes to seek. If set to false then the current offset is returned.
  163. * @param int $seek PHP Constant SEEK_SET | SEEK_CUR | SEEK_END determining what the $offset is relative to
  164. * @return int|bool True on success, false on failure (set mode), false on failure or integer offset on success (get mode)
  165. */
  166. public function offset($offset = false, $seek = SEEK_SET)
  167. {
  168. if ($offset === false) {
  169. if (is_resource($this->handle)) {
  170. return ftell($this->handle);
  171. }
  172. } elseif ($this->open() === true) {
  173. return fseek($this->handle, $offset, $seek) === 0;
  174. }
  175. return false;
  176. }
  177. /**
  178. * Prepares an ASCII string for writing. Converts line endings to the
  179. * correct terminator for the current platform. If Windows, "\r\n" will be used,
  180. * all other platforms will use "\n"
  181. *
  182. * @param string $data Data to prepare for writing.
  183. * @param bool $forceWindows If true forces Windows new line string.
  184. * @return string The with converted line endings.
  185. */
  186. public static function prepare($data, $forceWindows = false)
  187. {
  188. $lineBreak = "\n";
  189. if (DIRECTORY_SEPARATOR === '\\' || $forceWindows === true) {
  190. $lineBreak = "\r\n";
  191. }
  192. return strtr($data, ["\r\n" => $lineBreak, "\n" => $lineBreak, "\r" => $lineBreak]);
  193. }
  194. /**
  195. * Write given data to this file.
  196. *
  197. * @param string $data Data to write to this File.
  198. * @param string $mode Mode of writing. {@link https://secure.php.net/fwrite See fwrite()}.
  199. * @param bool $force Force the file to open
  200. * @return bool Success
  201. */
  202. public function write($data, $mode = 'w', $force = false)
  203. {
  204. $success = false;
  205. if ($this->open($mode, $force) === true) {
  206. if ($this->lock !== null && flock($this->handle, LOCK_EX) === false) {
  207. return false;
  208. }
  209. if (fwrite($this->handle, $data) !== false) {
  210. $success = true;
  211. }
  212. if ($this->lock !== null) {
  213. flock($this->handle, LOCK_UN);
  214. }
  215. }
  216. return $success;
  217. }
  218. /**
  219. * Append given data string to this file.
  220. *
  221. * @param string $data Data to write
  222. * @param bool $force Force the file to open
  223. * @return bool Success
  224. */
  225. public function append($data, $force = false)
  226. {
  227. return $this->write($data, 'a', $force);
  228. }
  229. /**
  230. * Closes the current file if it is opened.
  231. *
  232. * @return bool True if closing was successful or file was already closed, otherwise false
  233. */
  234. public function close()
  235. {
  236. if (!is_resource($this->handle)) {
  237. return true;
  238. }
  239. return fclose($this->handle);
  240. }
  241. /**
  242. * Deletes the file.
  243. *
  244. * @return bool Success
  245. */
  246. public function delete()
  247. {
  248. if (is_resource($this->handle)) {
  249. fclose($this->handle);
  250. $this->handle = null;
  251. }
  252. if ($this->exists()) {
  253. return unlink($this->path);
  254. }
  255. return false;
  256. }
  257. /**
  258. * Returns the file info as an array with the following keys:
  259. *
  260. * - dirname
  261. * - basename
  262. * - extension
  263. * - filename
  264. * - filesize
  265. * - mime
  266. *
  267. * @return array File information.
  268. */
  269. public function info()
  270. {
  271. if (!$this->info) {
  272. $this->info = pathinfo($this->path);
  273. }
  274. if (!isset($this->info['filename'])) {
  275. $this->info['filename'] = $this->name();
  276. }
  277. if (!isset($this->info['filesize'])) {
  278. $this->info['filesize'] = $this->size();
  279. }
  280. if (!isset($this->info['mime'])) {
  281. $this->info['mime'] = $this->mime();
  282. }
  283. return $this->info;
  284. }
  285. /**
  286. * Returns the file extension.
  287. *
  288. * @return string|false The file extension, false if extension cannot be extracted.
  289. */
  290. public function ext()
  291. {
  292. if (!$this->info) {
  293. $this->info();
  294. }
  295. if (isset($this->info['extension'])) {
  296. return $this->info['extension'];
  297. }
  298. return false;
  299. }
  300. /**
  301. * Returns the file name without extension.
  302. *
  303. * @return string|false The file name without extension, false if name cannot be extracted.
  304. */
  305. public function name()
  306. {
  307. if (!$this->info) {
  308. $this->info();
  309. }
  310. if (isset($this->info['extension'])) {
  311. return $this->_basename($this->name, '.' . $this->info['extension']);
  312. }
  313. if ($this->name) {
  314. return $this->name;
  315. }
  316. return false;
  317. }
  318. /**
  319. * Returns the file basename. simulate the php basename().
  320. *
  321. * @return string the file basename.
  322. */
  323. protected function _basename($name, $ext=null)
  324. {
  325. $splInfo = new SplFileInfo($name);
  326. $name = ltrim($splInfo->getFilename(), DS);
  327. if($ext===null || rtrim($name,$ext)===''){
  328. return $name;
  329. }
  330. return rtrim($name,$ext);
  331. }
  332. /**
  333. * Makes file name safe for saving
  334. *
  335. * @param string|null $name The name of the file to make safe if different from $this->name
  336. * @param string|null $ext The name of the extension to make safe if different from $this->ext
  337. * @return string The extension of the file
  338. */
  339. public function safe($name = null, $ext = null)
  340. {
  341. if (!$name) {
  342. $name = $this->name;
  343. }
  344. if (!$ext) {
  345. $ext = $this->ext();
  346. }
  347. return preg_replace("/(?:[^\w\.-]+)/", '_', $this->_basename($name, $ext));
  348. }
  349. /**
  350. * Get md5 Checksum of file with previous check of Filesize
  351. *
  352. * @param int|bool $maxsize in MB or true to force
  353. * @return string|false md5 Checksum {@link https://secure.php.net/md5_file See md5_file()}, or false in case of an error
  354. */
  355. public function md5($maxsize = 5)
  356. {
  357. if ($maxsize === true) {
  358. return md5_file($this->path);
  359. }
  360. $size = $this->size();
  361. if ($size && $size < ($maxsize * 1024) * 1024) {
  362. return md5_file($this->path);
  363. }
  364. return false;
  365. }
  366. /**
  367. * Returns the full path of the file.
  368. *
  369. * @return string Full path to the file
  370. */
  371. public function pwd()
  372. {
  373. if ($this->path === null) {
  374. $dir = $this->Folder->pwd();
  375. if (is_dir($dir)) {
  376. $this->path = $this->Folder->slashTerm($dir) . $this->name;
  377. }
  378. }
  379. return $this->path;
  380. }
  381. /**
  382. * Returns true if the file exists.
  383. *
  384. * @return bool True if it exists, false otherwise
  385. */
  386. public function exists()
  387. {
  388. $this->clearStatCache();
  389. return (file_exists($this->path) && is_file($this->path));
  390. }
  391. /**
  392. * Returns the "chmod" (permissions) of the file.
  393. *
  394. * @return string|false Permissions for the file, or false in case of an error
  395. */
  396. public function perms()
  397. {
  398. if ($this->exists()) {
  399. return substr(sprintf('%o', fileperms($this->path)), -4);
  400. }
  401. return false;
  402. }
  403. /**
  404. * Returns the file size
  405. *
  406. * @return int|false Size of the file in bytes, or false in case of an error
  407. */
  408. public function size()
  409. {
  410. if ($this->exists()) {
  411. return filesize($this->path);
  412. }
  413. return false;
  414. }
  415. /**
  416. * Returns true if the file is writable.
  417. *
  418. * @return bool True if it's writable, false otherwise
  419. */
  420. public function writable()
  421. {
  422. return is_writable($this->path);
  423. }
  424. /**
  425. * Returns true if the File is executable.
  426. *
  427. * @return bool True if it's executable, false otherwise
  428. */
  429. public function executable()
  430. {
  431. return is_executable($this->path);
  432. }
  433. /**
  434. * Returns true if the file is readable.
  435. *
  436. * @return bool True if file is readable, false otherwise
  437. */
  438. public function readable()
  439. {
  440. return is_readable($this->path);
  441. }
  442. /**
  443. * Returns the file's owner.
  444. *
  445. * @return int|false The file owner, or false in case of an error
  446. */
  447. public function owner()
  448. {
  449. if ($this->exists()) {
  450. return fileowner($this->path);
  451. }
  452. return false;
  453. }
  454. /**
  455. * Returns the file's group.
  456. *
  457. * @return int|false The file group, or false in case of an error
  458. */
  459. public function group()
  460. {
  461. if ($this->exists()) {
  462. return filegroup($this->path);
  463. }
  464. return false;
  465. }
  466. /**
  467. * Returns last access time.
  468. *
  469. * @return int|false Timestamp of last access time, or false in case of an error
  470. */
  471. public function lastAccess()
  472. {
  473. if ($this->exists()) {
  474. return fileatime($this->path);
  475. }
  476. return false;
  477. }
  478. /**
  479. * Returns last modified time.
  480. *
  481. * @return int|false Timestamp of last modification, or false in case of an error
  482. */
  483. public function lastChange()
  484. {
  485. if ($this->exists()) {
  486. return filemtime($this->path);
  487. }
  488. return false;
  489. }
  490. /**
  491. * Returns the current folder.
  492. *
  493. * @return \Cake\Filesystem\Folder Current folder
  494. */
  495. public function folder()
  496. {
  497. return $this->Folder;
  498. }
  499. /**
  500. * Copy the File to $dest
  501. *
  502. * @param string $dest Destination for the copy
  503. * @param bool $overwrite Overwrite $dest if exists
  504. * @return bool Success
  505. */
  506. public function copy($dest, $overwrite = true)
  507. {
  508. if (!$this->exists() || is_file($dest) && !$overwrite) {
  509. return false;
  510. }
  511. return copy($this->path, $dest);
  512. }
  513. /**
  514. * Gets the mime type of the file. Uses the finfo extension if
  515. * it's available, otherwise falls back to mime_content_type().
  516. *
  517. * @return false|string The mimetype of the file, or false if reading fails.
  518. */
  519. public function mime()
  520. {
  521. if (!$this->exists()) {
  522. return false;
  523. }
  524. if (class_exists('finfo')) {
  525. $finfo = new finfo(FILEINFO_MIME);
  526. $type = $finfo->file($this->pwd());
  527. if (!$type) {
  528. return false;
  529. }
  530. list($type) = explode(';', $type);
  531. return $type;
  532. }
  533. if (function_exists('mime_content_type')) {
  534. return mime_content_type($this->pwd());
  535. }
  536. return false;
  537. }
  538. /**
  539. * Clear PHP's internal stat cache
  540. *
  541. * @param bool $all Clear all cache or not. Passing false will clear
  542. * the stat cache for the current path only.
  543. * @return void
  544. */
  545. public function clearStatCache($all = false)
  546. {
  547. if ($all === false) {
  548. clearstatcache(true, $this->path);
  549. }
  550. clearstatcache();
  551. }
  552. /**
  553. * Searches for a given text and replaces the text if found.
  554. *
  555. * @param string|array $search Text(s) to search for.
  556. * @param string|array $replace Text(s) to replace with.
  557. * @return bool Success
  558. */
  559. public function replaceText($search, $replace)
  560. {
  561. if (!$this->open('r+')) {
  562. return false;
  563. }
  564. if ($this->lock !== null && flock($this->handle, LOCK_EX) === false) {
  565. return false;
  566. }
  567. $replaced = $this->write(str_replace($search, $replace, $this->read()), 'w', true);
  568. if ($this->lock !== null) {
  569. flock($this->handle, LOCK_UN);
  570. }
  571. $this->close();
  572. return $replaced;
  573. }
  574. }