PageRenderTime 71ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/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
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0

Large files files are truncated, but you can click here to view the full 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 =

Large files files are truncated, but you can click here to view the full file