/includes/filerepo/file/LocalFile.php

https://bitbucket.org/ghostfreeman/freeside-wiki · PHP · 2561 lines · 1549 code · 339 blank · 673 comment · 188 complexity · cc9f3983c30f93a58e5753c625b88505 MD5 · raw file

  1. <?php
  2. /**
  3. * Local file in the wiki's own database.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. * @ingroup FileAbstraction
  22. */
  23. /**
  24. * Bump this number when serialized cache records may be incompatible.
  25. */
  26. define( 'MW_FILE_VERSION', 8 );
  27. /**
  28. * Class to represent a local file in the wiki's own database
  29. *
  30. * Provides methods to retrieve paths (physical, logical, URL),
  31. * to generate image thumbnails or for uploading.
  32. *
  33. * Note that only the repo object knows what its file class is called. You should
  34. * never name a file class explictly outside of the repo class. Instead use the
  35. * repo's factory functions to generate file objects, for example:
  36. *
  37. * RepoGroup::singleton()->getLocalRepo()->newFile($title);
  38. *
  39. * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
  40. * in most cases.
  41. *
  42. * @ingroup FileAbstraction
  43. */
  44. class LocalFile extends File {
  45. const CACHE_FIELD_MAX_LEN = 1000;
  46. /**#@+
  47. * @private
  48. */
  49. var
  50. $fileExists, # does the file exist on disk? (loadFromXxx)
  51. $historyLine, # Number of line to return by nextHistoryLine() (constructor)
  52. $historyRes, # result of the query for the file's history (nextHistoryLine)
  53. $width, # \
  54. $height, # |
  55. $bits, # --- returned by getimagesize (loadFromXxx)
  56. $attr, # /
  57. $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
  58. $mime, # MIME type, determined by MimeMagic::guessMimeType
  59. $major_mime, # Major mime type
  60. $minor_mime, # Minor mime type
  61. $size, # Size in bytes (loadFromXxx)
  62. $metadata, # Handler-specific metadata
  63. $timestamp, # Upload timestamp
  64. $sha1, # SHA-1 base 36 content hash
  65. $user, $user_text, # User, who uploaded the file
  66. $description, # Description of current revision of the file
  67. $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
  68. $upgraded, # Whether the row was upgraded on load
  69. $locked, # True if the image row is locked
  70. $missing, # True if file is not present in file system. Not to be cached in memcached
  71. $deleted; # Bitfield akin to rev_deleted
  72. /**#@-*/
  73. /**
  74. * @var LocalRepo
  75. */
  76. var $repo;
  77. protected $repoClass = 'LocalRepo';
  78. /**
  79. * Create a LocalFile from a title
  80. * Do not call this except from inside a repo class.
  81. *
  82. * Note: $unused param is only here to avoid an E_STRICT
  83. *
  84. * @param $title
  85. * @param $repo
  86. * @param $unused
  87. *
  88. * @return LocalFile
  89. */
  90. static function newFromTitle( $title, $repo, $unused = null ) {
  91. return new self( $title, $repo );
  92. }
  93. /**
  94. * Create a LocalFile from a title
  95. * Do not call this except from inside a repo class.
  96. *
  97. * @param $row
  98. * @param $repo
  99. *
  100. * @return LocalFile
  101. */
  102. static function newFromRow( $row, $repo ) {
  103. $title = Title::makeTitle( NS_FILE, $row->img_name );
  104. $file = new self( $title, $repo );
  105. $file->loadFromRow( $row );
  106. return $file;
  107. }
  108. /**
  109. * Create a LocalFile from a SHA-1 key
  110. * Do not call this except from inside a repo class.
  111. *
  112. * @param $sha1 string base-36 SHA-1
  113. * @param $repo LocalRepo
  114. * @param string|bool $timestamp MW_timestamp (optional)
  115. *
  116. * @return bool|LocalFile
  117. */
  118. static function newFromKey( $sha1, $repo, $timestamp = false ) {
  119. $dbr = $repo->getSlaveDB();
  120. $conds = array( 'img_sha1' => $sha1 );
  121. if ( $timestamp ) {
  122. $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
  123. }
  124. $row = $dbr->selectRow( 'image', self::selectFields(), $conds, __METHOD__ );
  125. if ( $row ) {
  126. return self::newFromRow( $row, $repo );
  127. } else {
  128. return false;
  129. }
  130. }
  131. /**
  132. * Fields in the image table
  133. * @return array
  134. */
  135. static function selectFields() {
  136. return array(
  137. 'img_name',
  138. 'img_size',
  139. 'img_width',
  140. 'img_height',
  141. 'img_metadata',
  142. 'img_bits',
  143. 'img_media_type',
  144. 'img_major_mime',
  145. 'img_minor_mime',
  146. 'img_description',
  147. 'img_user',
  148. 'img_user_text',
  149. 'img_timestamp',
  150. 'img_sha1',
  151. );
  152. }
  153. /**
  154. * Constructor.
  155. * Do not call this except from inside a repo class.
  156. */
  157. function __construct( $title, $repo ) {
  158. parent::__construct( $title, $repo );
  159. $this->metadata = '';
  160. $this->historyLine = 0;
  161. $this->historyRes = null;
  162. $this->dataLoaded = false;
  163. $this->assertRepoDefined();
  164. $this->assertTitleDefined();
  165. }
  166. /**
  167. * Get the memcached key for the main data for this file, or false if
  168. * there is no access to the shared cache.
  169. * @return bool
  170. */
  171. function getCacheKey() {
  172. $hashedName = md5( $this->getName() );
  173. return $this->repo->getSharedCacheKey( 'file', $hashedName );
  174. }
  175. /**
  176. * Try to load file metadata from memcached. Returns true on success.
  177. * @return bool
  178. */
  179. function loadFromCache() {
  180. global $wgMemc;
  181. wfProfileIn( __METHOD__ );
  182. $this->dataLoaded = false;
  183. $key = $this->getCacheKey();
  184. if ( !$key ) {
  185. wfProfileOut( __METHOD__ );
  186. return false;
  187. }
  188. $cachedValues = $wgMemc->get( $key );
  189. // Check if the key existed and belongs to this version of MediaWiki
  190. if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION ) ) {
  191. wfDebug( "Pulling file metadata from cache key $key\n" );
  192. $this->fileExists = $cachedValues['fileExists'];
  193. if ( $this->fileExists ) {
  194. $this->setProps( $cachedValues );
  195. }
  196. $this->dataLoaded = true;
  197. }
  198. if ( $this->dataLoaded ) {
  199. wfIncrStats( 'image_cache_hit' );
  200. } else {
  201. wfIncrStats( 'image_cache_miss' );
  202. }
  203. wfProfileOut( __METHOD__ );
  204. return $this->dataLoaded;
  205. }
  206. /**
  207. * Save the file metadata to memcached
  208. */
  209. function saveToCache() {
  210. global $wgMemc;
  211. $this->load();
  212. $key = $this->getCacheKey();
  213. if ( !$key ) {
  214. return;
  215. }
  216. $fields = $this->getCacheFields( '' );
  217. $cache = array( 'version' => MW_FILE_VERSION );
  218. $cache['fileExists'] = $this->fileExists;
  219. if ( $this->fileExists ) {
  220. foreach ( $fields as $field ) {
  221. $cache[$field] = $this->$field;
  222. }
  223. }
  224. $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
  225. }
  226. /**
  227. * Load metadata from the file itself
  228. */
  229. function loadFromFile() {
  230. $props = $this->repo->getFileProps( $this->getVirtualUrl() );
  231. $this->setProps( $props );
  232. }
  233. /**
  234. * @param $prefix string
  235. * @return array
  236. */
  237. function getCacheFields( $prefix = 'img_' ) {
  238. static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
  239. 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
  240. static $results = array();
  241. if ( $prefix == '' ) {
  242. return $fields;
  243. }
  244. if ( !isset( $results[$prefix] ) ) {
  245. $prefixedFields = array();
  246. foreach ( $fields as $field ) {
  247. $prefixedFields[] = $prefix . $field;
  248. }
  249. $results[$prefix] = $prefixedFields;
  250. }
  251. return $results[$prefix];
  252. }
  253. /**
  254. * Load file metadata from the DB
  255. */
  256. function loadFromDB() {
  257. # Polymorphic function name to distinguish foreign and local fetches
  258. $fname = get_class( $this ) . '::' . __FUNCTION__;
  259. wfProfileIn( $fname );
  260. # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
  261. $this->dataLoaded = true;
  262. $dbr = $this->repo->getMasterDB();
  263. $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
  264. array( 'img_name' => $this->getName() ), $fname );
  265. if ( $row ) {
  266. $this->loadFromRow( $row );
  267. } else {
  268. $this->fileExists = false;
  269. }
  270. wfProfileOut( $fname );
  271. }
  272. /**
  273. * Decode a row from the database (either object or array) to an array
  274. * with timestamps and MIME types decoded, and the field prefix removed.
  275. * @param $row
  276. * @param $prefix string
  277. * @throws MWException
  278. * @return array
  279. */
  280. function decodeRow( $row, $prefix = 'img_' ) {
  281. $array = (array)$row;
  282. $prefixLength = strlen( $prefix );
  283. // Sanity check prefix once
  284. if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
  285. throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
  286. }
  287. $decoded = array();
  288. foreach ( $array as $name => $value ) {
  289. $decoded[substr( $name, $prefixLength )] = $value;
  290. }
  291. $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
  292. if ( empty( $decoded['major_mime'] ) ) {
  293. $decoded['mime'] = 'unknown/unknown';
  294. } else {
  295. if ( !$decoded['minor_mime'] ) {
  296. $decoded['minor_mime'] = 'unknown';
  297. }
  298. $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
  299. }
  300. # Trim zero padding from char/binary field
  301. $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
  302. return $decoded;
  303. }
  304. /**
  305. * Load file metadata from a DB result row
  306. */
  307. function loadFromRow( $row, $prefix = 'img_' ) {
  308. $this->dataLoaded = true;
  309. $array = $this->decodeRow( $row, $prefix );
  310. foreach ( $array as $name => $value ) {
  311. $this->$name = $value;
  312. }
  313. $this->fileExists = true;
  314. $this->maybeUpgradeRow();
  315. }
  316. /**
  317. * Load file metadata from cache or DB, unless already loaded
  318. */
  319. function load() {
  320. if ( !$this->dataLoaded ) {
  321. if ( !$this->loadFromCache() ) {
  322. $this->loadFromDB();
  323. $this->saveToCache();
  324. }
  325. $this->dataLoaded = true;
  326. }
  327. }
  328. /**
  329. * Upgrade a row if it needs it
  330. */
  331. function maybeUpgradeRow() {
  332. global $wgUpdateCompatibleMetadata;
  333. if ( wfReadOnly() ) {
  334. return;
  335. }
  336. if ( is_null( $this->media_type ) ||
  337. $this->mime == 'image/svg'
  338. ) {
  339. $this->upgradeRow();
  340. $this->upgraded = true;
  341. } else {
  342. $handler = $this->getHandler();
  343. if ( $handler ) {
  344. $validity = $handler->isMetadataValid( $this, $this->metadata );
  345. if ( $validity === MediaHandler::METADATA_BAD
  346. || ( $validity === MediaHandler::METADATA_COMPATIBLE && $wgUpdateCompatibleMetadata )
  347. ) {
  348. $this->upgradeRow();
  349. $this->upgraded = true;
  350. }
  351. }
  352. }
  353. }
  354. function getUpgraded() {
  355. return $this->upgraded;
  356. }
  357. /**
  358. * Fix assorted version-related problems with the image row by reloading it from the file
  359. */
  360. function upgradeRow() {
  361. wfProfileIn( __METHOD__ );
  362. $this->lock(); // begin
  363. $this->loadFromFile();
  364. # Don't destroy file info of missing files
  365. if ( !$this->fileExists ) {
  366. wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
  367. wfProfileOut( __METHOD__ );
  368. return;
  369. }
  370. $dbw = $this->repo->getMasterDB();
  371. list( $major, $minor ) = self::splitMime( $this->mime );
  372. if ( wfReadOnly() ) {
  373. wfProfileOut( __METHOD__ );
  374. return;
  375. }
  376. wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
  377. $dbw->update( 'image',
  378. array(
  379. 'img_size' => $this->size, // sanity
  380. 'img_width' => $this->width,
  381. 'img_height' => $this->height,
  382. 'img_bits' => $this->bits,
  383. 'img_media_type' => $this->media_type,
  384. 'img_major_mime' => $major,
  385. 'img_minor_mime' => $minor,
  386. 'img_metadata' => $this->metadata,
  387. 'img_sha1' => $this->sha1,
  388. ),
  389. array( 'img_name' => $this->getName() ),
  390. __METHOD__
  391. );
  392. $this->saveToCache();
  393. $this->unlock(); // done
  394. wfProfileOut( __METHOD__ );
  395. }
  396. /**
  397. * Set properties in this object to be equal to those given in the
  398. * associative array $info. Only cacheable fields can be set.
  399. *
  400. * If 'mime' is given, it will be split into major_mime/minor_mime.
  401. * If major_mime/minor_mime are given, $this->mime will also be set.
  402. */
  403. function setProps( $info ) {
  404. $this->dataLoaded = true;
  405. $fields = $this->getCacheFields( '' );
  406. $fields[] = 'fileExists';
  407. foreach ( $fields as $field ) {
  408. if ( isset( $info[$field] ) ) {
  409. $this->$field = $info[$field];
  410. }
  411. }
  412. // Fix up mime fields
  413. if ( isset( $info['major_mime'] ) ) {
  414. $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
  415. } elseif ( isset( $info['mime'] ) ) {
  416. $this->mime = $info['mime'];
  417. list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
  418. }
  419. }
  420. /** splitMime inherited */
  421. /** getName inherited */
  422. /** getTitle inherited */
  423. /** getURL inherited */
  424. /** getViewURL inherited */
  425. /** getPath inherited */
  426. /** isVisible inhereted */
  427. /**
  428. * @return bool
  429. */
  430. function isMissing() {
  431. if ( $this->missing === null ) {
  432. list( $fileExists ) = $this->repo->fileExists( $this->getVirtualUrl() );
  433. $this->missing = !$fileExists;
  434. }
  435. return $this->missing;
  436. }
  437. /**
  438. * Return the width of the image
  439. *
  440. * @param $page int
  441. * @return bool|int Returns false on error
  442. */
  443. public function getWidth( $page = 1 ) {
  444. $this->load();
  445. if ( $this->isMultipage() ) {
  446. $dim = $this->getHandler()->getPageDimensions( $this, $page );
  447. if ( $dim ) {
  448. return $dim['width'];
  449. } else {
  450. return false;
  451. }
  452. } else {
  453. return $this->width;
  454. }
  455. }
  456. /**
  457. * Return the height of the image
  458. *
  459. * @param $page int
  460. * @return bool|int Returns false on error
  461. */
  462. public function getHeight( $page = 1 ) {
  463. $this->load();
  464. if ( $this->isMultipage() ) {
  465. $dim = $this->getHandler()->getPageDimensions( $this, $page );
  466. if ( $dim ) {
  467. return $dim['height'];
  468. } else {
  469. return false;
  470. }
  471. } else {
  472. return $this->height;
  473. }
  474. }
  475. /**
  476. * Returns ID or name of user who uploaded the file
  477. *
  478. * @param $type string 'text' or 'id'
  479. * @return int|string
  480. */
  481. function getUser( $type = 'text' ) {
  482. $this->load();
  483. if ( $type == 'text' ) {
  484. return $this->user_text;
  485. } elseif ( $type == 'id' ) {
  486. return $this->user;
  487. }
  488. }
  489. /**
  490. * Get handler-specific metadata
  491. * @return string
  492. */
  493. function getMetadata() {
  494. $this->load();
  495. return $this->metadata;
  496. }
  497. /**
  498. * @return int
  499. */
  500. function getBitDepth() {
  501. $this->load();
  502. return $this->bits;
  503. }
  504. /**
  505. * Return the size of the image file, in bytes
  506. * @return int
  507. */
  508. public function getSize() {
  509. $this->load();
  510. return $this->size;
  511. }
  512. /**
  513. * Returns the mime type of the file.
  514. * @return string
  515. */
  516. function getMimeType() {
  517. $this->load();
  518. return $this->mime;
  519. }
  520. /**
  521. * Return the type of the media in the file.
  522. * Use the value returned by this function with the MEDIATYPE_xxx constants.
  523. * @return string
  524. */
  525. function getMediaType() {
  526. $this->load();
  527. return $this->media_type;
  528. }
  529. /** canRender inherited */
  530. /** mustRender inherited */
  531. /** allowInlineDisplay inherited */
  532. /** isSafeFile inherited */
  533. /** isTrustedFile inherited */
  534. /**
  535. * Returns true if the file exists on disk.
  536. * @return boolean Whether file exist on disk.
  537. */
  538. public function exists() {
  539. $this->load();
  540. return $this->fileExists;
  541. }
  542. /** getTransformScript inherited */
  543. /** getUnscaledThumb inherited */
  544. /** thumbName inherited */
  545. /** createThumb inherited */
  546. /** transform inherited */
  547. /**
  548. * Fix thumbnail files from 1.4 or before, with extreme prejudice
  549. * @todo : do we still care about this? Perhaps a maintenance script
  550. * can be made instead. Enabling this code results in a serious
  551. * RTT regression for wikis without 404 handling.
  552. */
  553. function migrateThumbFile( $thumbName ) {
  554. $thumbDir = $this->getThumbPath();
  555. /* Old code for bug 2532
  556. $thumbPath = "$thumbDir/$thumbName";
  557. if ( is_dir( $thumbPath ) ) {
  558. // Directory where file should be
  559. // This happened occasionally due to broken migration code in 1.5
  560. // Rename to broken-*
  561. for ( $i = 0; $i < 100 ; $i++ ) {
  562. $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
  563. if ( !file_exists( $broken ) ) {
  564. rename( $thumbPath, $broken );
  565. break;
  566. }
  567. }
  568. // Doesn't exist anymore
  569. clearstatcache();
  570. }
  571. */
  572. /*
  573. if ( $this->repo->fileExists( $thumbDir ) ) {
  574. // Delete file where directory should be
  575. $this->repo->cleanupBatch( array( $thumbDir ) );
  576. }
  577. */
  578. }
  579. /** getHandler inherited */
  580. /** iconThumb inherited */
  581. /** getLastError inherited */
  582. /**
  583. * Get all thumbnail names previously generated for this file
  584. * @param $archiveName string|bool Name of an archive file, default false
  585. * @return array first element is the base dir, then files in that base dir.
  586. */
  587. function getThumbnails( $archiveName = false ) {
  588. if ( $archiveName ) {
  589. $dir = $this->getArchiveThumbPath( $archiveName );
  590. } else {
  591. $dir = $this->getThumbPath();
  592. }
  593. $backend = $this->repo->getBackend();
  594. $files = array( $dir );
  595. $iterator = $backend->getFileList( array( 'dir' => $dir ) );
  596. foreach ( $iterator as $file ) {
  597. $files[] = $file;
  598. }
  599. return $files;
  600. }
  601. /**
  602. * Refresh metadata in memcached, but don't touch thumbnails or squid
  603. */
  604. function purgeMetadataCache() {
  605. $this->loadFromDB();
  606. $this->saveToCache();
  607. $this->purgeHistory();
  608. }
  609. /**
  610. * Purge the shared history (OldLocalFile) cache
  611. */
  612. function purgeHistory() {
  613. global $wgMemc;
  614. $hashedName = md5( $this->getName() );
  615. $oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
  616. // Must purge thumbnails for old versions too! bug 30192
  617. foreach( $this->getHistory() as $oldFile ) {
  618. $oldFile->purgeThumbnails();
  619. }
  620. if ( $oldKey ) {
  621. $wgMemc->delete( $oldKey );
  622. }
  623. }
  624. /**
  625. * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
  626. */
  627. function purgeCache( $options = array() ) {
  628. // Refresh metadata cache
  629. $this->purgeMetadataCache();
  630. // Delete thumbnails
  631. $this->purgeThumbnails( $options );
  632. // Purge squid cache for this file
  633. SquidUpdate::purge( array( $this->getURL() ) );
  634. }
  635. /**
  636. * Delete cached transformed files for an archived version only.
  637. * @param $archiveName string name of the archived file
  638. */
  639. function purgeOldThumbnails( $archiveName ) {
  640. global $wgUseSquid;
  641. wfProfileIn( __METHOD__ );
  642. // Get a list of old thumbnails and URLs
  643. $files = $this->getThumbnails( $archiveName );
  644. $dir = array_shift( $files );
  645. $this->purgeThumbList( $dir, $files );
  646. // Purge any custom thumbnail caches
  647. wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
  648. // Purge the squid
  649. if ( $wgUseSquid ) {
  650. $urls = array();
  651. foreach( $files as $file ) {
  652. $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
  653. }
  654. SquidUpdate::purge( $urls );
  655. }
  656. wfProfileOut( __METHOD__ );
  657. }
  658. /**
  659. * Delete cached transformed files for the current version only.
  660. */
  661. function purgeThumbnails( $options = array() ) {
  662. global $wgUseSquid;
  663. wfProfileIn( __METHOD__ );
  664. // Delete thumbnails
  665. $files = $this->getThumbnails();
  666. // Give media handler a chance to filter the purge list
  667. if ( !empty( $options['forThumbRefresh'] ) ) {
  668. $handler = $this->getHandler();
  669. if ( $handler ) {
  670. $handler->filterThumbnailPurgeList( $files, $options );
  671. }
  672. }
  673. $dir = array_shift( $files );
  674. $this->purgeThumbList( $dir, $files );
  675. // Purge any custom thumbnail caches
  676. wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
  677. // Purge the squid
  678. if ( $wgUseSquid ) {
  679. $urls = array();
  680. foreach( $files as $file ) {
  681. $urls[] = $this->getThumbUrl( $file );
  682. }
  683. SquidUpdate::purge( $urls );
  684. }
  685. wfProfileOut( __METHOD__ );
  686. }
  687. /**
  688. * Delete a list of thumbnails visible at urls
  689. * @param $dir string base dir of the files.
  690. * @param $files array of strings: relative filenames (to $dir)
  691. */
  692. protected function purgeThumbList( $dir, $files ) {
  693. $fileListDebug = strtr(
  694. var_export( $files, true ),
  695. array("\n"=>'')
  696. );
  697. wfDebug( __METHOD__ . ": $fileListDebug\n" );
  698. $purgeList = array();
  699. foreach ( $files as $file ) {
  700. # Check that the base file name is part of the thumb name
  701. # This is a basic sanity check to avoid erasing unrelated directories
  702. if ( strpos( $file, $this->getName() ) !== false ) {
  703. $purgeList[] = "{$dir}/{$file}";
  704. }
  705. }
  706. # Delete the thumbnails
  707. $this->repo->quickPurgeBatch( $purgeList );
  708. # Clear out the thumbnail directory if empty
  709. $this->repo->quickCleanDir( $dir );
  710. }
  711. /** purgeDescription inherited */
  712. /** purgeEverything inherited */
  713. /**
  714. * @param $limit null
  715. * @param $start null
  716. * @param $end null
  717. * @param $inc bool
  718. * @return array
  719. */
  720. function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
  721. $dbr = $this->repo->getSlaveDB();
  722. $tables = array( 'oldimage' );
  723. $fields = OldLocalFile::selectFields();
  724. $conds = $opts = $join_conds = array();
  725. $eq = $inc ? '=' : '';
  726. $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
  727. if ( $start ) {
  728. $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
  729. }
  730. if ( $end ) {
  731. $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
  732. }
  733. if ( $limit ) {
  734. $opts['LIMIT'] = $limit;
  735. }
  736. // Search backwards for time > x queries
  737. $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
  738. $opts['ORDER BY'] = "oi_timestamp $order";
  739. $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
  740. wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
  741. &$conds, &$opts, &$join_conds ) );
  742. $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
  743. $r = array();
  744. foreach ( $res as $row ) {
  745. if ( $this->repo->oldFileFromRowFactory ) {
  746. $r[] = call_user_func( $this->repo->oldFileFromRowFactory, $row, $this->repo );
  747. } else {
  748. $r[] = OldLocalFile::newFromRow( $row, $this->repo );
  749. }
  750. }
  751. if ( $order == 'ASC' ) {
  752. $r = array_reverse( $r ); // make sure it ends up descending
  753. }
  754. return $r;
  755. }
  756. /**
  757. * Return the history of this file, line by line.
  758. * starts with current version, then old versions.
  759. * uses $this->historyLine to check which line to return:
  760. * 0 return line for current version
  761. * 1 query for old versions, return first one
  762. * 2, ... return next old version from above query
  763. * @return bool
  764. */
  765. public function nextHistoryLine() {
  766. # Polymorphic function name to distinguish foreign and local fetches
  767. $fname = get_class( $this ) . '::' . __FUNCTION__;
  768. $dbr = $this->repo->getSlaveDB();
  769. if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
  770. $this->historyRes = $dbr->select( 'image',
  771. array(
  772. '*',
  773. "'' AS oi_archive_name",
  774. '0 as oi_deleted',
  775. 'img_sha1'
  776. ),
  777. array( 'img_name' => $this->title->getDBkey() ),
  778. $fname
  779. );
  780. if ( 0 == $dbr->numRows( $this->historyRes ) ) {
  781. $this->historyRes = null;
  782. return false;
  783. }
  784. } elseif ( $this->historyLine == 1 ) {
  785. $this->historyRes = $dbr->select( 'oldimage', '*',
  786. array( 'oi_name' => $this->title->getDBkey() ),
  787. $fname,
  788. array( 'ORDER BY' => 'oi_timestamp DESC' )
  789. );
  790. }
  791. $this->historyLine ++;
  792. return $dbr->fetchObject( $this->historyRes );
  793. }
  794. /**
  795. * Reset the history pointer to the first element of the history
  796. */
  797. public function resetHistory() {
  798. $this->historyLine = 0;
  799. if ( !is_null( $this->historyRes ) ) {
  800. $this->historyRes = null;
  801. }
  802. }
  803. /** getHashPath inherited */
  804. /** getRel inherited */
  805. /** getUrlRel inherited */
  806. /** getArchiveRel inherited */
  807. /** getArchivePath inherited */
  808. /** getThumbPath inherited */
  809. /** getArchiveUrl inherited */
  810. /** getThumbUrl inherited */
  811. /** getArchiveVirtualUrl inherited */
  812. /** getThumbVirtualUrl inherited */
  813. /** isHashed inherited */
  814. /**
  815. * Upload a file and record it in the DB
  816. * @param $srcPath String: source storage path or virtual URL
  817. * @param $comment String: upload description
  818. * @param $pageText String: text to use for the new description page,
  819. * if a new description page is created
  820. * @param $flags Integer|bool: flags for publish()
  821. * @param $props Array|bool: File properties, if known. This can be used to reduce the
  822. * upload time when uploading virtual URLs for which the file info
  823. * is already known
  824. * @param $timestamp String|bool: timestamp for img_timestamp, or false to use the current time
  825. * @param $user User|null: User object or null to use $wgUser
  826. *
  827. * @return FileRepoStatus object. On success, the value member contains the
  828. * archive name, or an empty string if it was a new file.
  829. */
  830. function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
  831. global $wgContLang;
  832. if ( $this->getRepo()->getReadOnlyReason() !== false ) {
  833. return $this->readOnlyFatalStatus();
  834. }
  835. // truncate nicely or the DB will do it for us
  836. // non-nicely (dangling multi-byte chars, non-truncated version in cache).
  837. $comment = $wgContLang->truncate( $comment, 255 );
  838. $this->lock(); // begin
  839. $status = $this->publish( $srcPath, $flags );
  840. if ( $status->successCount > 0 ) {
  841. # Essentially we are displacing any existing current file and saving
  842. # a new current file at the old location. If just the first succeeded,
  843. # we still need to displace the current DB entry and put in a new one.
  844. if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
  845. $status->fatal( 'filenotfound', $srcPath );
  846. }
  847. }
  848. $this->unlock(); // done
  849. return $status;
  850. }
  851. /**
  852. * Record a file upload in the upload log and the image table
  853. * @param $oldver
  854. * @param $desc string
  855. * @param $license string
  856. * @param $copyStatus string
  857. * @param $source string
  858. * @param $watch bool
  859. * @param $timestamp string|bool
  860. * @return bool
  861. */
  862. function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
  863. $watch = false, $timestamp = false )
  864. {
  865. $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
  866. if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
  867. return false;
  868. }
  869. if ( $watch ) {
  870. global $wgUser;
  871. $wgUser->addWatch( $this->getTitle() );
  872. }
  873. return true;
  874. }
  875. /**
  876. * Record a file upload in the upload log and the image table
  877. * @param $oldver
  878. * @param $comment string
  879. * @param $pageText string
  880. * @param $props bool|array
  881. * @param $timestamp bool|string
  882. * @param $user null|User
  883. * @return bool
  884. */
  885. function recordUpload2(
  886. $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
  887. ) {
  888. wfProfileIn( __METHOD__ );
  889. if ( is_null( $user ) ) {
  890. global $wgUser;
  891. $user = $wgUser;
  892. }
  893. $dbw = $this->repo->getMasterDB();
  894. $dbw->begin( __METHOD__ );
  895. if ( !$props ) {
  896. wfProfileIn( __METHOD__ . '-getProps' );
  897. $props = $this->repo->getFileProps( $this->getVirtualUrl() );
  898. wfProfileOut( __METHOD__ . '-getProps' );
  899. }
  900. if ( $timestamp === false ) {
  901. $timestamp = $dbw->timestamp();
  902. }
  903. $props['description'] = $comment;
  904. $props['user'] = $user->getId();
  905. $props['user_text'] = $user->getName();
  906. $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
  907. $this->setProps( $props );
  908. # Fail now if the file isn't there
  909. if ( !$this->fileExists ) {
  910. wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!\n" );
  911. wfProfileOut( __METHOD__ );
  912. return false;
  913. }
  914. $reupload = false;
  915. # Test to see if the row exists using INSERT IGNORE
  916. # This avoids race conditions by locking the row until the commit, and also
  917. # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
  918. $dbw->insert( 'image',
  919. array(
  920. 'img_name' => $this->getName(),
  921. 'img_size' => $this->size,
  922. 'img_width' => intval( $this->width ),
  923. 'img_height' => intval( $this->height ),
  924. 'img_bits' => $this->bits,
  925. 'img_media_type' => $this->media_type,
  926. 'img_major_mime' => $this->major_mime,
  927. 'img_minor_mime' => $this->minor_mime,
  928. 'img_timestamp' => $timestamp,
  929. 'img_description' => $comment,
  930. 'img_user' => $user->getId(),
  931. 'img_user_text' => $user->getName(),
  932. 'img_metadata' => $this->metadata,
  933. 'img_sha1' => $this->sha1
  934. ),
  935. __METHOD__,
  936. 'IGNORE'
  937. );
  938. if ( $dbw->affectedRows() == 0 ) {
  939. # (bug 34993) Note: $oldver can be empty here, if the previous
  940. # version of the file was broken. Allow registration of the new
  941. # version to continue anyway, because that's better than having
  942. # an image that's not fixable by user operations.
  943. $reupload = true;
  944. # Collision, this is an update of a file
  945. # Insert previous contents into oldimage
  946. $dbw->insertSelect( 'oldimage', 'image',
  947. array(
  948. 'oi_name' => 'img_name',
  949. 'oi_archive_name' => $dbw->addQuotes( $oldver ),
  950. 'oi_size' => 'img_size',
  951. 'oi_width' => 'img_width',
  952. 'oi_height' => 'img_height',
  953. 'oi_bits' => 'img_bits',
  954. 'oi_timestamp' => 'img_timestamp',
  955. 'oi_description' => 'img_description',
  956. 'oi_user' => 'img_user',
  957. 'oi_user_text' => 'img_user_text',
  958. 'oi_metadata' => 'img_metadata',
  959. 'oi_media_type' => 'img_media_type',
  960. 'oi_major_mime' => 'img_major_mime',
  961. 'oi_minor_mime' => 'img_minor_mime',
  962. 'oi_sha1' => 'img_sha1'
  963. ),
  964. array( 'img_name' => $this->getName() ),
  965. __METHOD__
  966. );
  967. # Update the current image row
  968. $dbw->update( 'image',
  969. array( /* SET */
  970. 'img_size' => $this->size,
  971. 'img_width' => intval( $this->width ),
  972. 'img_height' => intval( $this->height ),
  973. 'img_bits' => $this->bits,
  974. 'img_media_type' => $this->media_type,
  975. 'img_major_mime' => $this->major_mime,
  976. 'img_minor_mime' => $this->minor_mime,
  977. 'img_timestamp' => $timestamp,
  978. 'img_description' => $comment,
  979. 'img_user' => $user->getId(),
  980. 'img_user_text' => $user->getName(),
  981. 'img_metadata' => $this->metadata,
  982. 'img_sha1' => $this->sha1
  983. ),
  984. array( 'img_name' => $this->getName() ),
  985. __METHOD__
  986. );
  987. } else {
  988. # This is a new file, so update the image count
  989. DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
  990. }
  991. $descTitle = $this->getTitle();
  992. $wikiPage = new WikiFilePage( $descTitle );
  993. $wikiPage->setFile( $this );
  994. # Add the log entry
  995. $log = new LogPage( 'upload' );
  996. $action = $reupload ? 'overwrite' : 'upload';
  997. $logId = $log->addEntry( $action, $descTitle, $comment, array(), $user );
  998. wfProfileIn( __METHOD__ . '-edit' );
  999. $exists = $descTitle->exists();
  1000. if ( $exists ) {
  1001. # Create a null revision
  1002. $latest = $descTitle->getLatestRevID();
  1003. $nullRevision = Revision::newNullRevision(
  1004. $dbw,
  1005. $descTitle->getArticleID(),
  1006. $log->getRcComment(),
  1007. false
  1008. );
  1009. if (!is_null($nullRevision)) {
  1010. $nullRevision->insertOn( $dbw );
  1011. wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
  1012. $wikiPage->updateRevisionOn( $dbw, $nullRevision );
  1013. }
  1014. }
  1015. # Commit the transaction now, in case something goes wrong later
  1016. # The most important thing is that files don't get lost, especially archives
  1017. # NOTE: once we have support for nested transactions, the commit may be moved
  1018. # to after $wikiPage->doEdit has been called.
  1019. $dbw->commit( __METHOD__ );
  1020. if ( $exists ) {
  1021. # Invalidate the cache for the description page
  1022. $descTitle->invalidateCache();
  1023. $descTitle->purgeSquid();
  1024. } else {
  1025. # New file; create the description page.
  1026. # There's already a log entry, so don't make a second RC entry
  1027. # Squid and file cache for the description page are purged by doEdit.
  1028. $status = $wikiPage->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC, false, $user );
  1029. if ( isset( $status->value['revision'] ) ) { // XXX; doEdit() uses a transaction
  1030. $dbw->begin();
  1031. $dbw->update( 'logging',
  1032. array( 'log_page' => $status->value['revision']->getPage() ),
  1033. array( 'log_id' => $logId ),
  1034. __METHOD__
  1035. );
  1036. $dbw->commit(); // commit before anything bad can happen
  1037. }
  1038. }
  1039. wfProfileOut( __METHOD__ . '-edit' );
  1040. # Save to cache and purge the squid
  1041. # We shall not saveToCache before the commit since otherwise
  1042. # in case of a rollback there is an usable file from memcached
  1043. # which in fact doesn't really exist (bug 24978)
  1044. $this->saveToCache();
  1045. if ( $reupload ) {
  1046. # Delete old thumbnails
  1047. wfProfileIn( __METHOD__ . '-purge' );
  1048. $this->purgeThumbnails();
  1049. wfProfileOut( __METHOD__ . '-purge' );
  1050. # Remove the old file from the squid cache
  1051. SquidUpdate::purge( array( $this->getURL() ) );
  1052. }
  1053. # Hooks, hooks, the magic of hooks...
  1054. wfProfileIn( __METHOD__ . '-hooks' );
  1055. wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
  1056. wfProfileOut( __METHOD__ . '-hooks' );
  1057. # Invalidate cache for all pages using this file
  1058. $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
  1059. $update->doUpdate();
  1060. # Invalidate cache for all pages that redirects on this page
  1061. $redirs = $this->getTitle()->getRedirectsHere();
  1062. foreach ( $redirs as $redir ) {
  1063. $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
  1064. $update->doUpdate();
  1065. }
  1066. wfProfileOut( __METHOD__ );
  1067. return true;
  1068. }
  1069. /**
  1070. * Move or copy a file to its public location. If a file exists at the
  1071. * destination, move it to an archive. Returns a FileRepoStatus object with
  1072. * the archive name in the "value" member on success.
  1073. *
  1074. * The archive name should be passed through to recordUpload for database
  1075. * registration.
  1076. *
  1077. * @param $srcPath String: local filesystem path to the source image
  1078. * @param $flags Integer: a bitwise combination of:
  1079. * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
  1080. * @return FileRepoStatus object. On success, the value member contains the
  1081. * archive name, or an empty string if it was a new file.
  1082. */
  1083. function publish( $srcPath, $flags = 0 ) {
  1084. return $this->publishTo( $srcPath, $this->getRel(), $flags );
  1085. }
  1086. /**
  1087. * Move or copy a file to a specified location. Returns a FileRepoStatus
  1088. * object with the archive name in the "value" member on success.
  1089. *
  1090. * The archive name should be passed through to recordUpload for database
  1091. * registration.
  1092. *
  1093. * @param $srcPath String: local filesystem path to the source image
  1094. * @param $dstRel String: target relative path
  1095. * @param $flags Integer: a bitwise combination of:
  1096. * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
  1097. * @return FileRepoStatus object. On success, the value member contains the
  1098. * archive name, or an empty string if it was a new file.
  1099. */
  1100. function publishTo( $srcPath, $dstRel, $flags = 0 ) {
  1101. if ( $this->getRepo()->getReadOnlyReason() !== false ) {
  1102. return $this->readOnlyFatalStatus();
  1103. }
  1104. $this->lock(); // begin
  1105. $archiveName = wfTimestamp( TS_MW ) . '!'. $this->getName();
  1106. $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
  1107. $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
  1108. $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags );
  1109. if ( $status->value == 'new' ) {
  1110. $status->value = '';
  1111. } else {
  1112. $status->value = $archiveName;
  1113. }
  1114. $this->unlock(); // done
  1115. return $status;
  1116. }
  1117. /** getLinksTo inherited */
  1118. /** getExifData inherited */
  1119. /** isLocal inherited */
  1120. /** wasDeleted inherited */
  1121. /**
  1122. * Move file to the new title
  1123. *
  1124. * Move current, old version and all thumbnails
  1125. * to the new filename. Old file is deleted.
  1126. *
  1127. * Cache purging is done; checks for validity
  1128. * and logging are caller's responsibility
  1129. *
  1130. * @param $target Title New file name
  1131. * @return FileRepoStatus object.
  1132. */
  1133. function move( $target ) {
  1134. if ( $this->getRepo()->getReadOnlyReason() !== false ) {
  1135. return $this->readOnlyFatalStatus();
  1136. }
  1137. wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
  1138. $batch = new LocalFileMoveBatch( $this, $target );
  1139. $this->lock(); // begin
  1140. $batch->addCurrent();
  1141. $archiveNames = $batch->addOlds();
  1142. $status = $batch->execute();
  1143. $this->unlock(); // done
  1144. wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
  1145. $this->purgeEverything();
  1146. foreach ( $archiveNames as $archiveName ) {
  1147. $this->purgeOldThumbnails( $archiveName );
  1148. }
  1149. if ( $status->isOK() ) {
  1150. // Now switch the object
  1151. $this->title = $target;
  1152. // Force regeneration of the name and hashpath
  1153. unset( $this->name );
  1154. unset( $this->hashPath );
  1155. // Purge the new image
  1156. $this->purgeEverything();
  1157. }
  1158. return $status;
  1159. }
  1160. /**
  1161. * Delete all versions of the file.
  1162. *
  1163. * Moves the files into an archive directory (or deletes them)
  1164. * and removes the database rows.
  1165. *
  1166. * Cache purging is done; logging is caller's responsibility.
  1167. *
  1168. * @param $reason
  1169. * @param $suppress
  1170. * @return FileRepoStatus object.
  1171. */
  1172. function delete( $reason, $suppress = false ) {
  1173. if ( $this->getRepo()->getReadOnlyReason() !== false ) {
  1174. return $this->readOnlyFatalStatus();
  1175. }
  1176. $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
  1177. $this->lock(); // begin
  1178. $batch->addCurrent();
  1179. # Get old version relative paths
  1180. $archiveNames = $batch->addOlds();
  1181. $status = $batch->execute();
  1182. $this->unlock(); // done
  1183. if ( $status->isOK() ) {
  1184. DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => -1 ) ) );
  1185. }
  1186. $this->purgeEverything();
  1187. foreach ( $archiveNames as $archiveName ) {
  1188. $this->purgeOldThumbnails( $archiveName );
  1189. }
  1190. return $status;
  1191. }
  1192. /**
  1193. * Delete an old version of the file.
  1194. *
  1195. * Moves the file into an archive directory (or deletes it)
  1196. * and removes the database row.
  1197. *
  1198. * Cache purging is done; logging is caller's responsibility.
  1199. *
  1200. * @param $archiveName String
  1201. * @param $reason String
  1202. * @param $suppress Boolean
  1203. * @throws MWException or FSException on database or file store failure
  1204. * @return FileRepoStatus object.
  1205. */
  1206. function deleteOld( $archiveName, $reason, $suppress = false ) {
  1207. if ( $this->getRepo()->getReadOnlyReason() !== false ) {
  1208. return $this->readOnlyFatalStatus();
  1209. }
  1210. $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
  1211. $this->lock(); // begin
  1212. $batch->addOld( $archiveName );
  1213. $status = $batch->execute();
  1214. $this->unlock(); // done
  1215. $this->purgeOldThumbnails( $archiveName );
  1216. if ( $status->isOK() ) {
  1217. $this->purgeDescription();
  1218. $this->purgeHistory();
  1219. }
  1220. return $status;
  1221. }
  1222. /**
  1223. * Restore all or specified deleted revisions to the given file.
  1224. * Permissions and logging are left to the caller.
  1225. *
  1226. * May throw database exceptions on error.
  1227. *
  1228. * @param $versions array set of record ids of deleted items to restore,
  1229. * or empty to restore all revisions.
  1230. * @param $unsuppress Boolean
  1231. * @return FileRepoStatus
  1232. */
  1233. function restore( $versions = array(), $unsuppress = false ) {
  1234. if ( $this->getRepo()->getReadOnlyReason() !== false ) {
  1235. return $this->readOnlyFatalStatus();
  1236. }
  1237. $batch = new LocalFileRestoreBatch( $this, $unsuppress );
  1238. $this->lock(); // begin
  1239. if ( !$versions ) {
  1240. $batch->addAll();
  1241. } else {
  1242. $batch->addIds( $versions );
  1243. }
  1244. $status = $batch->execute();
  1245. if ( $status->isGood() ) {
  1246. $cleanupStatus = $batch->cleanup();
  1247. $cleanupStatus->successCount = 0;
  1248. $cleanupStatus->failCount = 0;
  1249. $status->merge( $cleanupStatus );
  1250. }
  1251. $this->unlock(); // done
  1252. return $status;
  1253. }
  1254. /** isMultipage inherited */
  1255. /** pageCount inherited */
  1256. /** scaleHeight inherited */
  1257. /** getImageSize inherited */
  1258. /**
  1259. * Get the URL of the file description page.
  1260. * @return String
  1261. */
  1262. function getDescriptionUrl() {
  1263. return $this->title->getLocalUrl();
  1264. }
  1265. /**
  1266. * Get the HTML text of the description page
  1267. * This is not used by ImagePage for local files, since (among other things)
  1268. * it skips the parser cache.
  1269. * @return bool|mixed
  1270. */
  1271. function getDescriptionText() {
  1272. global $wgParser;
  1273. $revision = Revision::newFromTitle( $this->title, false, Revision::READ_NORMAL );
  1274. if ( !$revision ) return false;
  1275. $text = $revision->getText();
  1276. if ( !$text ) return false;
  1277. $pout = $wgParser->parse( $text, $this->title, new ParserOptions() );
  1278. return $pout->getText();
  1279. }
  1280. /**
  1281. * @return string
  1282. */
  1283. function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
  1284. $this->load();
  1285. if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
  1286. return '';
  1287. } elseif ( $audience == self::FOR_THIS_USER
  1288. && !$this->userCan( self::DELETED_COMMENT, $user ) )
  1289. {
  1290. return '';
  1291. } else {
  1292. return $this->description;
  1293. }
  1294. }
  1295. /**
  1296. * @return bool|string
  1297. */
  1298. function getTimestamp() {
  1299. $this->load();
  1300. return $this->timestamp;
  1301. }
  1302. /**
  1303. * @return string
  1304. */
  1305. function getSha1() {
  1306. $this->load();
  1307. // Initialise now if necessary
  1308. if ( $this->sha1 == '' && $this->fileExists ) {
  1309. $this->lock(); // begin
  1310. $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
  1311. if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
  1312. $dbw = $this->repo->getMasterDB();
  1313. $dbw->update( 'image',
  1314. array( 'img_sha1' => $this->sha1 ),
  1315. array( 'img_name' => $this->getName() ),
  1316. __METHOD__ );
  1317. $this->saveToCache();
  1318. }
  1319. $this->unlock(); // done
  1320. }
  1321. return $this->sha1;
  1322. }
  1323. /**
  1324. * @return bool
  1325. */
  1326. function isCacheable() {
  1327. $this->load();
  1328. return strlen( $this->metadata ) <= self::CACHE_FIELD_MAX_LEN; // avoid OOMs
  1329. }
  1330. /**
  1331. * Start a transaction and lock the image for update
  1332. * Increments a reference counter if the lock is already held
  1333. * @return boolean True if the image exists, false otherwise
  1334. */
  1335. function lock() {
  1336. $dbw = $this->repo->getMasterDB();
  1337. if ( !$this->locked ) {
  1338. $dbw->begin( __METHOD__ );
  1339. $this->locked++;
  1340. }
  1341. return $dbw->selectField( 'image', '1',
  1342. array( 'img_name' => $this->getName() ), __METHOD__, array( 'FOR UPDATE' ) );
  1343. }
  1344. /**
  1345. * Decrement the lock reference count. If the reference count is reduced to zero, commits
  1346. * the transaction and thereby releases the image lock.
  1347. */
  1348. function unlock() {
  1349. if ( $this->locked ) {
  1350. --$this->locked;
  1351. if ( !$this->locked ) {
  1352. $dbw = $this->repo->getMasterDB();
  1353. $dbw->commit( __METHOD__ );
  1354. }
  1355. }
  1356. }
  1357. /**
  1358. * Roll back the DB transaction and mark the image unlocked
  1359. */
  1360. function unlockAndRollback() {
  1361. $this->locked = false;
  1362. $dbw = $this->repo->getMasterDB();
  1363. $dbw->rollback( __METHOD__ );
  1364. }
  1365. /**
  1366. * @return Status
  1367. */
  1368. protected function readOnlyFatalStatus() {
  1369. return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
  1370. $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
  1371. }
  1372. } // LocalFile class
  1373. # ------------------------------------------------------------------------------
  1374. /**
  1375. * Helper class for file deletion
  1376. * @ingroup FileAbstraction
  1377. */
  1378. class LocalFileDeleteBatch {
  1379. /**
  1380. * @var LocalFile
  1381. */
  1382. var $file;
  1383. var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
  1384. var $status;
  1385. /**
  1386. * @param $file File
  1387. * @param $reason string
  1388. * @param $suppress bool
  1389. */
  1390. function __construct( File $file, $reason = '', $suppress = false ) {
  1391. $this->file = $file;
  1392. $this->reason = $reason;
  1393. $this->suppress = $suppress;
  1394. $this->status = $file->repo->newGood();
  1395. }
  1396. function addCurrent() {
  1397. $this->srcRels['.'] = $this->file->getRel();
  1398. }
  1399. /**
  1400. * @param $oldName string
  1401. */
  1402. function addOld( $oldName ) {
  1403. $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
  1404. $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
  1405. }
  1406. /**
  1407. * Add the old versions of the image to the batch
  1408. * @return Array List of archive names from old versions
  1409. */
  1410. function addOlds() {
  1411. $archiveNames = array();
  1412. $dbw = $this->file->repo->getMasterDB();
  1413. $result = $dbw->select( 'oldimage',
  1414. array( 'oi_archive_name' ),
  1415. array( 'oi_name' => $this->file->getName() ),
  1416. __METHOD__
  1417. );
  1418. foreach ( $result as $row ) {
  1419. $this->addOld( $row->oi_archive_name );
  1420. $archiveNames[] = $row->oi_archive_name;
  1421. }
  1422. return $archiveNames;
  1423. }
  1424. /**
  1425. * @return array
  1426. */
  1427. function getOldRels() {
  1428. if ( !isset( $this->srcRels['.'] ) ) {
  1429. $oldRels =& $this->srcRels;
  1430. $deleteCurrent = false;
  1431. } else {
  1432. $oldRels = $this->srcRels;
  1433. unset( $oldRels['.'] );
  1434. $deleteCurrent = true;
  1435. }
  1436. return array( $oldRels, $deleteCurrent );
  1437. }
  1438. /**
  1439. * @return array
  1440. */
  1441. protected function getHashes() {
  1442. $hashes = array();
  1443. list( $oldRels, $deleteCurrent ) = $this->getOldRels();
  1444. if ( $deleteCurrent ) {
  1445. $hashes['.'] = $this->file->getSha1();
  1446. }
  1447. if ( count( $oldRels ) ) {
  1448. $dbw = $this->file->repo->getMasterDB();
  1449. $res = $dbw->select(
  1450. 'oldimage',
  1451. array( 'oi_archive_name', 'oi_sha1' ),
  1452. 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
  1453. __METHOD__
  1454. );
  1455. foreach ( $res as $row ) {
  1456. if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
  1457. // Get the hash from the file
  1458. $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
  1459. $props = $this->file->repo->getFileProps( $oldUrl );
  1460. if ( $props['fileExists'] ) {
  1461. // Upgrade the oldimage row
  1462. $dbw->update( 'oldimage',
  1463. array( 'oi_sha1' => $props['sha1'] ),
  1464. array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
  1465. __METHOD__ );
  1466. $hashes[$row->oi_archive_name] = $props['sha1'];
  1467. } else {
  1468. $hashes[$row->oi_archive_name] = false;
  1469. }
  1470. } else {
  1471. $hashes[$row->oi_archive_name] = $row->oi_sha1;
  1472. }
  1473. }
  1474. }
  1475. $missing = array_diff_key( $this->srcRels, $hashes );
  1476. foreach ( $missing as $name => $rel ) {
  1477. $this->status->error( 'filedelete-old-unregistered', $name );
  1478. }
  1479. foreach ( $hashes as $name => $hash ) {
  1480. if ( !$hash ) {
  1481. $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
  1482. unset( $hashes[$name] );
  1483. }
  1484. }
  1485. return $hashes;
  1486. }
  1487. function doDBInserts() {
  1488. global $wgUser;
  1489. $dbw = $this->file->repo->getMasterDB();
  1490. $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
  1491. $encUserId = $dbw->addQuotes( $wgUser->getId() );
  1492. $encReason = $dbw->addQuotes( $this->reason );
  1493. $encGroup = $dbw->addQuotes( 'deleted' );
  1494. $ext = $this->file->getExtension();
  1495. $dotExt = $ext === '' ? '' : ".$ext";
  1496. $encExt = $dbw->addQuotes( $dotExt );
  1497. list( $oldRels, $deleteCurrent ) = $this->getOldRels();
  1498. // Bitfields to further suppress the content
  1499. if ( $this->suppress ) {
  1500. $bitfield = 0;
  1501. // This should be 15...
  1502. $bitfield |= Revision::DELETED_TEXT;
  1503. $bitfield |= Revision::DELETED_COMMENT;
  1504. $bitfield |= Revision::DELETED_USER;
  1505. $bitfield |= Revision::DELETED_RESTRICTED;
  1506. } else {
  1507. $bitfield = 'oi_deleted';
  1508. }
  1509. if ( $deleteCurrent ) {
  1510. $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
  1511. $where = array( 'img_name' => $this->file->getName() );
  1512. $dbw->insertSelect( 'filearchive', 'image',
  1513. array(
  1514. 'fa_storage_group' => $encGroup,
  1515. 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
  1516. 'fa_deleted_user' => $encUserId,
  1517. 'fa_deleted_timestamp' => $encTimestamp,
  1518. 'fa_deleted_reason' => $encReason,
  1519. 'fa_deleted' => $this->suppress ? $bitfield : 0,
  1520. 'fa_name' => 'img_name',
  1521. 'fa_archive_name' => 'NULL',
  1522. 'fa_size' => 'img_size',
  1523. 'fa_width' => 'img_width',
  1524. 'fa_height' => 'img_height',
  1525. 'fa_metadata' => 'img_metadata',
  1526. 'fa_bits' => 'img_bits',
  1527. 'fa_media_type' => 'img_media_type',
  1528. 'fa_major_mime' => 'img_major_mime',
  1529. 'fa_minor_mime' => 'img_minor_mime',
  1530. 'fa_description' => 'img_description',
  1531. 'fa_user' => 'img_user',
  1532. 'fa_user_text' => 'img_user_text',
  1533. 'fa_timestamp' => 'img_timestamp'
  1534. ), $where, __METHOD__ );
  1535. }
  1536. if ( count( $oldRels ) ) {
  1537. $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
  1538. $where = array(
  1539. 'oi_name' => $this->file->getName(),
  1540. 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
  1541. $dbw->insertSelect( 'filearchive', 'oldimage',
  1542. array(
  1543. 'fa_storage_group' => $encGroup,
  1544. 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
  1545. 'fa_deleted_user' => $encUserId,
  1546. 'fa_deleted_timestamp' => $encTimestamp,
  1547. 'fa_deleted_reason' => $encReason,
  1548. 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
  1549. 'fa_name' => 'oi_name',
  1550. 'fa_archive_name' => 'oi_archive_name',
  1551. 'fa_size' => 'oi_size',
  1552. 'fa_width' => 'oi_width',
  1553. 'fa_height' => 'oi_height',
  1554. 'fa_metadata' => 'oi_metadata',
  1555. 'fa_bits' => 'oi_bits',
  1556. 'fa_media_type' => 'oi_media_type',
  1557. 'fa_major_mime' => 'oi_major_mime',
  1558. 'fa_minor_mime' => 'oi_minor_mime',
  1559. 'fa_description' => 'oi_description',
  1560. 'fa_user' => 'oi_user',
  1561. 'fa_user_text' => 'oi_user_text',
  1562. 'fa_timestamp' => 'oi_timestamp',
  1563. ), $where, __METHOD__ );
  1564. }
  1565. }
  1566. function doDBDeletes() {
  1567. $dbw = $this->file->repo->getMasterDB();
  1568. list( $oldRels, $deleteCurrent ) = $this->getOldRels();
  1569. if ( count( $oldRels ) ) {
  1570. $dbw->delete( 'oldimage',
  1571. array(
  1572. 'oi_name' => $this->file->getName(),
  1573. 'oi_archive_name' => array_keys( $oldRels )
  1574. ), __METHOD__ );
  1575. }
  1576. if ( $deleteCurrent ) {
  1577. $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
  1578. }
  1579. }
  1580. /**
  1581. * Run the transaction
  1582. * @return FileRepoStatus
  1583. */
  1584. function execute() {
  1585. wfProfileIn( __METHOD__ );
  1586. $this->file->lock();
  1587. // Leave private files alone
  1588. $privateFiles = array();
  1589. list( $oldRels, $deleteCurrent ) = $this->getOldRels();
  1590. $dbw = $this->file->repo->getMasterDB();
  1591. if ( !empty( $oldRels ) ) {
  1592. $res = $dbw->select( 'oldimage',
  1593. array( 'oi_archive_name' ),
  1594. array( 'oi_name' => $this->file->getName(),
  1595. 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
  1596. $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE ),
  1597. __METHOD__ );
  1598. foreach ( $res as $row ) {
  1599. $privateFiles[$row->oi_archive_name] = 1;
  1600. }
  1601. }
  1602. // Prepare deletion batch
  1603. $hashes = $this->getHashes();
  1604. $this->deletionBatch = array();
  1605. $ext = $this->file->getExtension();
  1606. $dotExt = $ext === '' ? '' : ".$ext";
  1607. foreach ( $this->srcRels as $name => $srcRel ) {
  1608. // Skip files that have no hash (missing source).
  1609. // Keep private files where they are.
  1610. if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
  1611. $hash = $hashes[$name];
  1612. $key = $hash . $dotExt;
  1613. $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
  1614. $this->deletionBatch[$name] = array( $srcRel, $dstRel );
  1615. }
  1616. }
  1617. // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
  1618. // We acquire this lock by running the inserts now, before the file operations.
  1619. //
  1620. // This potentially has poor lock contention characteristics -- an alternative
  1621. // scheme would be to insert stub filearchive entries with no fa_name and commit
  1622. // them in a separate transaction, then run the file ops, then update the fa_name fields.
  1623. $this->doDBInserts();
  1624. // Removes non-existent file from the batch, so we don't get errors.
  1625. $this->deletionBatch = $this->removeNonexistentFiles( $this->deletionBatch );
  1626. // Execute the file deletion batch
  1627. $status = $this->file->repo->deleteBatch( $this->deletionBatch );
  1628. if ( !$status->isGood() ) {
  1629. $this->status->merge( $status );
  1630. }
  1631. if ( !$this->status->isOK() ) {
  1632. // Critical file deletion error
  1633. // Roll back inserts, release lock and abort
  1634. // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
  1635. $this->file->unlockAndRollback();
  1636. wfProfileOut( __METHOD__ );
  1637. return $this->status;
  1638. }
  1639. // Delete image/oldimage rows
  1640. $this->doDBDeletes();
  1641. // Commit and return
  1642. $this->file->unlock();
  1643. wfProfileOut( __METHOD__ );
  1644. return $this->status;
  1645. }
  1646. /**
  1647. * Removes non-existent files from a deletion batch.
  1648. * @param $batch array
  1649. * @return array
  1650. */
  1651. function removeNonexistentFiles( $batch ) {
  1652. $files = $newBatch = array();
  1653. foreach ( $batch as $batchItem ) {
  1654. list( $src, $dest ) = $batchItem;
  1655. $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
  1656. }
  1657. $result = $this->file->repo->fileExistsBatch( $files );
  1658. foreach ( $batch as $batchItem ) {
  1659. if ( $result[$batchItem[0]] ) {
  1660. $newBatch[] = $batchItem;
  1661. }
  1662. }
  1663. return $newBatch;
  1664. }
  1665. }
  1666. # ------------------------------------------------------------------------------
  1667. /**
  1668. * Helper class for file undeletion
  1669. * @ingroup FileAbstraction
  1670. */
  1671. class LocalFileRestoreBatch {
  1672. /**
  1673. * @var LocalFile
  1674. */
  1675. var $file;
  1676. var $cleanupBatch, $ids, $all, $unsuppress = false;
  1677. /**
  1678. * @param $file File
  1679. * @param $unsuppress bool
  1680. */
  1681. function __construct( File $file, $unsuppress = false ) {
  1682. $this->file = $file;
  1683. $this->cleanupBatch = $this->ids = array();
  1684. $this->ids = array();
  1685. $this->unsuppress = $unsuppress;
  1686. }
  1687. /**
  1688. * Add a file by ID
  1689. */
  1690. function addId( $fa_id ) {
  1691. $this->ids[] = $fa_id;
  1692. }
  1693. /**
  1694. * Add a whole lot of files by ID
  1695. */
  1696. function addIds( $ids ) {
  1697. $this->ids = array_merge( $this->ids, $ids );
  1698. }
  1699. /**
  1700. * Add all revisions of the file
  1701. */
  1702. function addAll() {
  1703. $this->all = true;
  1704. }
  1705. /**
  1706. * Run the transaction, except the cleanup batch.
  1707. * The cleanup batch should be run in a separate transaction, because it locks different
  1708. * rows and there's no need to keep the image row locked while it's acquiring those locks
  1709. * The caller may have its own transaction open.
  1710. * So we save the batch and let the caller call cleanup()
  1711. * @return FileRepoStatus
  1712. */
  1713. function execute() {
  1714. global $wgLang;
  1715. if ( !$this->all && !$this->ids ) {
  1716. // Do nothing
  1717. return $this->file->repo->newGood();
  1718. }
  1719. $exists = $this->file->lock();
  1720. $dbw = $this->file->repo->getMasterDB();
  1721. $status = $this->file->repo->newGood();
  1722. // Fetch all or selected archived revisions for the file,
  1723. // sorted from the most recent to the oldest.
  1724. $conditions = array( 'fa_name' => $this->file->getName() );
  1725. if ( !$this->all ) {
  1726. $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
  1727. }
  1728. $result = $dbw->select( 'filearchive', '*',
  1729. $conditions,
  1730. __METHOD__,
  1731. array( 'ORDER BY' => 'fa_timestamp DESC' )
  1732. );
  1733. $idsPresent = array();
  1734. $storeBatch = array();
  1735. $insertBatch = array();
  1736. $insertCurrent = false;
  1737. $deleteIds = array();
  1738. $first = true;
  1739. $archiveNames = array();
  1740. foreach ( $result as $row ) {
  1741. $idsPresent[] = $row->fa_id;
  1742. if ( $row->fa_name != $this->file->getName() ) {
  1743. $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
  1744. $status->failCount++;
  1745. continue;
  1746. }
  1747. if ( $row->fa_storage_key == '' ) {
  1748. // Revision was missing pre-deletion
  1749. $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
  1750. $status->failCount++;
  1751. continue;
  1752. }
  1753. $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) . $row->fa_storage_key;
  1754. $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
  1755. $sha1 = substr( $row->fa_storage_key, 0, strcspn( $row->fa_storage_key, '.' ) );
  1756. # Fix leading zero
  1757. if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
  1758. $sha1 = substr( $sha1, 1 );
  1759. }
  1760. if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
  1761. || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
  1762. || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
  1763. || is_null( $row->fa_metadata ) ) {
  1764. // Refresh our metadata
  1765. // Required for a new current revision; nice for older ones too. :)
  1766. $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
  1767. } else {
  1768. $props = array(
  1769. 'minor_mime' => $row->fa_minor_mime,
  1770. 'major_mime' => $row->fa_major_mime,
  1771. 'media_type' => $row->fa_media_type,
  1772. 'metadata' => $row->fa_metadata
  1773. );
  1774. }
  1775. if ( $first && !$exists ) {
  1776. // This revision will be published as the new current version
  1777. $destRel = $this->file->getRel();
  1778. $insertCurrent = array(
  1779. 'img_name' => $row->fa_name,
  1780. 'img_size' => $row->fa_size,
  1781. 'img_width' => $row->fa_width,
  1782. 'img_height' => $row->fa_height,
  1783. 'img_metadata' => $props['metadata'],
  1784. 'img_bits' => $row->fa_bits,
  1785. 'img_media_type' => $props['media_type'],
  1786. 'img_major_mime' => $props['major_mime'],
  1787. 'img_minor_mime' => $props['minor_mime'],
  1788. 'img_description' => $row->fa_description,
  1789. 'img_user' => $row->fa_user,
  1790. 'img_user_text' => $row->fa_user_text,
  1791. 'img_timestamp' => $row->fa_timestamp,
  1792. 'img_sha1' => $sha1
  1793. );
  1794. // The live (current) version cannot be hidden!
  1795. if ( !$this->unsuppress && $row->fa_deleted ) {
  1796. $storeBatch[] = array( $deletedUrl, 'public', $destRel );
  1797. $this->cleanupBatch[] = $row->fa_storage_key;
  1798. }
  1799. } else {
  1800. $archiveName = $row->fa_archive_name;
  1801. if ( $archiveName == '' ) {
  1802. // This was originally a current version; we
  1803. // have to devise a new archive name for it.
  1804. // Format is <timestamp of archiving>!<name>
  1805. $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
  1806. do {
  1807. $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
  1808. $timestamp++;
  1809. } while ( isset( $archiveNames[$archiveName] ) );
  1810. }
  1811. $archiveNames[$archiveName] = true;
  1812. $destRel = $this->file->getArchiveRel( $archiveName );
  1813. $insertBatch[] = array(
  1814. 'oi_name' => $row->fa_name,
  1815. 'oi_archive_name' => $archiveName,
  1816. 'oi_size' => $row->fa_size,
  1817. 'oi_width' => $row->fa_width,
  1818. 'oi_height' => $row->fa_height,
  1819. 'oi_bits' => $row->fa_bits,
  1820. 'oi_description' => $row->fa_description,
  1821. 'oi_user' => $row->fa_user,
  1822. 'oi_user_text' => $row->fa_user_text,
  1823. 'oi_timestamp' => $row->fa_timestamp,
  1824. 'oi_metadata' => $props['metadata'],
  1825. 'oi_media_type' => $props['media_type'],
  1826. 'oi_major_mime' => $props['major_mime'],
  1827. 'oi_minor_mime' => $props['minor_mime'],
  1828. 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
  1829. 'oi_sha1' => $sha1 );
  1830. }
  1831. $deleteIds[] = $row->fa_id;
  1832. if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
  1833. // private files can stay where they are
  1834. $status->successCount++;
  1835. } else {
  1836. $storeBatch[] = array( $deletedUrl, 'public', $destRel );
  1837. $this->cleanupBatch[] = $row->fa_storage_key;
  1838. }
  1839. $first = false;
  1840. }
  1841. unset( $result );
  1842. // Add a warning to the status object for missing IDs
  1843. $missingIds = array_diff( $this->ids, $idsPresent );
  1844. foreach ( $missingIds as $id ) {
  1845. $status->error( 'undelete-missing-filearchive', $id );
  1846. }
  1847. // Remove missing files from batch, so we don't get errors when undeleting them
  1848. $storeBatch = $this->removeNonexistentFiles( $storeBatch );
  1849. // Run the store batch
  1850. // Use the OVERWRITE_SAME flag to smooth over a common error
  1851. $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
  1852. $status->merge( $storeStatus );
  1853. if ( !$status->isGood() ) {
  1854. // Even if some files could be copied, fail entirely as that is the
  1855. // easiest thing to do without data loss
  1856. $this->cleanupFailedBatch( $storeStatus, $storeBatch );
  1857. $status->ok = false;
  1858. $this->file->unlock();
  1859. return $status;
  1860. }
  1861. // Run the DB updates
  1862. // Because we have locked the image row, key conflicts should be rare.
  1863. // If they do occur, we can roll back the transaction at this time with
  1864. // no data loss, but leaving unregistered files scattered throughout the
  1865. // public zone.
  1866. // This is not ideal, which is why it's important to lock the image row.
  1867. if ( $insertCurrent ) {
  1868. $dbw->insert( 'image', $insertCurrent, __METHOD__ );
  1869. }
  1870. if ( $insertBatch ) {
  1871. $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
  1872. }
  1873. if ( $deleteIds ) {
  1874. $dbw->delete( 'filearchive',
  1875. array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
  1876. __METHOD__ );
  1877. }
  1878. // If store batch is empty (all files are missing), deletion is to be considered successful
  1879. if ( $status->successCount > 0 || !$storeBatch ) {
  1880. if ( !$exists ) {
  1881. wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
  1882. DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
  1883. $this->file->purgeEverything();
  1884. } else {
  1885. wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
  1886. $this->file->purgeDescription();
  1887. $this->file->purgeHistory();
  1888. }
  1889. }
  1890. $this->file->unlock();
  1891. return $status;
  1892. }
  1893. /**
  1894. * Removes non-existent files from a store batch.
  1895. * @param $triplets array
  1896. * @return array
  1897. */
  1898. function removeNonexistentFiles( $triplets ) {
  1899. $files = $filteredTriplets = array();
  1900. foreach ( $triplets as $file ) {
  1901. $files[$file[0]] = $file[0];
  1902. }
  1903. $result = $this->file->repo->fileExistsBatch( $files );
  1904. foreach ( $triplets as $file ) {
  1905. if ( $result[$file[0]] ) {
  1906. $filteredTriplets[] = $file;
  1907. }
  1908. }
  1909. return $filteredTriplets;
  1910. }
  1911. /**
  1912. * Removes non-existent files from a cleanup batch.
  1913. * @param $batch array
  1914. * @return array
  1915. */
  1916. function removeNonexistentFromCleanup( $batch ) {
  1917. $files = $newBatch = array();
  1918. $repo = $this->file->repo;
  1919. foreach ( $batch as $file ) {
  1920. $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
  1921. rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
  1922. }
  1923. $result = $repo->fileExistsBatch( $files );
  1924. foreach ( $batch as $file ) {
  1925. if ( $result[$file] ) {
  1926. $newBatch[] = $file;
  1927. }
  1928. }
  1929. return $newBatch;
  1930. }
  1931. /**
  1932. * Delete unused files in the deleted zone.
  1933. * This should be called from outside the transaction in which execute() was called.
  1934. * @return FileRepoStatus|void
  1935. */
  1936. function cleanup() {
  1937. if ( !$this->cleanupBatch ) {
  1938. return $this->file->repo->newGood();
  1939. }
  1940. $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
  1941. $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
  1942. return $status;
  1943. }
  1944. /**
  1945. * Cleanup a failed batch. The batch was only partially successful, so
  1946. * rollback by removing all items that were succesfully copied.
  1947. *
  1948. * @param Status $storeStatus
  1949. * @param array $storeBatch
  1950. */
  1951. function cleanupFailedBatch( $storeStatus, $storeBatch ) {
  1952. $cleanupBatch = array();
  1953. foreach ( $storeStatus->success as $i => $success ) {
  1954. // Check if this item of the batch was successfully copied
  1955. if ( $success ) {
  1956. // Item was successfully copied and needs to be removed again
  1957. // Extract ($dstZone, $dstRel) from the batch
  1958. $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
  1959. }
  1960. }
  1961. $this->file->repo->cleanupBatch( $cleanupBatch );
  1962. }
  1963. }
  1964. # ------------------------------------------------------------------------------
  1965. /**
  1966. * Helper class for file movement
  1967. * @ingroup FileAbstraction
  1968. */
  1969. class LocalFileMoveBatch {
  1970. /**
  1971. * @var LocalFile
  1972. */
  1973. var $file;
  1974. /**
  1975. * @var Title
  1976. */
  1977. var $target;
  1978. var $cur, $olds, $oldCount, $archive;
  1979. /**
  1980. * @var DatabaseBase
  1981. */
  1982. var $db;
  1983. /**
  1984. * @param File $file
  1985. * @param Title $target
  1986. */
  1987. function __construct( File $file, Title $target ) {
  1988. $this->file = $file;
  1989. $this->target = $target;
  1990. $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
  1991. $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
  1992. $this->oldName = $this->file->getName();
  1993. $this->newName = $this->file->repo->getNameFromTitle( $this->target );
  1994. $this->oldRel = $this->oldHash . $this->oldName;
  1995. $this->newRel = $this->newHash . $this->newName;
  1996. $this->db = $file->getRepo()->getMasterDb();
  1997. }
  1998. /**
  1999. * Add the current image to the batch
  2000. */
  2001. function addCurrent() {
  2002. $this->cur = array( $this->oldRel, $this->newRel );
  2003. }
  2004. /**
  2005. * Add the old versions of the image to the batch
  2006. * @return Array List of archive names from old versions
  2007. */
  2008. function addOlds() {
  2009. $archiveBase = 'archive';
  2010. $this->olds = array();
  2011. $this->oldCount = 0;
  2012. $archiveNames = array();
  2013. $result = $this->db->select( 'oldimage',
  2014. array( 'oi_archive_name', 'oi_deleted' ),
  2015. array( 'oi_name' => $this->oldName ),
  2016. __METHOD__
  2017. );
  2018. foreach ( $result as $row ) {
  2019. $archiveNames[] = $row->oi_archive_name;
  2020. $oldName = $row->oi_archive_name;
  2021. $bits = explode( '!', $oldName, 2 );
  2022. if ( count( $bits ) != 2 ) {
  2023. wfDebug( "Old file name missing !: '$oldName' \n" );
  2024. continue;
  2025. }
  2026. list( $timestamp, $filename ) = $bits;
  2027. if ( $this->oldName != $filename ) {
  2028. wfDebug( "Old file name doesn't match: '$oldName' \n" );
  2029. continue;
  2030. }
  2031. $this->oldCount++;
  2032. // Do we want to add those to oldCount?
  2033. if ( $row->oi_deleted & File::DELETED_FILE ) {
  2034. continue;
  2035. }
  2036. $this->olds[] = array(
  2037. "{$archiveBase}/{$this->oldHash}{$oldName}",
  2038. "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
  2039. );
  2040. }
  2041. return $archiveNames;
  2042. }
  2043. /**
  2044. * Perform the move.
  2045. * @return FileRepoStatus
  2046. */
  2047. function execute() {
  2048. $repo = $this->file->repo;
  2049. $status = $repo->newGood();
  2050. $triplets = $this->getMoveTriplets();
  2051. $triplets = $this->removeNonexistentFiles( $triplets );
  2052. $this->file->lock(); // begin
  2053. // Rename the file versions metadata in the DB.
  2054. // This implicitly locks the destination file, which avoids race conditions.
  2055. // If we moved the files from A -> C before DB updates, another process could
  2056. // move files from B -> C at this point, causing storeBatch() to fail and thus
  2057. // cleanupTarget() to trigger. It would delete the C files and cause data loss.
  2058. $statusDb = $this->doDBUpdates();
  2059. if ( !$statusDb->isGood() ) {
  2060. $this->file->unlockAndRollback();
  2061. $statusDb->ok = false;
  2062. return $statusDb;
  2063. }
  2064. wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
  2065. // Copy the files into their new location.
  2066. // If a prior process fataled copying or cleaning up files we tolerate any
  2067. // of the existing files if they are identical to the ones being stored.
  2068. $statusMove = $repo->storeBatch( $triplets, FileRepo::OVERWRITE_SAME );
  2069. wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
  2070. if ( !$statusMove->isGood() ) {
  2071. // Delete any files copied over (while the destination is still locked)
  2072. $this->cleanupTarget( $triplets );
  2073. $this->file->unlockAndRollback(); // unlocks the destination
  2074. wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
  2075. $statusMove->ok = false;
  2076. return $statusMove;
  2077. }
  2078. $this->file->unlock(); // done
  2079. // Everything went ok, remove the source files
  2080. $this->cleanupSource( $triplets );
  2081. $status->merge( $statusDb );
  2082. $status->merge( $statusMove );
  2083. return $status;
  2084. }
  2085. /**
  2086. * Do the database updates and return a new FileRepoStatus indicating how
  2087. * many rows where updated.
  2088. *
  2089. * @return FileRepoStatus
  2090. */
  2091. function doDBUpdates() {
  2092. $repo = $this->file->repo;
  2093. $status = $repo->newGood();
  2094. $dbw = $this->db;
  2095. // Update current image
  2096. $dbw->update(
  2097. 'image',
  2098. array( 'img_name' => $this->newName ),
  2099. array( 'img_name' => $this->oldName ),
  2100. __METHOD__
  2101. );
  2102. if ( $dbw->affectedRows() ) {
  2103. $status->successCount++;
  2104. } else {
  2105. $status->failCount++;
  2106. $status->fatal( 'imageinvalidfilename' );
  2107. return $status;
  2108. }
  2109. // Update old images
  2110. $dbw->update(
  2111. 'oldimage',
  2112. array(
  2113. 'oi_name' => $this->newName,
  2114. 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
  2115. $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
  2116. ),
  2117. array( 'oi_name' => $this->oldName ),
  2118. __METHOD__
  2119. );
  2120. $affected = $dbw->affectedRows();
  2121. $total = $this->oldCount;
  2122. $status->successCount += $affected;
  2123. // Bug 34934: $total is based on files that actually exist.
  2124. // There may be more DB rows than such files, in which case $affected
  2125. // can be greater than $total. We use max() to avoid negatives here.
  2126. $status->failCount += max( 0, $total - $affected );
  2127. if ( $status->failCount ) {
  2128. $status->error( 'imageinvalidfilename' );
  2129. }
  2130. return $status;
  2131. }
  2132. /**
  2133. * Generate triplets for FileRepo::storeBatch().
  2134. * @return array
  2135. */
  2136. function getMoveTriplets() {
  2137. $moves = array_merge( array( $this->cur ), $this->olds );
  2138. $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
  2139. foreach ( $moves as $move ) {
  2140. // $move: (oldRelativePath, newRelativePath)
  2141. $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
  2142. $triplets[] = array( $srcUrl, 'public', $move[1] );
  2143. wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
  2144. }
  2145. return $triplets;
  2146. }
  2147. /**
  2148. * Removes non-existent files from move batch.
  2149. * @param $triplets array
  2150. * @return array
  2151. */
  2152. function removeNonexistentFiles( $triplets ) {
  2153. $files = array();
  2154. foreach ( $triplets as $file ) {
  2155. $files[$file[0]] = $file[0];
  2156. }
  2157. $result = $this->file->repo->fileExistsBatch( $files );
  2158. $filteredTriplets = array();
  2159. foreach ( $triplets as $file ) {
  2160. if ( $result[$file[0]] ) {
  2161. $filteredTriplets[] = $file;
  2162. } else {
  2163. wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
  2164. }
  2165. }
  2166. return $filteredTriplets;
  2167. }
  2168. /**
  2169. * Cleanup a partially moved array of triplets by deleting the target
  2170. * files. Called if something went wrong half way.
  2171. */
  2172. function cleanupTarget( $triplets ) {
  2173. // Create dest pairs from the triplets
  2174. $pairs = array();
  2175. foreach ( $triplets as $triplet ) {
  2176. // $triplet: (old source virtual URL, dst zone, dest rel)
  2177. $pairs[] = array( $triplet[1], $triplet[2] );
  2178. }
  2179. $this->file->repo->cleanupBatch( $pairs );
  2180. }
  2181. /**
  2182. * Cleanup a fully moved array of triplets by deleting the source files.
  2183. * Called at the end of the move process if everything else went ok.
  2184. */
  2185. function cleanupSource( $triplets ) {
  2186. // Create source file names from the triplets
  2187. $files = array();
  2188. foreach ( $triplets as $triplet ) {
  2189. $files[] = $triplet[0];
  2190. }
  2191. $this->file->repo->cleanupBatch( $files );
  2192. }
  2193. }