PageRenderTime 57ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/filebackend/FileBackend.php

https://bitbucket.org/glasshouse/glasshousewiki
PHP | 1173 lines | 254 code | 67 blank | 852 comment | 34 complexity | 2960c7945e519869b2cdf29bf626f3a0 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0
  1. <?php
  2. /**
  3. * @defgroup FileBackend File backend
  4. * @ingroup FileRepo
  5. *
  6. * File backend is used to interact with file storage systems,
  7. * such as the local file system, NFS, or cloud storage systems.
  8. */
  9. /**
  10. * Base class for all file backends.
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 2 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License along
  23. * with this program; if not, write to the Free Software Foundation, Inc.,
  24. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  25. * http://www.gnu.org/copyleft/gpl.html
  26. *
  27. * @file
  28. * @ingroup FileBackend
  29. * @author Aaron Schulz
  30. */
  31. /**
  32. * @brief Base class for all file backend classes (including multi-write backends).
  33. *
  34. * This class defines the methods as abstract that subclasses must implement.
  35. * Outside callers can assume that all backends will have these functions.
  36. *
  37. * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
  38. * The "<path>" portion is a relative path that uses UNIX file system (FS)
  39. * notation, though any particular backend may not actually be using a local
  40. * filesystem. Therefore, the relative paths are only virtual.
  41. *
  42. * Backend contents are stored under wiki-specific container names by default.
  43. * For legacy reasons, this has no effect for the FS backend class, and per-wiki
  44. * segregation must be done by setting the container paths appropriately.
  45. *
  46. * FS-based backends are somewhat more restrictive due to the existence of real
  47. * directory files; a regular file cannot have the same name as a directory. Other
  48. * backends with virtual directories may not have this limitation. Callers should
  49. * store files in such a way that no files and directories are under the same path.
  50. *
  51. * Methods of subclasses should avoid throwing exceptions at all costs.
  52. * As a corollary, external dependencies should be kept to a minimum.
  53. *
  54. * @ingroup FileBackend
  55. * @since 1.19
  56. */
  57. abstract class FileBackend {
  58. protected $name; // string; unique backend name
  59. protected $wikiId; // string; unique wiki name
  60. protected $readOnly; // string; read-only explanation message
  61. protected $parallelize; // string; when to do operations in parallel
  62. protected $concurrency; // integer; how many operations can be done in parallel
  63. /** @var LockManager */
  64. protected $lockManager;
  65. /** @var FileJournal */
  66. protected $fileJournal;
  67. /**
  68. * Create a new backend instance from configuration.
  69. * This should only be called from within FileBackendGroup.
  70. *
  71. * $config includes:
  72. * - name : The unique name of this backend.
  73. * This should consist of alphanumberic, '-', and '_' characters.
  74. * This name should not be changed after use.
  75. * - wikiId : Prefix to container names that is unique to this wiki.
  76. * It should only consist of alphanumberic, '-', and '_' characters.
  77. * - lockManager : Registered name of a file lock manager to use.
  78. * - fileJournal : File journal configuration; see FileJournal::factory().
  79. * Journals simply log changes to files stored in the backend.
  80. * - readOnly : Write operations are disallowed if this is a non-empty string.
  81. * It should be an explanation for the backend being read-only.
  82. * - parallelize : When to do file operations in parallel (when possible).
  83. * Allowed values are "implicit", "explicit" and "off".
  84. * - concurrency : How many file operations can be done in parallel.
  85. *
  86. * @param $config Array
  87. * @throws MWException
  88. */
  89. public function __construct( array $config ) {
  90. $this->name = $config['name'];
  91. if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name ) ) {
  92. throw new MWException( "Backend name `{$this->name}` is invalid." );
  93. }
  94. $this->wikiId = isset( $config['wikiId'] )
  95. ? $config['wikiId']
  96. : wfWikiID(); // e.g. "my_wiki-en_"
  97. $this->lockManager = ( $config['lockManager'] instanceof LockManager )
  98. ? $config['lockManager']
  99. : LockManagerGroup::singleton()->get( $config['lockManager'] );
  100. $this->fileJournal = isset( $config['fileJournal'] )
  101. ? ( ( $config['fileJournal'] instanceof FileJournal )
  102. ? $config['fileJournal']
  103. : FileJournal::factory( $config['fileJournal'], $this->name ) )
  104. : FileJournal::factory( array( 'class' => 'NullFileJournal' ), $this->name );
  105. $this->readOnly = isset( $config['readOnly'] )
  106. ? (string)$config['readOnly']
  107. : '';
  108. $this->parallelize = isset( $config['parallelize'] )
  109. ? (string)$config['parallelize']
  110. : 'off';
  111. $this->concurrency = isset( $config['concurrency'] )
  112. ? (int)$config['concurrency']
  113. : 50;
  114. }
  115. /**
  116. * Get the unique backend name.
  117. * We may have multiple different backends of the same type.
  118. * For example, we can have two Swift backends using different proxies.
  119. *
  120. * @return string
  121. */
  122. final public function getName() {
  123. return $this->name;
  124. }
  125. /**
  126. * Get the wiki identifier used for this backend (possibly empty)
  127. *
  128. * @return string
  129. * @since 1.20
  130. */
  131. final public function getWikiId() {
  132. return $this->wikiId;
  133. }
  134. /**
  135. * Check if this backend is read-only
  136. *
  137. * @return bool
  138. */
  139. final public function isReadOnly() {
  140. return ( $this->readOnly != '' );
  141. }
  142. /**
  143. * Get an explanatory message if this backend is read-only
  144. *
  145. * @return string|bool Returns false if the backend is not read-only
  146. */
  147. final public function getReadOnlyReason() {
  148. return ( $this->readOnly != '' ) ? $this->readOnly : false;
  149. }
  150. /**
  151. * This is the main entry point into the backend for write operations.
  152. * Callers supply an ordered list of operations to perform as a transaction.
  153. * Files will be locked, the stat cache cleared, and then the operations attempted.
  154. * If any serious errors occur, all attempted operations will be rolled back.
  155. *
  156. * $ops is an array of arrays. The outer array holds a list of operations.
  157. * Each inner array is a set of key value pairs that specify an operation.
  158. *
  159. * Supported operations and their parameters. The supported actions are:
  160. * - create
  161. * - store
  162. * - copy
  163. * - move
  164. * - delete
  165. * - null
  166. *
  167. * a) Create a new file in storage with the contents of a string
  168. * @code
  169. * array(
  170. * 'op' => 'create',
  171. * 'dst' => <storage path>,
  172. * 'content' => <string of new file contents>,
  173. * 'overwrite' => <boolean>,
  174. * 'overwriteSame' => <boolean>,
  175. * 'disposition' => <Content-Disposition header value>
  176. * );
  177. * @endcode
  178. *
  179. * b) Copy a file system file into storage
  180. * @code
  181. * array(
  182. * 'op' => 'store',
  183. * 'src' => <file system path>,
  184. * 'dst' => <storage path>,
  185. * 'overwrite' => <boolean>,
  186. * 'overwriteSame' => <boolean>,
  187. * 'disposition' => <Content-Disposition header value>
  188. * )
  189. * @endcode
  190. *
  191. * c) Copy a file within storage
  192. * @code
  193. * array(
  194. * 'op' => 'copy',
  195. * 'src' => <storage path>,
  196. * 'dst' => <storage path>,
  197. * 'overwrite' => <boolean>,
  198. * 'overwriteSame' => <boolean>,
  199. * 'disposition' => <Content-Disposition header value>
  200. * )
  201. * @endcode
  202. *
  203. * d) Move a file within storage
  204. * @code
  205. * array(
  206. * 'op' => 'move',
  207. * 'src' => <storage path>,
  208. * 'dst' => <storage path>,
  209. * 'overwrite' => <boolean>,
  210. * 'overwriteSame' => <boolean>,
  211. * 'disposition' => <Content-Disposition header value>
  212. * )
  213. * @endcode
  214. *
  215. * e) Delete a file within storage
  216. * @code
  217. * array(
  218. * 'op' => 'delete',
  219. * 'src' => <storage path>,
  220. * 'ignoreMissingSource' => <boolean>
  221. * )
  222. * @endcode
  223. *
  224. * f) Do nothing (no-op)
  225. * @code
  226. * array(
  227. * 'op' => 'null',
  228. * )
  229. * @endcode
  230. *
  231. * Boolean flags for operations (operation-specific):
  232. * - ignoreMissingSource : The operation will simply succeed and do
  233. * nothing if the source file does not exist.
  234. * - overwrite : Any destination file will be overwritten.
  235. * - overwriteSame : An error will not be given if a file already
  236. * exists at the destination that has the same
  237. * contents as the new contents to be written there.
  238. * - disposition : When supplied, the backend will add a Content-Disposition
  239. * header when GETs/HEADs of the destination file are made.
  240. * Backends that don't support file metadata will ignore this.
  241. * See http://tools.ietf.org/html/rfc6266 (since 1.20).
  242. *
  243. * $opts is an associative of boolean flags, including:
  244. * - force : Operation precondition errors no longer trigger an abort.
  245. * Any remaining operations are still attempted. Unexpected
  246. * failures may still cause remaning operations to be aborted.
  247. * - nonLocking : No locks are acquired for the operations.
  248. * This can increase performance for non-critical writes.
  249. * This has no effect unless the 'force' flag is set.
  250. * - allowStale : Don't require the latest available data.
  251. * This can increase performance for non-critical writes.
  252. * This has no effect unless the 'force' flag is set.
  253. * - nonJournaled : Don't log this operation batch in the file journal.
  254. * This limits the ability of recovery scripts.
  255. * - parallelize : Try to do operations in parallel when possible.
  256. * - bypassReadOnly : Allow writes in read-only mode (since 1.20).
  257. * - preserveCache : Don't clear the process cache before checking files.
  258. * This should only be used if all entries in the process
  259. * cache were added after the files were already locked (since 1.20).
  260. *
  261. * @remarks Remarks on locking:
  262. * File system paths given to operations should refer to files that are
  263. * already locked or otherwise safe from modification from other processes.
  264. * Normally these files will be new temp files, which should be adequate.
  265. *
  266. * @par Return value:
  267. *
  268. * This returns a Status, which contains all warnings and fatals that occurred
  269. * during the operation. The 'failCount', 'successCount', and 'success' members
  270. * will reflect each operation attempted.
  271. *
  272. * The status will be "OK" unless:
  273. * - a) unexpected operation errors occurred (network partitions, disk full...)
  274. * - b) significant operation errors occurred and 'force' was not set
  275. *
  276. * @param $ops Array List of operations to execute in order
  277. * @param $opts Array Batch operation options
  278. * @return Status
  279. */
  280. final public function doOperations( array $ops, array $opts = array() ) {
  281. if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
  282. return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
  283. }
  284. if ( empty( $opts['force'] ) ) { // sanity
  285. unset( $opts['nonLocking'] );
  286. unset( $opts['allowStale'] );
  287. }
  288. $opts['concurrency'] = 1; // off
  289. if ( $this->parallelize === 'implicit' ) {
  290. if ( !isset( $opts['parallelize'] ) || $opts['parallelize'] ) {
  291. $opts['concurrency'] = $this->concurrency;
  292. }
  293. } elseif ( $this->parallelize === 'explicit' ) {
  294. if ( !empty( $opts['parallelize'] ) ) {
  295. $opts['concurrency'] = $this->concurrency;
  296. }
  297. }
  298. return $this->doOperationsInternal( $ops, $opts );
  299. }
  300. /**
  301. * @see FileBackend::doOperations()
  302. */
  303. abstract protected function doOperationsInternal( array $ops, array $opts );
  304. /**
  305. * Same as doOperations() except it takes a single operation.
  306. * If you are doing a batch of operations that should either
  307. * all succeed or all fail, then use that function instead.
  308. *
  309. * @see FileBackend::doOperations()
  310. *
  311. * @param $op Array Operation
  312. * @param $opts Array Operation options
  313. * @return Status
  314. */
  315. final public function doOperation( array $op, array $opts = array() ) {
  316. return $this->doOperations( array( $op ), $opts );
  317. }
  318. /**
  319. * Performs a single create operation.
  320. * This sets $params['op'] to 'create' and passes it to doOperation().
  321. *
  322. * @see FileBackend::doOperation()
  323. *
  324. * @param $params Array Operation parameters
  325. * @param $opts Array Operation options
  326. * @return Status
  327. */
  328. final public function create( array $params, array $opts = array() ) {
  329. return $this->doOperation( array( 'op' => 'create' ) + $params, $opts );
  330. }
  331. /**
  332. * Performs a single store operation.
  333. * This sets $params['op'] to 'store' and passes it to doOperation().
  334. *
  335. * @see FileBackend::doOperation()
  336. *
  337. * @param $params Array Operation parameters
  338. * @param $opts Array Operation options
  339. * @return Status
  340. */
  341. final public function store( array $params, array $opts = array() ) {
  342. return $this->doOperation( array( 'op' => 'store' ) + $params, $opts );
  343. }
  344. /**
  345. * Performs a single copy operation.
  346. * This sets $params['op'] to 'copy' and passes it to doOperation().
  347. *
  348. * @see FileBackend::doOperation()
  349. *
  350. * @param $params Array Operation parameters
  351. * @param $opts Array Operation options
  352. * @return Status
  353. */
  354. final public function copy( array $params, array $opts = array() ) {
  355. return $this->doOperation( array( 'op' => 'copy' ) + $params, $opts );
  356. }
  357. /**
  358. * Performs a single move operation.
  359. * This sets $params['op'] to 'move' and passes it to doOperation().
  360. *
  361. * @see FileBackend::doOperation()
  362. *
  363. * @param $params Array Operation parameters
  364. * @param $opts Array Operation options
  365. * @return Status
  366. */
  367. final public function move( array $params, array $opts = array() ) {
  368. return $this->doOperation( array( 'op' => 'move' ) + $params, $opts );
  369. }
  370. /**
  371. * Performs a single delete operation.
  372. * This sets $params['op'] to 'delete' and passes it to doOperation().
  373. *
  374. * @see FileBackend::doOperation()
  375. *
  376. * @param $params Array Operation parameters
  377. * @param $opts Array Operation options
  378. * @return Status
  379. */
  380. final public function delete( array $params, array $opts = array() ) {
  381. return $this->doOperation( array( 'op' => 'delete' ) + $params, $opts );
  382. }
  383. /**
  384. * Perform a set of independent file operations on some files.
  385. *
  386. * This does no locking, nor journaling, and possibly no stat calls.
  387. * Any destination files that already exist will be overwritten.
  388. * This should *only* be used on non-original files, like cache files.
  389. *
  390. * Supported operations and their parameters:
  391. * - create
  392. * - store
  393. * - copy
  394. * - move
  395. * - delete
  396. * - null
  397. *
  398. * a) Create a new file in storage with the contents of a string
  399. * @code
  400. * array(
  401. * 'op' => 'create',
  402. * 'dst' => <storage path>,
  403. * 'content' => <string of new file contents>,
  404. * 'disposition' => <Content-Disposition header value>
  405. * )
  406. * @endcode
  407. * b) Copy a file system file into storage
  408. * @code
  409. * array(
  410. * 'op' => 'store',
  411. * 'src' => <file system path>,
  412. * 'dst' => <storage path>,
  413. * 'disposition' => <Content-Disposition header value>
  414. * )
  415. * @endcode
  416. * c) Copy a file within storage
  417. * @code
  418. * array(
  419. * 'op' => 'copy',
  420. * 'src' => <storage path>,
  421. * 'dst' => <storage path>,
  422. * 'disposition' => <Content-Disposition header value>
  423. * )
  424. * @endcode
  425. * d) Move a file within storage
  426. * @code
  427. * array(
  428. * 'op' => 'move',
  429. * 'src' => <storage path>,
  430. * 'dst' => <storage path>,
  431. * 'disposition' => <Content-Disposition header value>
  432. * )
  433. * @endcode
  434. * e) Delete a file within storage
  435. * @code
  436. * array(
  437. * 'op' => 'delete',
  438. * 'src' => <storage path>,
  439. * 'ignoreMissingSource' => <boolean>
  440. * )
  441. * @endcode
  442. * f) Do nothing (no-op)
  443. * @code
  444. * array(
  445. * 'op' => 'null',
  446. * )
  447. * @endcode
  448. *
  449. * @par Boolean flags for operations (operation-specific):
  450. * - ignoreMissingSource : The operation will simply succeed and do
  451. * nothing if the source file does not exist.
  452. * - disposition : When supplied, the backend will add a Content-Disposition
  453. * header when GETs/HEADs of the destination file are made.
  454. * Backends that don't support file metadata will ignore this.
  455. * See http://tools.ietf.org/html/rfc6266 (since 1.20).
  456. *
  457. * $opts is an associative of boolean flags, including:
  458. * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
  459. *
  460. * @par Return value:
  461. * This returns a Status, which contains all warnings and fatals that occurred
  462. * during the operation. The 'failCount', 'successCount', and 'success' members
  463. * will reflect each operation attempted for the given files. The status will be
  464. * considered "OK" as long as no fatal errors occurred.
  465. *
  466. * @param $ops Array Set of operations to execute
  467. * @param $opts Array Batch operation options
  468. * @return Status
  469. * @since 1.20
  470. */
  471. final public function doQuickOperations( array $ops, array $opts = array() ) {
  472. if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
  473. return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
  474. }
  475. foreach ( $ops as &$op ) {
  476. $op['overwrite'] = true; // avoids RTTs in key/value stores
  477. }
  478. return $this->doQuickOperationsInternal( $ops );
  479. }
  480. /**
  481. * @see FileBackend::doQuickOperations()
  482. * @since 1.20
  483. */
  484. abstract protected function doQuickOperationsInternal( array $ops );
  485. /**
  486. * Same as doQuickOperations() except it takes a single operation.
  487. * If you are doing a batch of operations, then use that function instead.
  488. *
  489. * @see FileBackend::doQuickOperations()
  490. *
  491. * @param $op Array Operation
  492. * @return Status
  493. * @since 1.20
  494. */
  495. final public function doQuickOperation( array $op ) {
  496. return $this->doQuickOperations( array( $op ) );
  497. }
  498. /**
  499. * Performs a single quick create operation.
  500. * This sets $params['op'] to 'create' and passes it to doQuickOperation().
  501. *
  502. * @see FileBackend::doQuickOperation()
  503. *
  504. * @param $params Array Operation parameters
  505. * @return Status
  506. * @since 1.20
  507. */
  508. final public function quickCreate( array $params ) {
  509. return $this->doQuickOperation( array( 'op' => 'create' ) + $params );
  510. }
  511. /**
  512. * Performs a single quick store operation.
  513. * This sets $params['op'] to 'store' and passes it to doQuickOperation().
  514. *
  515. * @see FileBackend::doQuickOperation()
  516. *
  517. * @param $params Array Operation parameters
  518. * @return Status
  519. * @since 1.20
  520. */
  521. final public function quickStore( array $params ) {
  522. return $this->doQuickOperation( array( 'op' => 'store' ) + $params );
  523. }
  524. /**
  525. * Performs a single quick copy operation.
  526. * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
  527. *
  528. * @see FileBackend::doQuickOperation()
  529. *
  530. * @param $params Array Operation parameters
  531. * @return Status
  532. * @since 1.20
  533. */
  534. final public function quickCopy( array $params ) {
  535. return $this->doQuickOperation( array( 'op' => 'copy' ) + $params );
  536. }
  537. /**
  538. * Performs a single quick move operation.
  539. * This sets $params['op'] to 'move' and passes it to doQuickOperation().
  540. *
  541. * @see FileBackend::doQuickOperation()
  542. *
  543. * @param $params Array Operation parameters
  544. * @return Status
  545. * @since 1.20
  546. */
  547. final public function quickMove( array $params ) {
  548. return $this->doQuickOperation( array( 'op' => 'move' ) + $params );
  549. }
  550. /**
  551. * Performs a single quick delete operation.
  552. * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
  553. *
  554. * @see FileBackend::doQuickOperation()
  555. *
  556. * @param $params Array Operation parameters
  557. * @return Status
  558. * @since 1.20
  559. */
  560. final public function quickDelete( array $params ) {
  561. return $this->doQuickOperation( array( 'op' => 'delete' ) + $params );
  562. }
  563. /**
  564. * Concatenate a list of storage files into a single file system file.
  565. * The target path should refer to a file that is already locked or
  566. * otherwise safe from modification from other processes. Normally,
  567. * the file will be a new temp file, which should be adequate.
  568. *
  569. * @param $params Array Operation parameters
  570. * $params include:
  571. * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
  572. * - dst : file system path to 0-byte temp file
  573. * @return Status
  574. */
  575. abstract public function concatenate( array $params );
  576. /**
  577. * Prepare a storage directory for usage.
  578. * This will create any required containers and parent directories.
  579. * Backends using key/value stores only need to create the container.
  580. *
  581. * The 'noAccess' and 'noListing' parameters works the same as in secure(),
  582. * except they are only applied *if* the directory/container had to be created.
  583. * These flags should always be set for directories that have private files.
  584. *
  585. * @param $params Array
  586. * $params include:
  587. * - dir : storage directory
  588. * - noAccess : try to deny file access (since 1.20)
  589. * - noListing : try to deny file listing (since 1.20)
  590. * - bypassReadOnly : allow writes in read-only mode (since 1.20)
  591. * @return Status
  592. */
  593. final public function prepare( array $params ) {
  594. if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
  595. return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
  596. }
  597. return $this->doPrepare( $params );
  598. }
  599. /**
  600. * @see FileBackend::prepare()
  601. */
  602. abstract protected function doPrepare( array $params );
  603. /**
  604. * Take measures to block web access to a storage directory and
  605. * the container it belongs to. FS backends might add .htaccess
  606. * files whereas key/value store backends might revoke container
  607. * access to the storage user representing end-users in web requests.
  608. * This is not guaranteed to actually do anything.
  609. *
  610. * @param $params Array
  611. * $params include:
  612. * - dir : storage directory
  613. * - noAccess : try to deny file access
  614. * - noListing : try to deny file listing
  615. * - bypassReadOnly : allow writes in read-only mode (since 1.20)
  616. * @return Status
  617. */
  618. final public function secure( array $params ) {
  619. if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
  620. return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
  621. }
  622. return $this->doSecure( $params );
  623. }
  624. /**
  625. * @see FileBackend::secure()
  626. */
  627. abstract protected function doSecure( array $params );
  628. /**
  629. * Remove measures to block web access to a storage directory and
  630. * the container it belongs to. FS backends might remove .htaccess
  631. * files whereas key/value store backends might grant container
  632. * access to the storage user representing end-users in web requests.
  633. * This essentially can undo the result of secure() calls.
  634. *
  635. * @param $params Array
  636. * $params include:
  637. * - dir : storage directory
  638. * - access : try to allow file access
  639. * - listing : try to allow file listing
  640. * - bypassReadOnly : allow writes in read-only mode (since 1.20)
  641. * @return Status
  642. * @since 1.20
  643. */
  644. final public function publish( array $params ) {
  645. if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
  646. return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
  647. }
  648. return $this->doPublish( $params );
  649. }
  650. /**
  651. * @see FileBackend::publish()
  652. */
  653. abstract protected function doPublish( array $params );
  654. /**
  655. * Delete a storage directory if it is empty.
  656. * Backends using key/value stores may do nothing unless the directory
  657. * is that of an empty container, in which case it will be deleted.
  658. *
  659. * @param $params Array
  660. * $params include:
  661. * - dir : storage directory
  662. * - recursive : recursively delete empty subdirectories first (since 1.20)
  663. * - bypassReadOnly : allow writes in read-only mode (since 1.20)
  664. * @return Status
  665. */
  666. final public function clean( array $params ) {
  667. if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
  668. return Status::newFatal( 'backend-fail-readonly', $this->name, $this->readOnly );
  669. }
  670. return $this->doClean( $params );
  671. }
  672. /**
  673. * @see FileBackend::clean()
  674. */
  675. abstract protected function doClean( array $params );
  676. /**
  677. * Check if a file exists at a storage path in the backend.
  678. * This returns false if only a directory exists at the path.
  679. *
  680. * @param $params Array
  681. * $params include:
  682. * - src : source storage path
  683. * - latest : use the latest available data
  684. * @return bool|null Returns null on failure
  685. */
  686. abstract public function fileExists( array $params );
  687. /**
  688. * Get the last-modified timestamp of the file at a storage path.
  689. *
  690. * @param $params Array
  691. * $params include:
  692. * - src : source storage path
  693. * - latest : use the latest available data
  694. * @return string|bool TS_MW timestamp or false on failure
  695. */
  696. abstract public function getFileTimestamp( array $params );
  697. /**
  698. * Get the contents of a file at a storage path in the backend.
  699. * This should be avoided for potentially large files.
  700. *
  701. * @param $params Array
  702. * $params include:
  703. * - src : source storage path
  704. * - latest : use the latest available data
  705. * @return string|bool Returns false on failure
  706. */
  707. abstract public function getFileContents( array $params );
  708. /**
  709. * Get the size (bytes) of a file at a storage path in the backend.
  710. *
  711. * @param $params Array
  712. * $params include:
  713. * - src : source storage path
  714. * - latest : use the latest available data
  715. * @return integer|bool Returns false on failure
  716. */
  717. abstract public function getFileSize( array $params );
  718. /**
  719. * Get quick information about a file at a storage path in the backend.
  720. * If the file does not exist, then this returns false.
  721. * Otherwise, the result is an associative array that includes:
  722. * - mtime : the last-modified timestamp (TS_MW)
  723. * - size : the file size (bytes)
  724. * Additional values may be included for internal use only.
  725. *
  726. * @param $params Array
  727. * $params include:
  728. * - src : source storage path
  729. * - latest : use the latest available data
  730. * @return Array|bool|null Returns null on failure
  731. */
  732. abstract public function getFileStat( array $params );
  733. /**
  734. * Get a SHA-1 hash of the file at a storage path in the backend.
  735. *
  736. * @param $params Array
  737. * $params include:
  738. * - src : source storage path
  739. * - latest : use the latest available data
  740. * @return string|bool Hash string or false on failure
  741. */
  742. abstract public function getFileSha1Base36( array $params );
  743. /**
  744. * Get the properties of the file at a storage path in the backend.
  745. * Returns FSFile::placeholderProps() on failure.
  746. *
  747. * @param $params Array
  748. * $params include:
  749. * - src : source storage path
  750. * - latest : use the latest available data
  751. * @return Array
  752. */
  753. abstract public function getFileProps( array $params );
  754. /**
  755. * Stream the file at a storage path in the backend.
  756. * If the file does not exists, an HTTP 404 error will be given.
  757. * Appropriate HTTP headers (Status, Content-Type, Content-Length)
  758. * will be sent if streaming began, while none will be sent otherwise.
  759. * Implementations should flush the output buffer before sending data.
  760. *
  761. * @param $params Array
  762. * $params include:
  763. * - src : source storage path
  764. * - headers : list of additional HTTP headers to send on success
  765. * - latest : use the latest available data
  766. * @return Status
  767. */
  768. abstract public function streamFile( array $params );
  769. /**
  770. * Returns a file system file, identical to the file at a storage path.
  771. * The file returned is either:
  772. * - a) A local copy of the file at a storage path in the backend.
  773. * The temporary copy will have the same extension as the source.
  774. * - b) An original of the file at a storage path in the backend.
  775. * Temporary files may be purged when the file object falls out of scope.
  776. *
  777. * Write operations should *never* be done on this file as some backends
  778. * may do internal tracking or may be instances of FileBackendMultiWrite.
  779. * In that later case, there are copies of the file that must stay in sync.
  780. * Additionally, further calls to this function may return the same file.
  781. *
  782. * @param $params Array
  783. * $params include:
  784. * - src : source storage path
  785. * - latest : use the latest available data
  786. * @return FSFile|null Returns null on failure
  787. */
  788. abstract public function getLocalReference( array $params );
  789. /**
  790. * Get a local copy on disk of the file at a storage path in the backend.
  791. * The temporary copy will have the same file extension as the source.
  792. * Temporary files may be purged when the file object falls out of scope.
  793. *
  794. * @param $params Array
  795. * $params include:
  796. * - src : source storage path
  797. * - latest : use the latest available data
  798. * @return TempFSFile|null Returns null on failure
  799. */
  800. abstract public function getLocalCopy( array $params );
  801. /**
  802. * Check if a directory exists at a given storage path.
  803. * Backends using key/value stores will check if the path is a
  804. * virtual directory, meaning there are files under the given directory.
  805. *
  806. * Storage backends with eventual consistency might return stale data.
  807. *
  808. * @param $params array
  809. * $params include:
  810. * - dir : storage directory
  811. * @return bool|null Returns null on failure
  812. * @since 1.20
  813. */
  814. abstract public function directoryExists( array $params );
  815. /**
  816. * Get an iterator to list *all* directories under a storage directory.
  817. * If the directory is of the form "mwstore://backend/container",
  818. * then all directories in the container will be listed.
  819. * If the directory is of form "mwstore://backend/container/dir",
  820. * then all directories directly under that directory will be listed.
  821. * Results will be storage directories relative to the given directory.
  822. *
  823. * Storage backends with eventual consistency might return stale data.
  824. *
  825. * @param $params array
  826. * $params include:
  827. * - dir : storage directory
  828. * - topOnly : only return direct child dirs of the directory
  829. * @return Traversable|Array|null Returns null on failure
  830. * @since 1.20
  831. */
  832. abstract public function getDirectoryList( array $params );
  833. /**
  834. * Same as FileBackend::getDirectoryList() except only lists
  835. * directories that are immediately under the given directory.
  836. *
  837. * Storage backends with eventual consistency might return stale data.
  838. *
  839. * @param $params array
  840. * $params include:
  841. * - dir : storage directory
  842. * @return Traversable|Array|null Returns null on failure
  843. * @since 1.20
  844. */
  845. final public function getTopDirectoryList( array $params ) {
  846. return $this->getDirectoryList( array( 'topOnly' => true ) + $params );
  847. }
  848. /**
  849. * Get an iterator to list *all* stored files under a storage directory.
  850. * If the directory is of the form "mwstore://backend/container",
  851. * then all files in the container will be listed.
  852. * If the directory is of form "mwstore://backend/container/dir",
  853. * then all files under that directory will be listed.
  854. * Results will be storage paths relative to the given directory.
  855. *
  856. * Storage backends with eventual consistency might return stale data.
  857. *
  858. * @param $params array
  859. * $params include:
  860. * - dir : storage directory
  861. * - topOnly : only return direct child files of the directory (since 1.20)
  862. * @return Traversable|Array|null Returns null on failure
  863. */
  864. abstract public function getFileList( array $params );
  865. /**
  866. * Same as FileBackend::getFileList() except only lists
  867. * files that are immediately under the given directory.
  868. *
  869. * Storage backends with eventual consistency might return stale data.
  870. *
  871. * @param $params array
  872. * $params include:
  873. * - dir : storage directory
  874. * @return Traversable|Array|null Returns null on failure
  875. * @since 1.20
  876. */
  877. final public function getTopFileList( array $params ) {
  878. return $this->getFileList( array( 'topOnly' => true ) + $params );
  879. }
  880. /**
  881. * Preload persistent file stat and property cache into in-process cache.
  882. * This should be used when stat calls will be made on a known list of a many files.
  883. *
  884. * @param $paths Array Storage paths
  885. * @return void
  886. */
  887. public function preloadCache( array $paths ) {}
  888. /**
  889. * Invalidate any in-process file stat and property cache.
  890. * If $paths is given, then only the cache for those files will be cleared.
  891. *
  892. * @param $paths Array Storage paths (optional)
  893. * @return void
  894. */
  895. public function clearCache( array $paths = null ) {}
  896. /**
  897. * Lock the files at the given storage paths in the backend.
  898. * This will either lock all the files or none (on failure).
  899. *
  900. * Callers should consider using getScopedFileLocks() instead.
  901. *
  902. * @param $paths Array Storage paths
  903. * @param $type integer LockManager::LOCK_* constant
  904. * @return Status
  905. */
  906. final public function lockFiles( array $paths, $type ) {
  907. return $this->lockManager->lock( $paths, $type );
  908. }
  909. /**
  910. * Unlock the files at the given storage paths in the backend.
  911. *
  912. * @param $paths Array Storage paths
  913. * @param $type integer LockManager::LOCK_* constant
  914. * @return Status
  915. */
  916. final public function unlockFiles( array $paths, $type ) {
  917. return $this->lockManager->unlock( $paths, $type );
  918. }
  919. /**
  920. * Lock the files at the given storage paths in the backend.
  921. * This will either lock all the files or none (on failure).
  922. * On failure, the status object will be updated with errors.
  923. *
  924. * Once the return value goes out scope, the locks will be released and
  925. * the status updated. Unlock fatals will not change the status "OK" value.
  926. *
  927. * @param $paths Array Storage paths
  928. * @param $type integer LockManager::LOCK_* constant
  929. * @param $status Status Status to update on lock/unlock
  930. * @return ScopedLock|null Returns null on failure
  931. */
  932. final public function getScopedFileLocks( array $paths, $type, Status $status ) {
  933. return ScopedLock::factory( $this->lockManager, $paths, $type, $status );
  934. }
  935. /**
  936. * Get an array of scoped locks needed for a batch of file operations.
  937. *
  938. * Normally, FileBackend::doOperations() handles locking, unless
  939. * the 'nonLocking' param is passed in. This function is useful if you
  940. * want the files to be locked for a broader scope than just when the
  941. * files are changing. For example, if you need to update DB metadata,
  942. * you may want to keep the files locked until finished.
  943. *
  944. * @see FileBackend::doOperations()
  945. *
  946. * @param $ops Array List of file operations to FileBackend::doOperations()
  947. * @param $status Status Status to update on lock/unlock
  948. * @return Array List of ScopedFileLocks or null values
  949. * @since 1.20
  950. */
  951. abstract public function getScopedLocksForOps( array $ops, Status $status );
  952. /**
  953. * Get the root storage path of this backend.
  954. * All container paths are "subdirectories" of this path.
  955. *
  956. * @return string Storage path
  957. * @since 1.20
  958. */
  959. final public function getRootStoragePath() {
  960. return "mwstore://{$this->name}";
  961. }
  962. /**
  963. * Get the file journal object for this backend
  964. *
  965. * @return FileJournal
  966. */
  967. final public function getJournal() {
  968. return $this->fileJournal;
  969. }
  970. /**
  971. * Check if a given path is a "mwstore://" path.
  972. * This does not do any further validation or any existence checks.
  973. *
  974. * @param $path string
  975. * @return bool
  976. */
  977. final public static function isStoragePath( $path ) {
  978. return ( strpos( $path, 'mwstore://' ) === 0 );
  979. }
  980. /**
  981. * Split a storage path into a backend name, a container name,
  982. * and a relative file path. The relative path may be the empty string.
  983. * This does not do any path normalization or traversal checks.
  984. *
  985. * @param $storagePath string
  986. * @return Array (backend, container, rel object) or (null, null, null)
  987. */
  988. final public static function splitStoragePath( $storagePath ) {
  989. if ( self::isStoragePath( $storagePath ) ) {
  990. // Remove the "mwstore://" prefix and split the path
  991. $parts = explode( '/', substr( $storagePath, 10 ), 3 );
  992. if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
  993. if ( count( $parts ) == 3 ) {
  994. return $parts; // e.g. "backend/container/path"
  995. } else {
  996. return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
  997. }
  998. }
  999. }
  1000. return array( null, null, null );
  1001. }
  1002. /**
  1003. * Normalize a storage path by cleaning up directory separators.
  1004. * Returns null if the path is not of the format of a valid storage path.
  1005. *
  1006. * @param $storagePath string
  1007. * @return string|null
  1008. */
  1009. final public static function normalizeStoragePath( $storagePath ) {
  1010. list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
  1011. if ( $relPath !== null ) { // must be for this backend
  1012. $relPath = self::normalizeContainerPath( $relPath );
  1013. if ( $relPath !== null ) {
  1014. return ( $relPath != '' )
  1015. ? "mwstore://{$backend}/{$container}/{$relPath}"
  1016. : "mwstore://{$backend}/{$container}";
  1017. }
  1018. }
  1019. return null;
  1020. }
  1021. /**
  1022. * Get the parent storage directory of a storage path.
  1023. * This returns a path like "mwstore://backend/container",
  1024. * "mwstore://backend/container/...", or null if there is no parent.
  1025. *
  1026. * @param $storagePath string
  1027. * @return string|null
  1028. */
  1029. final public static function parentStoragePath( $storagePath ) {
  1030. $storagePath = dirname( $storagePath );
  1031. list( $b, $cont, $rel ) = self::splitStoragePath( $storagePath );
  1032. return ( $rel === null ) ? null : $storagePath;
  1033. }
  1034. /**
  1035. * Get the final extension from a storage or FS path
  1036. *
  1037. * @param $path string
  1038. * @return string
  1039. */
  1040. final public static function extensionFromPath( $path ) {
  1041. $i = strrpos( $path, '.' );
  1042. return strtolower( $i ? substr( $path, $i + 1 ) : '' );
  1043. }
  1044. /**
  1045. * Check if a relative path has no directory traversals
  1046. *
  1047. * @param $path string
  1048. * @return bool
  1049. * @since 1.20
  1050. */
  1051. final public static function isPathTraversalFree( $path ) {
  1052. return ( self::normalizeContainerPath( $path ) !== null );
  1053. }
  1054. /**
  1055. * Build a Content-Disposition header value per RFC 6266.
  1056. *
  1057. * @param $type string One of (attachment, inline)
  1058. * @param $filename string Suggested file name (should not contain slashes)
  1059. * @return string
  1060. * @since 1.20
  1061. */
  1062. final public static function makeContentDisposition( $type, $filename = '' ) {
  1063. $parts = array();
  1064. $type = strtolower( $type );
  1065. if ( !in_array( $type, array( 'inline', 'attachment' ) ) ) {
  1066. throw new MWException( "Invalid Content-Disposition type '$type'." );
  1067. }
  1068. $parts[] = $type;
  1069. if ( strlen( $filename ) ) {
  1070. $parts[] = "filename*=UTF-8''" . rawurlencode( basename( $filename ) );
  1071. }
  1072. return implode( ';', $parts );
  1073. }
  1074. /**
  1075. * Validate and normalize a relative storage path.
  1076. * Null is returned if the path involves directory traversal.
  1077. * Traversal is insecure for FS backends and broken for others.
  1078. *
  1079. * This uses the same traversal protection as Title::secureAndSplit().
  1080. *
  1081. * @param $path string Storage path relative to a container
  1082. * @return string|null
  1083. */
  1084. final protected static function normalizeContainerPath( $path ) {
  1085. // Normalize directory separators
  1086. $path = strtr( $path, '\\', '/' );
  1087. // Collapse any consecutive directory separators
  1088. $path = preg_replace( '![/]{2,}!', '/', $path );
  1089. // Remove any leading directory separator
  1090. $path = ltrim( $path, '/' );
  1091. // Use the same traversal protection as Title::secureAndSplit()
  1092. if ( strpos( $path, '.' ) !== false ) {
  1093. if (
  1094. $path === '.' ||
  1095. $path === '..' ||
  1096. strpos( $path, './' ) === 0 ||
  1097. strpos( $path, '../' ) === 0 ||
  1098. strpos( $path, '/./' ) !== false ||
  1099. strpos( $path, '/../' ) !== false
  1100. ) {
  1101. return null;
  1102. }
  1103. }
  1104. return $path;
  1105. }
  1106. }