PageRenderTime 64ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/filerepo/FileRepo.php

https://github.com/spenser-roark/OOUG-Wiki
PHP | 1456 lines | 847 code | 99 blank | 510 comment | 141 complexity | ceecbcf94c16ebc3b789bcee3390d769 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0
  1. <?php
  2. /**
  3. * @defgroup FileRepo File Repository
  4. *
  5. * @brief This module handles how MediaWiki interacts with filesystems.
  6. *
  7. * @details
  8. */
  9. /**
  10. * Base code for file repositories.
  11. *
  12. * @file
  13. * @ingroup FileRepo
  14. */
  15. /**
  16. * Base class for file repositories
  17. *
  18. * @ingroup FileRepo
  19. */
  20. class FileRepo {
  21. const FILES_ONLY = 1;
  22. const DELETE_SOURCE = 1;
  23. const OVERWRITE = 2;
  24. const OVERWRITE_SAME = 4;
  25. const SKIP_LOCKING = 8;
  26. /** @var FileBackend */
  27. protected $backend;
  28. /** @var Array Map of zones to config */
  29. protected $zones = array();
  30. var $thumbScriptUrl, $transformVia404;
  31. var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
  32. var $fetchDescription, $initialCapital;
  33. var $pathDisclosureProtection = 'simple'; // 'paranoid'
  34. var $descriptionCacheExpiry, $url, $thumbUrl;
  35. var $hashLevels, $deletedHashLevels;
  36. /**
  37. * Factory functions for creating new files
  38. * Override these in the base class
  39. */
  40. var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
  41. var $oldFileFactory = false;
  42. var $fileFactoryKey = false, $oldFileFactoryKey = false;
  43. function __construct( Array $info = null ) {
  44. // Verify required settings presence
  45. if(
  46. $info === null
  47. || !array_key_exists( 'name', $info )
  48. || !array_key_exists( 'backend', $info )
  49. ) {
  50. throw new MWException( __CLASS__ . " requires an array of options having both 'name' and 'backend' keys.\n" );
  51. }
  52. // Required settings
  53. $this->name = $info['name'];
  54. if ( $info['backend'] instanceof FileBackend ) {
  55. $this->backend = $info['backend']; // useful for testing
  56. } else {
  57. $this->backend = FileBackendGroup::singleton()->get( $info['backend'] );
  58. }
  59. // Optional settings that can have no value
  60. $optionalSettings = array(
  61. 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
  62. 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
  63. 'scriptExtension'
  64. );
  65. foreach ( $optionalSettings as $var ) {
  66. if ( isset( $info[$var] ) ) {
  67. $this->$var = $info[$var];
  68. }
  69. }
  70. // Optional settings that have a default
  71. $this->initialCapital = isset( $info['initialCapital'] )
  72. ? $info['initialCapital']
  73. : MWNamespace::isCapitalized( NS_FILE );
  74. $this->url = isset( $info['url'] )
  75. ? $info['url']
  76. : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
  77. if ( isset( $info['thumbUrl'] ) ) {
  78. $this->thumbUrl = $info['thumbUrl'];
  79. } else {
  80. $this->thumbUrl = $this->url ? "{$this->url}/thumb" : false;
  81. }
  82. $this->hashLevels = isset( $info['hashLevels'] )
  83. ? $info['hashLevels']
  84. : 2;
  85. $this->deletedHashLevels = isset( $info['deletedHashLevels'] )
  86. ? $info['deletedHashLevels']
  87. : $this->hashLevels;
  88. $this->transformVia404 = !empty( $info['transformVia404'] );
  89. $this->zones = isset( $info['zones'] )
  90. ? $info['zones']
  91. : array();
  92. // Give defaults for the basic zones...
  93. foreach ( array( 'public', 'thumb', 'temp', 'deleted' ) as $zone ) {
  94. if ( !isset( $this->zones[$zone] ) ) {
  95. $this->zones[$zone] = array(
  96. 'container' => "{$this->name}-{$zone}",
  97. 'directory' => '' // container root
  98. );
  99. }
  100. }
  101. }
  102. /**
  103. * Get the file backend instance
  104. *
  105. * @return FileBackend
  106. */
  107. public function getBackend() {
  108. return $this->backend;
  109. }
  110. /**
  111. * Prepare a single zone or list of zones for usage.
  112. * See initDeletedDir() for additional setup needed for the 'deleted' zone.
  113. *
  114. * @param $doZones Array Only do a particular zones
  115. * @return Status
  116. */
  117. protected function initZones( $doZones = array() ) {
  118. $status = $this->newGood();
  119. foreach ( (array)$doZones as $zone ) {
  120. $root = $this->getZonePath( $zone );
  121. if ( $root === null ) {
  122. throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
  123. }
  124. }
  125. return $status;
  126. }
  127. /**
  128. * Take all available measures to prevent web accessibility of new deleted
  129. * directories, in case the user has not configured offline storage
  130. *
  131. * @param $dir string
  132. * @return void
  133. */
  134. protected function initDeletedDir( $dir ) {
  135. $this->backend->secure( // prevent web access & dir listings
  136. array( 'dir' => $dir, 'noAccess' => true, 'noListing' => true ) );
  137. }
  138. /**
  139. * Determine if a string is an mwrepo:// URL
  140. *
  141. * @param $url string
  142. * @return bool
  143. */
  144. public static function isVirtualUrl( $url ) {
  145. return substr( $url, 0, 9 ) == 'mwrepo://';
  146. }
  147. /**
  148. * Get a URL referring to this repository, with the private mwrepo protocol.
  149. * The suffix, if supplied, is considered to be unencoded, and will be
  150. * URL-encoded before being returned.
  151. *
  152. * @param $suffix string
  153. * @return string
  154. */
  155. public function getVirtualUrl( $suffix = false ) {
  156. $path = 'mwrepo://' . $this->name;
  157. if ( $suffix !== false ) {
  158. $path .= '/' . rawurlencode( $suffix );
  159. }
  160. return $path;
  161. }
  162. /**
  163. * Get the URL corresponding to one of the four basic zones
  164. *
  165. * @param $zone String: one of: public, deleted, temp, thumb
  166. * @return String or false
  167. */
  168. public function getZoneUrl( $zone ) {
  169. switch ( $zone ) {
  170. case 'public':
  171. return $this->url;
  172. case 'temp':
  173. return "{$this->url}/temp";
  174. case 'deleted':
  175. return false; // no public URL
  176. case 'thumb':
  177. return $this->thumbUrl;
  178. default:
  179. return false;
  180. }
  181. }
  182. /**
  183. * Get the backend storage path corresponding to a virtual URL
  184. *
  185. * @param $url string
  186. * @return string
  187. */
  188. function resolveVirtualUrl( $url ) {
  189. if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
  190. throw new MWException( __METHOD__.': unknown protocol' );
  191. }
  192. $bits = explode( '/', substr( $url, 9 ), 3 );
  193. if ( count( $bits ) != 3 ) {
  194. throw new MWException( __METHOD__.": invalid mwrepo URL: $url" );
  195. }
  196. list( $repo, $zone, $rel ) = $bits;
  197. if ( $repo !== $this->name ) {
  198. throw new MWException( __METHOD__.": fetching from a foreign repo is not supported" );
  199. }
  200. $base = $this->getZonePath( $zone );
  201. if ( !$base ) {
  202. throw new MWException( __METHOD__.": invalid zone: $zone" );
  203. }
  204. return $base . '/' . rawurldecode( $rel );
  205. }
  206. /**
  207. * The the storage container and base path of a zone
  208. *
  209. * @param $zone string
  210. * @return Array (container, base path) or (null, null)
  211. */
  212. protected function getZoneLocation( $zone ) {
  213. if ( !isset( $this->zones[$zone] ) ) {
  214. return array( null, null ); // bogus
  215. }
  216. return array( $this->zones[$zone]['container'], $this->zones[$zone]['directory'] );
  217. }
  218. /**
  219. * Get the storage path corresponding to one of the zones
  220. *
  221. * @param $zone string
  222. * @return string|null
  223. */
  224. public function getZonePath( $zone ) {
  225. list( $container, $base ) = $this->getZoneLocation( $zone );
  226. if ( $container === null || $base === null ) {
  227. return null;
  228. }
  229. $backendName = $this->backend->getName();
  230. if ( $base != '' ) { // may not be set
  231. $base = "/{$base}";
  232. }
  233. return "mwstore://$backendName/{$container}{$base}";
  234. }
  235. /**
  236. * Create a new File object from the local repository
  237. *
  238. * @param $title Mixed: Title object or string
  239. * @param $time Mixed: Time at which the image was uploaded.
  240. * If this is specified, the returned object will be an
  241. * instance of the repository's old file class instead of a
  242. * current file. Repositories not supporting version control
  243. * should return false if this parameter is set.
  244. * @return File|null A File, or null if passed an invalid Title
  245. */
  246. public function newFile( $title, $time = false ) {
  247. $title = File::normalizeTitle( $title );
  248. if ( !$title ) {
  249. return null;
  250. }
  251. if ( $time ) {
  252. if ( $this->oldFileFactory ) {
  253. return call_user_func( $this->oldFileFactory, $title, $this, $time );
  254. } else {
  255. return false;
  256. }
  257. } else {
  258. return call_user_func( $this->fileFactory, $title, $this );
  259. }
  260. }
  261. /**
  262. * Find an instance of the named file created at the specified time
  263. * Returns false if the file does not exist. Repositories not supporting
  264. * version control should return false if the time is specified.
  265. *
  266. * @param $title Mixed: Title object or string
  267. * @param $options array Associative array of options:
  268. * time: requested time for an archived image, or false for the
  269. * current version. An image object will be returned which was
  270. * created at the specified time.
  271. *
  272. * ignoreRedirect: If true, do not follow file redirects
  273. *
  274. * private: If true, return restricted (deleted) files if the current
  275. * user is allowed to view them. Otherwise, such files will not
  276. * be found.
  277. * @return File|false
  278. */
  279. public function findFile( $title, $options = array() ) {
  280. $title = File::normalizeTitle( $title );
  281. if ( !$title ) {
  282. return false;
  283. }
  284. $time = isset( $options['time'] ) ? $options['time'] : false;
  285. # First try the current version of the file to see if it precedes the timestamp
  286. $img = $this->newFile( $title );
  287. if ( !$img ) {
  288. return false;
  289. }
  290. if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
  291. return $img;
  292. }
  293. # Now try an old version of the file
  294. if ( $time !== false ) {
  295. $img = $this->newFile( $title, $time );
  296. if ( $img && $img->exists() ) {
  297. if ( !$img->isDeleted( File::DELETED_FILE ) ) {
  298. return $img; // always OK
  299. } elseif ( !empty( $options['private'] ) && $img->userCan( File::DELETED_FILE ) ) {
  300. return $img;
  301. }
  302. }
  303. }
  304. # Now try redirects
  305. if ( !empty( $options['ignoreRedirect'] ) ) {
  306. return false;
  307. }
  308. $redir = $this->checkRedirect( $title );
  309. if ( $redir && $title->getNamespace() == NS_FILE) {
  310. $img = $this->newFile( $redir );
  311. if ( !$img ) {
  312. return false;
  313. }
  314. if ( $img->exists() ) {
  315. $img->redirectedFrom( $title->getDBkey() );
  316. return $img;
  317. }
  318. }
  319. return false;
  320. }
  321. /**
  322. * Find many files at once.
  323. *
  324. * @param $items An array of titles, or an array of findFile() options with
  325. * the "title" option giving the title. Example:
  326. *
  327. * $findItem = array( 'title' => $title, 'private' => true );
  328. * $findBatch = array( $findItem );
  329. * $repo->findFiles( $findBatch );
  330. * @return array
  331. */
  332. public function findFiles( $items ) {
  333. $result = array();
  334. foreach ( $items as $item ) {
  335. if ( is_array( $item ) ) {
  336. $title = $item['title'];
  337. $options = $item;
  338. unset( $options['title'] );
  339. } else {
  340. $title = $item;
  341. $options = array();
  342. }
  343. $file = $this->findFile( $title, $options );
  344. if ( $file ) {
  345. $result[$file->getTitle()->getDBkey()] = $file;
  346. }
  347. }
  348. return $result;
  349. }
  350. /**
  351. * Find an instance of the file with this key, created at the specified time
  352. * Returns false if the file does not exist. Repositories not supporting
  353. * version control should return false if the time is specified.
  354. *
  355. * @param $sha1 String base 36 SHA-1 hash
  356. * @param $options Option array, same as findFile().
  357. * @return File|false
  358. */
  359. public function findFileFromKey( $sha1, $options = array() ) {
  360. $time = isset( $options['time'] ) ? $options['time'] : false;
  361. # First try to find a matching current version of a file...
  362. if ( $this->fileFactoryKey ) {
  363. $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
  364. } else {
  365. return false; // find-by-sha1 not supported
  366. }
  367. if ( $img && $img->exists() ) {
  368. return $img;
  369. }
  370. # Now try to find a matching old version of a file...
  371. if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
  372. $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
  373. if ( $img && $img->exists() ) {
  374. if ( !$img->isDeleted( File::DELETED_FILE ) ) {
  375. return $img; // always OK
  376. } elseif ( !empty( $options['private'] ) && $img->userCan( File::DELETED_FILE ) ) {
  377. return $img;
  378. }
  379. }
  380. }
  381. return false;
  382. }
  383. /**
  384. * Get an array or iterator of file objects for files that have a given
  385. * SHA-1 content hash.
  386. *
  387. * STUB
  388. */
  389. public function findBySha1( $hash ) {
  390. return array();
  391. }
  392. /**
  393. * Get the public root URL of the repository
  394. *
  395. * @return string|false
  396. */
  397. public function getRootUrl() {
  398. return $this->url;
  399. }
  400. /**
  401. * Returns true if the repository uses a multi-level directory structure
  402. *
  403. * @return string
  404. */
  405. public function isHashed() {
  406. return (bool)$this->hashLevels;
  407. }
  408. /**
  409. * Get the URL of thumb.php
  410. *
  411. * @return string
  412. */
  413. public function getThumbScriptUrl() {
  414. return $this->thumbScriptUrl;
  415. }
  416. /**
  417. * Returns true if the repository can transform files via a 404 handler
  418. *
  419. * @return bool
  420. */
  421. public function canTransformVia404() {
  422. return $this->transformVia404;
  423. }
  424. /**
  425. * Get the name of an image from its title object
  426. *
  427. * @param $title Title
  428. */
  429. public function getNameFromTitle( Title $title ) {
  430. global $wgContLang;
  431. if ( $this->initialCapital != MWNamespace::isCapitalized( NS_FILE ) ) {
  432. $name = $title->getUserCaseDBKey();
  433. if ( $this->initialCapital ) {
  434. $name = $wgContLang->ucfirst( $name );
  435. }
  436. } else {
  437. $name = $title->getDBkey();
  438. }
  439. return $name;
  440. }
  441. /**
  442. * Get the public zone root storage directory of the repository
  443. *
  444. * @return string
  445. */
  446. public function getRootDirectory() {
  447. return $this->getZonePath( 'public' );
  448. }
  449. /**
  450. * Get a relative path including trailing slash, e.g. f/fa/
  451. * If the repo is not hashed, returns an empty string
  452. *
  453. * @param $name string
  454. * @return string
  455. */
  456. public function getHashPath( $name ) {
  457. return self::getHashPathForLevel( $name, $this->hashLevels );
  458. }
  459. /**
  460. * @param $name
  461. * @param $levels
  462. * @return string
  463. */
  464. static function getHashPathForLevel( $name, $levels ) {
  465. if ( $levels == 0 ) {
  466. return '';
  467. } else {
  468. $hash = md5( $name );
  469. $path = '';
  470. for ( $i = 1; $i <= $levels; $i++ ) {
  471. $path .= substr( $hash, 0, $i ) . '/';
  472. }
  473. return $path;
  474. }
  475. }
  476. /**
  477. * Get the number of hash directory levels
  478. *
  479. * @return integer
  480. */
  481. public function getHashLevels() {
  482. return $this->hashLevels;
  483. }
  484. /**
  485. * Get the name of this repository, as specified by $info['name]' to the constructor
  486. *
  487. * @return string
  488. */
  489. public function getName() {
  490. return $this->name;
  491. }
  492. /**
  493. * Make an url to this repo
  494. *
  495. * @param $query mixed Query string to append
  496. * @param $entry string Entry point; defaults to index
  497. * @return string|false
  498. */
  499. public function makeUrl( $query = '', $entry = 'index' ) {
  500. if ( isset( $this->scriptDirUrl ) ) {
  501. $ext = isset( $this->scriptExtension ) ? $this->scriptExtension : '.php';
  502. return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
  503. }
  504. return false;
  505. }
  506. /**
  507. * Get the URL of an image description page. May return false if it is
  508. * unknown or not applicable. In general this should only be called by the
  509. * File class, since it may return invalid results for certain kinds of
  510. * repositories. Use File::getDescriptionUrl() in user code.
  511. *
  512. * In particular, it uses the article paths as specified to the repository
  513. * constructor, whereas local repositories use the local Title functions.
  514. *
  515. * @param $name string
  516. * @return string
  517. */
  518. public function getDescriptionUrl( $name ) {
  519. $encName = wfUrlencode( $name );
  520. if ( !is_null( $this->descBaseUrl ) ) {
  521. # "http://example.com/wiki/Image:"
  522. return $this->descBaseUrl . $encName;
  523. }
  524. if ( !is_null( $this->articleUrl ) ) {
  525. # "http://example.com/wiki/$1"
  526. #
  527. # We use "Image:" as the canonical namespace for
  528. # compatibility across all MediaWiki versions.
  529. return str_replace( '$1',
  530. "Image:$encName", $this->articleUrl );
  531. }
  532. if ( !is_null( $this->scriptDirUrl ) ) {
  533. # "http://example.com/w"
  534. #
  535. # We use "Image:" as the canonical namespace for
  536. # compatibility across all MediaWiki versions,
  537. # and just sort of hope index.php is right. ;)
  538. return $this->makeUrl( "title=Image:$encName" );
  539. }
  540. return false;
  541. }
  542. /**
  543. * Get the URL of the content-only fragment of the description page. For
  544. * MediaWiki this means action=render. This should only be called by the
  545. * repository's file class, since it may return invalid results. User code
  546. * should use File::getDescriptionText().
  547. *
  548. * @param $name String: name of image to fetch
  549. * @param $lang String: language to fetch it in, if any.
  550. * @return string
  551. */
  552. public function getDescriptionRenderUrl( $name, $lang = null ) {
  553. $query = 'action=render';
  554. if ( !is_null( $lang ) ) {
  555. $query .= '&uselang=' . $lang;
  556. }
  557. if ( isset( $this->scriptDirUrl ) ) {
  558. return $this->makeUrl(
  559. 'title=' .
  560. wfUrlencode( 'Image:' . $name ) .
  561. "&$query" );
  562. } else {
  563. $descUrl = $this->getDescriptionUrl( $name );
  564. if ( $descUrl ) {
  565. return wfAppendQuery( $descUrl, $query );
  566. } else {
  567. return false;
  568. }
  569. }
  570. }
  571. /**
  572. * Get the URL of the stylesheet to apply to description pages
  573. *
  574. * @return string|false
  575. */
  576. public function getDescriptionStylesheetUrl() {
  577. if ( isset( $this->scriptDirUrl ) ) {
  578. return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
  579. wfArrayToCGI( Skin::getDynamicStylesheetQuery() ) );
  580. }
  581. return false;
  582. }
  583. /**
  584. * Store a file to a given destination.
  585. *
  586. * @param $srcPath String: source FS path, storage path, or virtual URL
  587. * @param $dstZone String: destination zone
  588. * @param $dstRel String: destination relative path
  589. * @param $flags Integer: bitwise combination of the following flags:
  590. * self::DELETE_SOURCE Delete the source file after upload
  591. * self::OVERWRITE Overwrite an existing destination file instead of failing
  592. * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
  593. * same contents as the source
  594. * self::SKIP_LOCKING Skip any file locking when doing the store
  595. * @return FileRepoStatus
  596. */
  597. public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
  598. $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
  599. if ( $status->successCount == 0 ) {
  600. $status->ok = false;
  601. }
  602. return $status;
  603. }
  604. /**
  605. * Store a batch of files
  606. *
  607. * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
  608. * @param $flags Integer: bitwise combination of the following flags:
  609. * self::DELETE_SOURCE Delete the source file after upload
  610. * self::OVERWRITE Overwrite an existing destination file instead of failing
  611. * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
  612. * same contents as the source
  613. * self::SKIP_LOCKING Skip any file locking when doing the store
  614. * @return FileRepoStatus
  615. */
  616. public function storeBatch( $triplets, $flags = 0 ) {
  617. $backend = $this->backend; // convenience
  618. $status = $this->newGood();
  619. $operations = array();
  620. $sourceFSFilesToDelete = array(); // cleanup for disk source files
  621. // Validate each triplet and get the store operation...
  622. foreach ( $triplets as $triplet ) {
  623. list( $srcPath, $dstZone, $dstRel ) = $triplet;
  624. wfDebug( __METHOD__
  625. . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
  626. );
  627. // Resolve destination path
  628. $root = $this->getZonePath( $dstZone );
  629. if ( !$root ) {
  630. throw new MWException( "Invalid zone: $dstZone" );
  631. }
  632. if ( !$this->validateFilename( $dstRel ) ) {
  633. throw new MWException( 'Validation error in $dstRel' );
  634. }
  635. $dstPath = "$root/$dstRel";
  636. $dstDir = dirname( $dstPath );
  637. // Create destination directories for this triplet
  638. if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
  639. return $this->newFatal( 'directorycreateerror', $dstDir );
  640. }
  641. if ( $dstZone == 'deleted' ) {
  642. $this->initDeletedDir( $dstDir );
  643. }
  644. // Resolve source to a storage path if virtual
  645. if ( self::isVirtualUrl( $srcPath ) ) {
  646. $srcPath = $this->resolveVirtualUrl( $srcPath );
  647. }
  648. // Get the appropriate file operation
  649. if ( FileBackend::isStoragePath( $srcPath ) ) {
  650. $opName = ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy';
  651. } else {
  652. $opName = 'store';
  653. if ( $flags & self::DELETE_SOURCE ) {
  654. $sourceFSFilesToDelete[] = $srcPath;
  655. }
  656. }
  657. $operations[] = array(
  658. 'op' => $opName,
  659. 'src' => $srcPath,
  660. 'dst' => $dstPath,
  661. 'overwrite' => $flags & self::OVERWRITE,
  662. 'overwriteSame' => $flags & self::OVERWRITE_SAME,
  663. );
  664. }
  665. // Execute the store operation for each triplet
  666. $opts = array( 'force' => true );
  667. if ( $flags & self::SKIP_LOCKING ) {
  668. $opts['nonLocking'] = true;
  669. }
  670. $status->merge( $backend->doOperations( $operations, $opts ) );
  671. // Cleanup for disk source files...
  672. foreach ( $sourceFSFilesToDelete as $file ) {
  673. wfSuppressWarnings();
  674. unlink( $file ); // FS cleanup
  675. wfRestoreWarnings();
  676. }
  677. return $status;
  678. }
  679. /**
  680. * Deletes a batch of files.
  681. * Each file can be a (zone, rel) pair, virtual url, storage path, or FS path.
  682. * It will try to delete each file, but ignores any errors that may occur.
  683. *
  684. * @param $pairs array List of files to delete
  685. * @param $flags Integer: bitwise combination of the following flags:
  686. * self::SKIP_LOCKING Skip any file locking when doing the deletions
  687. * @return void
  688. */
  689. public function cleanupBatch( $files, $flags = 0 ) {
  690. $operations = array();
  691. $sourceFSFilesToDelete = array(); // cleanup for disk source files
  692. foreach ( $files as $file ) {
  693. if ( is_array( $file ) ) {
  694. // This is a pair, extract it
  695. list( $zone, $rel ) = $file;
  696. $root = $this->getZonePath( $zone );
  697. $path = "$root/$rel";
  698. } else {
  699. if ( self::isVirtualUrl( $file ) ) {
  700. // This is a virtual url, resolve it
  701. $path = $this->resolveVirtualUrl( $file );
  702. } else {
  703. // This is a full file name
  704. $path = $file;
  705. }
  706. }
  707. // Get a file operation if needed
  708. if ( FileBackend::isStoragePath( $path ) ) {
  709. $operations[] = array(
  710. 'op' => 'delete',
  711. 'src' => $path,
  712. );
  713. } else {
  714. $sourceFSFilesToDelete[] = $path;
  715. }
  716. }
  717. // Actually delete files from storage...
  718. $opts = array( 'force' => true );
  719. if ( $flags & self::SKIP_LOCKING ) {
  720. $opts['nonLocking'] = true;
  721. }
  722. $this->backend->doOperations( $operations, $opts );
  723. // Cleanup for disk source files...
  724. foreach ( $sourceFSFilesToDelete as $file ) {
  725. wfSuppressWarnings();
  726. unlink( $file ); // FS cleanup
  727. wfRestoreWarnings();
  728. }
  729. }
  730. /**
  731. * Pick a random name in the temp zone and store a file to it.
  732. * Returns a FileRepoStatus object with the file Virtual URL in the value,
  733. * file can later be disposed using FileRepo::freeTemp().
  734. *
  735. *
  736. * @param $originalName String: the base name of the file as specified
  737. * by the user. The file extension will be maintained.
  738. * @param $srcPath String: the current location of the file.
  739. * @return FileRepoStatus object with the URL in the value.
  740. */
  741. public function storeTemp( $originalName, $srcPath ) {
  742. $date = gmdate( "YmdHis" );
  743. $hashPath = $this->getHashPath( $originalName );
  744. $dstRel = "{$hashPath}{$date}!{$originalName}";
  745. $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
  746. $result = $this->store( $srcPath, 'temp', $dstRel, self::SKIP_LOCKING );
  747. $result->value = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
  748. return $result;
  749. }
  750. /**
  751. * Concatenate a list of files into a target file location.
  752. *
  753. * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
  754. * @param $dstPath String Target file system path
  755. * @param $flags Integer: bitwise combination of the following flags:
  756. * self::DELETE_SOURCE Delete the source files
  757. * @return FileRepoStatus
  758. */
  759. function concatenate( $srcPaths, $dstPath, $flags = 0 ) {
  760. $status = $this->newGood();
  761. $sources = array();
  762. $deleteOperations = array(); // post-concatenate ops
  763. foreach ( $srcPaths as $srcPath ) {
  764. // Resolve source to a storage path if virtual
  765. $source = $this->resolveToStoragePath( $srcPath );
  766. $sources[] = $source; // chunk to merge
  767. if ( $flags & self::DELETE_SOURCE ) {
  768. $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
  769. }
  770. }
  771. // Concatenate the chunks into one FS file
  772. $params = array( 'srcs' => $sources, 'dst' => $dstPath );
  773. $status->merge( $this->backend->concatenate( $params ) );
  774. if ( !$status->isOK() ) {
  775. return $status;
  776. }
  777. // Delete the sources if required
  778. if ( $deleteOperations ) {
  779. $opts = array( 'force' => true );
  780. $status->merge( $this->backend->doOperations( $deleteOperations, $opts ) );
  781. }
  782. // Make sure status is OK, despite any $deleteOperations fatals
  783. $status->setResult( true );
  784. return $status;
  785. }
  786. /**
  787. * Remove a temporary file or mark it for garbage collection
  788. *
  789. * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
  790. * @return Boolean: true on success, false on failure
  791. */
  792. public function freeTemp( $virtualUrl ) {
  793. $temp = "mwrepo://{$this->name}/temp";
  794. if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
  795. wfDebug( __METHOD__.": Invalid temp virtual URL\n" );
  796. return false;
  797. }
  798. $path = $this->resolveVirtualUrl( $virtualUrl );
  799. $op = array( 'op' => 'delete', 'src' => $path );
  800. $status = $this->backend->doOperation( $op );
  801. return $status->isOK();
  802. }
  803. /**
  804. * Copy or move a file either from a storage path, virtual URL,
  805. * or FS path, into this repository at the specified destination location.
  806. *
  807. * Returns a FileRepoStatus object. On success, the value contains "new" or
  808. * "archived", to indicate whether the file was new with that name.
  809. *
  810. * @param $srcPath String: the source FS path, storage path, or URL
  811. * @param $dstRel String: the destination relative path
  812. * @param $archiveRel String: the relative path where the existing file is to
  813. * be archived, if there is one. Relative to the public zone root.
  814. * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
  815. * that the source file should be deleted if possible
  816. */
  817. public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
  818. $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
  819. if ( $status->successCount == 0 ) {
  820. $status->ok = false;
  821. }
  822. if ( isset( $status->value[0] ) ) {
  823. $status->value = $status->value[0];
  824. } else {
  825. $status->value = false;
  826. }
  827. return $status;
  828. }
  829. /**
  830. * Publish a batch of files
  831. *
  832. * @param $triplets Array: (source, dest, archive) triplets as per publish()
  833. * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
  834. * that the source files should be deleted if possible
  835. * @return FileRepoStatus
  836. */
  837. public function publishBatch( $triplets, $flags = 0 ) {
  838. $backend = $this->backend; // convenience
  839. // Try creating directories
  840. $status = $this->initZones( 'public' );
  841. if ( !$status->isOK() ) {
  842. return $status;
  843. }
  844. $status = $this->newGood( array() );
  845. $operations = array();
  846. $sourceFSFilesToDelete = array(); // cleanup for disk source files
  847. // Validate each triplet and get the store operation...
  848. foreach ( $triplets as $i => $triplet ) {
  849. list( $srcPath, $dstRel, $archiveRel ) = $triplet;
  850. // Resolve source to a storage path if virtual
  851. if ( substr( $srcPath, 0, 9 ) == 'mwrepo://' ) {
  852. $srcPath = $this->resolveVirtualUrl( $srcPath );
  853. }
  854. if ( !$this->validateFilename( $dstRel ) ) {
  855. throw new MWException( 'Validation error in $dstRel' );
  856. }
  857. if ( !$this->validateFilename( $archiveRel ) ) {
  858. throw new MWException( 'Validation error in $archiveRel' );
  859. }
  860. $publicRoot = $this->getZonePath( 'public' );
  861. $dstPath = "$publicRoot/$dstRel";
  862. $archivePath = "$publicRoot/$archiveRel";
  863. $dstDir = dirname( $dstPath );
  864. $archiveDir = dirname( $archivePath );
  865. // Abort immediately on directory creation errors since they're likely to be repetitive
  866. if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
  867. return $this->newFatal( 'directorycreateerror', $dstDir );
  868. }
  869. if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
  870. return $this->newFatal( 'directorycreateerror', $archiveDir );
  871. }
  872. // Archive destination file if it exists
  873. if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
  874. // Check if the archive file exists
  875. // This is a sanity check to avoid data loss. In UNIX, the rename primitive
  876. // unlinks the destination file if it exists. DB-based synchronisation in
  877. // publishBatch's caller should prevent races. In Windows there's no
  878. // problem because the rename primitive fails if the destination exists.
  879. if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
  880. $operations[] = array( 'op' => 'null' );
  881. continue;
  882. } else {
  883. $operations[] = array(
  884. 'op' => 'move',
  885. 'src' => $dstPath,
  886. 'dst' => $archivePath
  887. );
  888. }
  889. $status->value[$i] = 'archived';
  890. } else {
  891. $status->value[$i] = 'new';
  892. }
  893. // Copy (or move) the source file to the destination
  894. if ( FileBackend::isStoragePath( $srcPath ) ) {
  895. if ( $flags & self::DELETE_SOURCE ) {
  896. $operations[] = array(
  897. 'op' => 'move',
  898. 'src' => $srcPath,
  899. 'dst' => $dstPath
  900. );
  901. } else {
  902. $operations[] = array(
  903. 'op' => 'copy',
  904. 'src' => $srcPath,
  905. 'dst' => $dstPath
  906. );
  907. }
  908. } else { // FS source path
  909. $operations[] = array(
  910. 'op' => 'store',
  911. 'src' => $srcPath,
  912. 'dst' => $dstPath
  913. );
  914. if ( $flags & self::DELETE_SOURCE ) {
  915. $sourceFSFilesToDelete[] = $srcPath;
  916. }
  917. }
  918. }
  919. // Execute the operations for each triplet
  920. $opts = array( 'force' => true );
  921. $status->merge( $backend->doOperations( $operations, $opts ) );
  922. // Cleanup for disk source files...
  923. foreach ( $sourceFSFilesToDelete as $file ) {
  924. wfSuppressWarnings();
  925. unlink( $file ); // FS cleanup
  926. wfRestoreWarnings();
  927. }
  928. return $status;
  929. }
  930. /**
  931. * Checks existence of a a file
  932. *
  933. * @param $file Virtual URL (or storage path) of file to check
  934. * @param $flags Integer: bitwise combination of the following flags:
  935. * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
  936. * @return bool
  937. */
  938. public function fileExists( $file, $flags = 0 ) {
  939. $result = $this->fileExistsBatch( array( $file ), $flags );
  940. return $result[0];
  941. }
  942. /**
  943. * Checks existence of an array of files.
  944. *
  945. * @param $files Array: Virtual URLs (or storage paths) of files to check
  946. * @param $flags Integer: bitwise combination of the following flags:
  947. * self::FILES_ONLY Mark file as existing only if it is a file (not directory)
  948. * @return Either array of files and existence flags, or false
  949. */
  950. public function fileExistsBatch( $files, $flags = 0 ) {
  951. $result = array();
  952. foreach ( $files as $key => $file ) {
  953. if ( self::isVirtualUrl( $file ) ) {
  954. $file = $this->resolveVirtualUrl( $file );
  955. }
  956. if ( FileBackend::isStoragePath( $file ) ) {
  957. $result[$key] = $this->backend->fileExists( array( 'src' => $file ) );
  958. } else {
  959. if ( $flags & self::FILES_ONLY ) {
  960. $result[$key] = is_file( $file ); // FS only
  961. } else {
  962. $result[$key] = file_exists( $file ); // FS only
  963. }
  964. }
  965. }
  966. return $result;
  967. }
  968. /**
  969. * Move a file to the deletion archive.
  970. * If no valid deletion archive exists, this may either delete the file
  971. * or throw an exception, depending on the preference of the repository
  972. *
  973. * @param $srcRel Mixed: relative path for the file to be deleted
  974. * @param $archiveRel Mixed: relative path for the archive location.
  975. * Relative to a private archive directory.
  976. * @return FileRepoStatus object
  977. */
  978. public function delete( $srcRel, $archiveRel ) {
  979. return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
  980. }
  981. /**
  982. * Move a group of files to the deletion archive.
  983. *
  984. * If no valid deletion archive is configured, this may either delete the
  985. * file or throw an exception, depending on the preference of the repository.
  986. *
  987. * The overwrite policy is determined by the repository -- currently LocalRepo
  988. * assumes a naming scheme in the deleted zone based on content hash, as
  989. * opposed to the public zone which is assumed to be unique.
  990. *
  991. * @param $sourceDestPairs Array of source/destination pairs. Each element
  992. * is a two-element array containing the source file path relative to the
  993. * public root in the first element, and the archive file path relative
  994. * to the deleted zone root in the second element.
  995. * @return FileRepoStatus
  996. */
  997. public function deleteBatch( $sourceDestPairs ) {
  998. $backend = $this->backend; // convenience
  999. // Try creating directories
  1000. $status = $this->initZones( array( 'public', 'deleted' ) );
  1001. if ( !$status->isOK() ) {
  1002. return $status;
  1003. }
  1004. $status = $this->newGood();
  1005. $operations = array();
  1006. // Validate filenames and create archive directories
  1007. foreach ( $sourceDestPairs as $pair ) {
  1008. list( $srcRel, $archiveRel ) = $pair;
  1009. if ( !$this->validateFilename( $srcRel ) ) {
  1010. throw new MWException( __METHOD__.':Validation error in $srcRel' );
  1011. }
  1012. if ( !$this->validateFilename( $archiveRel ) ) {
  1013. throw new MWException( __METHOD__.':Validation error in $archiveRel' );
  1014. }
  1015. $publicRoot = $this->getZonePath( 'public' );
  1016. $srcPath = "{$publicRoot}/$srcRel";
  1017. $deletedRoot = $this->getZonePath( 'deleted' );
  1018. $archivePath = "{$deletedRoot}/{$archiveRel}";
  1019. $archiveDir = dirname( $archivePath ); // does not touch FS
  1020. // Create destination directories
  1021. if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
  1022. return $this->newFatal( 'directorycreateerror', $archiveDir );
  1023. }
  1024. $this->initDeletedDir( $archiveDir );
  1025. $operations[] = array(
  1026. 'op' => 'move',
  1027. 'src' => $srcPath,
  1028. 'dst' => $archivePath,
  1029. // We may have 2+ identical files being deleted,
  1030. // all of which will map to the same destination file
  1031. 'overwriteSame' => true // also see bug 31792
  1032. );
  1033. }
  1034. // Move the files by execute the operations for each pair.
  1035. // We're now committed to returning an OK result, which will
  1036. // lead to the files being moved in the DB also.
  1037. $opts = array( 'force' => true );
  1038. $status->merge( $backend->doOperations( $operations, $opts ) );
  1039. return $status;
  1040. }
  1041. /**
  1042. * Get a relative path for a deletion archive key,
  1043. * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
  1044. *
  1045. * @return string
  1046. */
  1047. public function getDeletedHashPath( $key ) {
  1048. $path = '';
  1049. for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
  1050. $path .= $key[$i] . '/';
  1051. }
  1052. return $path;
  1053. }
  1054. /**
  1055. * If a path is a virtual URL, resolve it to a storage path.
  1056. * Otherwise, just return the path as it is.
  1057. *
  1058. * @param $path string
  1059. * @return string
  1060. * @throws MWException
  1061. */
  1062. protected function resolveToStoragePath( $path ) {
  1063. if ( $this->isVirtualUrl( $path ) ) {
  1064. return $this->resolveVirtualUrl( $path );
  1065. }
  1066. return $path;
  1067. }
  1068. /**
  1069. * Get a local FS copy of a file with a given virtual URL/storage path.
  1070. * Temporary files may be purged when the file object falls out of scope.
  1071. *
  1072. * @param $virtualUrl string
  1073. * @return TempFSFile|null Returns null on failure
  1074. */
  1075. public function getLocalCopy( $virtualUrl ) {
  1076. $path = $this->resolveToStoragePath( $virtualUrl );
  1077. return $this->backend->getLocalCopy( array( 'src' => $path ) );
  1078. }
  1079. /**
  1080. * Get a local FS file with a given virtual URL/storage path.
  1081. * The file is either an original or a copy. It should not be changed.
  1082. * Temporary files may be purged when the file object falls out of scope.
  1083. *
  1084. * @param $virtualUrl string
  1085. * @return FSFile|null Returns null on failure.
  1086. */
  1087. public function getLocalReference( $virtualUrl ) {
  1088. $path = $this->resolveToStoragePath( $virtualUrl );
  1089. return $this->backend->getLocalReference( array( 'src' => $path ) );
  1090. }
  1091. /**
  1092. * Get properties of a file with a given virtual URL/storage path.
  1093. * Properties should ultimately be obtained via FSFile::getProps().
  1094. *
  1095. * @param $virtualUrl string
  1096. * @return Array
  1097. */
  1098. public function getFileProps( $virtualUrl ) {
  1099. $path = $this->resolveToStoragePath( $virtualUrl );
  1100. return $this->backend->getFileProps( array( 'src' => $path ) );
  1101. }
  1102. /**
  1103. * Get the timestamp of a file with a given virtual URL/storage path
  1104. *
  1105. * @param $virtualUrl string
  1106. * @return string|false
  1107. */
  1108. public function getFileTimestamp( $virtualUrl ) {
  1109. $path = $this->resolveToStoragePath( $virtualUrl );
  1110. return $this->backend->getFileTimestamp( array( 'src' => $path ) );
  1111. }
  1112. /**
  1113. * Get the sha1 of a file with a given virtual URL/storage path
  1114. *
  1115. * @param $virtualUrl string
  1116. * @return string|false
  1117. */
  1118. public function getFileSha1( $virtualUrl ) {
  1119. $path = $this->resolveToStoragePath( $virtualUrl );
  1120. $tmpFile = $this->backend->getLocalReference( array( 'src' => $path ) );
  1121. if ( !$tmpFile ) {
  1122. return false;
  1123. }
  1124. return $tmpFile->getSha1Base36();
  1125. }
  1126. /**
  1127. * Attempt to stream a file with the given virtual URL/storage path
  1128. *
  1129. * @param $virtualUrl string
  1130. * @param $headers Array Additional HTTP headers to send on success
  1131. * @return bool Success
  1132. */
  1133. public function streamFile( $virtualUrl, $headers = array() ) {
  1134. $path = $this->resolveToStoragePath( $virtualUrl );
  1135. $params = array( 'src' => $path, 'headers' => $headers );
  1136. return $this->backend->streamFile( $params )->isOK();
  1137. }
  1138. /**
  1139. * Call a callback function for every public regular file in the repository.
  1140. * This only acts on the current version of files, not any old versions.
  1141. * May use either the database or the filesystem.
  1142. *
  1143. * @param $callback Array|string
  1144. * @return void
  1145. */
  1146. public function enumFiles( $callback ) {
  1147. $this->enumFilesInStorage( $callback );
  1148. }
  1149. /**
  1150. * Call a callback function for every public file in the repository.
  1151. * May use either the database or the filesystem.
  1152. *
  1153. * @param $callback Array|string
  1154. * @return void
  1155. */
  1156. protected function enumFilesInStorage( $callback ) {
  1157. $publicRoot = $this->getZonePath( 'public' );
  1158. $numDirs = 1 << ( $this->hashLevels * 4 );
  1159. // Use a priori assumptions about directory structure
  1160. // to reduce the tree height of the scanning process.
  1161. for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
  1162. $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
  1163. $path = $publicRoot;
  1164. for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
  1165. $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
  1166. }
  1167. $iterator = $this->backend->getFileList( array( 'dir' => $path ) );
  1168. foreach ( $iterator as $name ) {
  1169. // Each item returned is a public file
  1170. call_user_func( $callback, "{$path}/{$name}" );
  1171. }
  1172. }
  1173. }
  1174. /**
  1175. * Determine if a relative path is valid, i.e. not blank or involving directory traveral
  1176. *
  1177. * @param $filename string
  1178. * @return bool
  1179. */
  1180. public function validateFilename( $filename ) {
  1181. if ( strval( $filename ) == '' ) {
  1182. return false;
  1183. }
  1184. if ( wfIsWindows() ) {
  1185. $filename = strtr( $filename, '\\', '/' );
  1186. }
  1187. /**
  1188. * Use the same traversal protection as Title::secureAndSplit()
  1189. */
  1190. if ( strpos( $filename, '.' ) !== false &&
  1191. ( $filename === '.' || $filename === '..' ||
  1192. strpos( $filename, './' ) === 0 ||
  1193. strpos( $filename, '../' ) === 0 ||
  1194. strpos( $filename, '/./' ) !== false ||
  1195. strpos( $filename, '/../' ) !== false ) )
  1196. {
  1197. return false;
  1198. } else {
  1199. return true;
  1200. }
  1201. }
  1202. /**
  1203. * Get a callback function to use for cleaning error message parameters
  1204. *
  1205. * @return Array
  1206. */
  1207. function getErrorCleanupFunction() {
  1208. switch ( $this->pathDisclosureProtection ) {
  1209. case 'none':
  1210. $callback = array( $this, 'passThrough' );
  1211. break;
  1212. case 'simple':
  1213. $callback = array( $this, 'simpleClean' );
  1214. break;
  1215. default: // 'paranoid'
  1216. $callback = array( $this, 'paranoidClean' );
  1217. }
  1218. return $callback;
  1219. }
  1220. /**
  1221. * Path disclosure protection function
  1222. *
  1223. * @param $param string
  1224. * @return string
  1225. */
  1226. function paranoidClean( $param ) {
  1227. return '[hidden]';
  1228. }
  1229. /**
  1230. * Path disclosure protection function
  1231. *
  1232. * @param $param string
  1233. * @return string
  1234. */
  1235. function simpleClean( $param ) {
  1236. global $IP;
  1237. if ( !isset( $this->simpleCleanPairs ) ) {
  1238. $this->simpleCleanPairs = array(
  1239. $IP => '$IP', // sanity
  1240. );
  1241. }
  1242. return strtr( $param, $this->simpleCleanPairs );
  1243. }
  1244. /**
  1245. * Path disclosure protection function
  1246. *
  1247. * @param $param string
  1248. * @return string
  1249. */
  1250. function passThrough( $param ) {
  1251. return $param;
  1252. }
  1253. /**
  1254. * Create a new fatal error
  1255. *
  1256. * @return FileRepoStatus
  1257. */
  1258. function newFatal( $message /*, parameters...*/ ) {
  1259. $params = func_get_args();
  1260. array_unshift( $params, $this );
  1261. return MWInit::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
  1262. }
  1263. /**
  1264. * Create a new good result
  1265. *
  1266. * @return FileRepoStatus
  1267. */
  1268. function newGood( $value = null ) {
  1269. return FileRepoStatus::newGood( $this, $value );
  1270. }
  1271. /**
  1272. * Delete files in the deleted directory if they are not referenced in the filearchive table
  1273. *
  1274. * STUB
  1275. */
  1276. public function cleanupDeletedBatch( $storageKeys ) {}
  1277. /**
  1278. * Checks if there is a redirect named as $title. If there is, return the
  1279. * title object. If not, return false.
  1280. * STUB
  1281. *
  1282. * @param $title Title of image
  1283. * @return Bool
  1284. */
  1285. public function checkRedirect( Title $title ) {
  1286. return false;
  1287. }
  1288. /**
  1289. * Invalidates image redirect cache related to that image
  1290. * Doesn't do anything for repositories that don't support image redirects.
  1291. *
  1292. * STUB
  1293. * @param $title Title of image
  1294. */
  1295. public function invalidateImageRedirect( Title $title ) {}
  1296. /**
  1297. * Get the human-readable name of the repo
  1298. *
  1299. * @return string
  1300. */
  1301. public function getDisplayName() {
  1302. // We don't name our own repo, return nothing
  1303. if ( $this->isLocal() ) {
  1304. return null;
  1305. }
  1306. // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
  1307. return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
  1308. }
  1309. /**
  1310. * Returns true if this the local file repository.
  1311. *
  1312. * @return bool
  1313. */
  1314. public function isLocal() {
  1315. return $this->getName() == 'local';
  1316. }
  1317. /**
  1318. * Get a key on the primary cache for this repository.
  1319. * Returns false if the repository's cache is not accessible at this site.
  1320. * The parameters are the parts of the key, as for wfMemcKey().
  1321. *
  1322. * STUB
  1323. */
  1324. function getSharedCacheKey( /*...*/ ) {
  1325. return false;
  1326. }
  1327. /**
  1328. * Get a key for this repo in the local cache domain. These cache keys are
  1329. * not shared with remote instances of the repo.
  1330. * The parameters are the parts of the key, as for wfMemcKey().
  1331. *
  1332. * @return string
  1333. */
  1334. function getLocalCacheKey( /*...*/ ) {
  1335. $args = func_get_args();
  1336. array_unshift( $args, 'filerepo', $this->getName() );
  1337. return call_user_func_array( 'wfMemcKey', $args );
  1338. }
  1339. /**
  1340. * Get an UploadStash associated with this repo.
  1341. *
  1342. * @return UploadStash
  1343. */
  1344. public function getUploadStash() {
  1345. return new UploadStash( $this );
  1346. }
  1347. }