File.php 16 KB

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