File.php 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320
  1. <?php
  2. /**
  3. * @defgroup FileAbstraction File abstraction
  4. * @ingroup FileRepo
  5. *
  6. * Represents files in a repository.
  7. */
  8. use MediaWiki\MediaWikiServices;
  9. /**
  10. * Base code for files.
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 2 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License along
  23. * with this program; if not, write to the Free Software Foundation, Inc.,
  24. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  25. * http://www.gnu.org/copyleft/gpl.html
  26. *
  27. * @file
  28. * @ingroup FileAbstraction
  29. */
  30. /**
  31. * Implements some public methods and some protected utility functions which
  32. * are required by multiple child classes. Contains stub functionality for
  33. * unimplemented public methods.
  34. *
  35. * Stub functions which should be overridden are marked with STUB. Some more
  36. * concrete functions are also typically overridden by child classes.
  37. *
  38. * Note that only the repo object knows what its file class is called. You should
  39. * never name a file class explictly outside of the repo class. Instead use the
  40. * repo's factory functions to generate file objects, for example:
  41. *
  42. * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
  43. *
  44. * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
  45. * in most cases.
  46. *
  47. * @ingroup FileAbstraction
  48. */
  49. abstract class File implements IDBAccessObject {
  50. // Bitfield values akin to the Revision deletion constants
  51. const DELETED_FILE = 1;
  52. const DELETED_COMMENT = 2;
  53. const DELETED_USER = 4;
  54. const DELETED_RESTRICTED = 8;
  55. /** Force rendering in the current process */
  56. const RENDER_NOW = 1;
  57. /**
  58. * Force rendering even if thumbnail already exist and using RENDER_NOW
  59. * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
  60. */
  61. const RENDER_FORCE = 2;
  62. const DELETE_SOURCE = 1;
  63. // Audience options for File::getDescription()
  64. const FOR_PUBLIC = 1;
  65. const FOR_THIS_USER = 2;
  66. const RAW = 3;
  67. // Options for File::thumbName()
  68. const THUMB_FULL_NAME = 1;
  69. /**
  70. * Some member variables can be lazy-initialised using __get(). The
  71. * initialisation function for these variables is always a function named
  72. * like getVar(), where Var is the variable name with upper-case first
  73. * letter.
  74. *
  75. * The following variables are initialised in this way in this base class:
  76. * name, extension, handler, path, canRender, isSafeFile,
  77. * transformScript, hashPath, pageCount, url
  78. *
  79. * Code within this class should generally use the accessor function
  80. * directly, since __get() isn't re-entrant and therefore causes bugs that
  81. * depend on initialisation order.
  82. */
  83. /**
  84. * The following member variables are not lazy-initialised
  85. */
  86. /** @var FileRepo|LocalRepo|ForeignAPIRepo|bool */
  87. public $repo;
  88. /** @var Title|string|bool */
  89. protected $title;
  90. /** @var string Text of last error */
  91. protected $lastError;
  92. /** @var string Main part of the title, with underscores (Title::getDBkey) */
  93. protected $redirected;
  94. /** @var Title */
  95. protected $redirectedTitle;
  96. /** @var FSFile|bool False if undefined */
  97. protected $fsFile;
  98. /** @var MediaHandler */
  99. protected $handler;
  100. /** @var string The URL corresponding to one of the four basic zones */
  101. protected $url;
  102. /** @var string File extension */
  103. protected $extension;
  104. /** @var string The name of a file from its title object */
  105. protected $name;
  106. /** @var string The storage path corresponding to one of the zones */
  107. protected $path;
  108. /** @var string Relative path including trailing slash */
  109. protected $hashPath;
  110. /** @var string|false Number of pages of a multipage document, or false for
  111. * documents which aren't multipage documents
  112. */
  113. protected $pageCount;
  114. /** @var string URL of transformscript (for example thumb.php) */
  115. protected $transformScript;
  116. /** @var Title */
  117. protected $redirectTitle;
  118. /** @var bool Whether the output of transform() for this file is likely to be valid. */
  119. protected $canRender;
  120. /** @var bool Whether this media file is in a format that is unlikely to
  121. * contain viruses or malicious content
  122. */
  123. protected $isSafeFile;
  124. /** @var string Required Repository class type */
  125. protected $repoClass = FileRepo::class;
  126. /** @var array Cache of tmp filepaths pointing to generated bucket thumbnails, keyed by width */
  127. protected $tmpBucketedThumbCache = [];
  128. /**
  129. * Call this constructor from child classes.
  130. *
  131. * Both $title and $repo are optional, though some functions
  132. * may return false or throw exceptions if they are not set.
  133. * Most subclasses will want to call assertRepoDefined() here.
  134. *
  135. * @param Title|string|bool $title
  136. * @param FileRepo|bool $repo
  137. */
  138. function __construct( $title, $repo ) {
  139. // Some subclasses do not use $title, but set name/title some other way
  140. if ( $title !== false ) {
  141. $title = self::normalizeTitle( $title, 'exception' );
  142. }
  143. $this->title = $title;
  144. $this->repo = $repo;
  145. }
  146. /**
  147. * Given a string or Title object return either a
  148. * valid Title object with namespace NS_FILE or null
  149. *
  150. * @param Title|string $title
  151. * @param string|bool $exception Use 'exception' to throw an error on bad titles
  152. * @throws MWException
  153. * @return Title|null
  154. */
  155. static function normalizeTitle( $title, $exception = false ) {
  156. $ret = $title;
  157. if ( $ret instanceof Title ) {
  158. # Normalize NS_MEDIA -> NS_FILE
  159. if ( $ret->getNamespace() == NS_MEDIA ) {
  160. $ret = Title::makeTitleSafe( NS_FILE, $ret->getDBkey() );
  161. # Sanity check the title namespace
  162. } elseif ( $ret->getNamespace() !== NS_FILE ) {
  163. $ret = null;
  164. }
  165. } else {
  166. # Convert strings to Title objects
  167. $ret = Title::makeTitleSafe( NS_FILE, (string)$ret );
  168. }
  169. if ( !$ret && $exception !== false ) {
  170. throw new MWException( "`$title` is not a valid file title." );
  171. }
  172. return $ret;
  173. }
  174. function __get( $name ) {
  175. $function = [ $this, 'get' . ucfirst( $name ) ];
  176. if ( !is_callable( $function ) ) {
  177. return null;
  178. } else {
  179. $this->$name = call_user_func( $function );
  180. return $this->$name;
  181. }
  182. }
  183. /**
  184. * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
  185. * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
  186. * Keep in sync with mw.Title.normalizeExtension() in JS.
  187. *
  188. * @param string $extension File extension (without the leading dot)
  189. * @return string File extension in canonical form
  190. */
  191. static function normalizeExtension( $extension ) {
  192. $lower = strtolower( $extension );
  193. $squish = [
  194. 'htm' => 'html',
  195. 'jpeg' => 'jpg',
  196. 'mpeg' => 'mpg',
  197. 'tiff' => 'tif',
  198. 'ogv' => 'ogg' ];
  199. if ( isset( $squish[$lower] ) ) {
  200. return $squish[$lower];
  201. } elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
  202. return $lower;
  203. } else {
  204. return '';
  205. }
  206. }
  207. /**
  208. * Checks if file extensions are compatible
  209. *
  210. * @param File $old Old file
  211. * @param string $new New name
  212. *
  213. * @return bool|null
  214. */
  215. static function checkExtensionCompatibility( File $old, $new ) {
  216. $oldMime = $old->getMimeType();
  217. $n = strrpos( $new, '.' );
  218. $newExt = self::normalizeExtension( $n ? substr( $new, $n + 1 ) : '' );
  219. $mimeMagic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
  220. return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
  221. }
  222. /**
  223. * Upgrade the database row if there is one
  224. * Called by ImagePage
  225. * STUB
  226. */
  227. function upgradeRow() {
  228. }
  229. /**
  230. * Split an internet media type into its two components; if not
  231. * a two-part name, set the minor type to 'unknown'.
  232. *
  233. * @param string $mime "text/html" etc
  234. * @return string[] ("text", "html") etc
  235. */
  236. public static function splitMime( $mime ) {
  237. if ( strpos( $mime, '/' ) !== false ) {
  238. return explode( '/', $mime, 2 );
  239. } else {
  240. return [ $mime, 'unknown' ];
  241. }
  242. }
  243. /**
  244. * Callback for usort() to do file sorts by name
  245. *
  246. * @param File $a
  247. * @param File $b
  248. * @return int Result of name comparison
  249. */
  250. public static function compare( File $a, File $b ) {
  251. return strcmp( $a->getName(), $b->getName() );
  252. }
  253. /**
  254. * Return the name of this file
  255. *
  256. * @return string
  257. */
  258. public function getName() {
  259. if ( !isset( $this->name ) ) {
  260. $this->assertRepoDefined();
  261. $this->name = $this->repo->getNameFromTitle( $this->title );
  262. }
  263. return $this->name;
  264. }
  265. /**
  266. * Get the file extension, e.g. "svg"
  267. *
  268. * @return string
  269. */
  270. function getExtension() {
  271. if ( !isset( $this->extension ) ) {
  272. $n = strrpos( $this->getName(), '.' );
  273. $this->extension = self::normalizeExtension(
  274. $n ? substr( $this->getName(), $n + 1 ) : '' );
  275. }
  276. return $this->extension;
  277. }
  278. /**
  279. * Return the associated title object
  280. *
  281. * @return Title
  282. */
  283. public function getTitle() {
  284. return $this->title;
  285. }
  286. /**
  287. * Return the title used to find this file
  288. *
  289. * @return Title
  290. */
  291. public function getOriginalTitle() {
  292. if ( $this->redirected ) {
  293. return $this->getRedirectedTitle();
  294. }
  295. return $this->title;
  296. }
  297. /**
  298. * Return the URL of the file
  299. *
  300. * @return string
  301. */
  302. public function getUrl() {
  303. if ( !isset( $this->url ) ) {
  304. $this->assertRepoDefined();
  305. $ext = $this->getExtension();
  306. $this->url = $this->repo->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
  307. }
  308. return $this->url;
  309. }
  310. /**
  311. * Get short description URL for a files based on the page ID
  312. *
  313. * @return string|null
  314. * @since 1.27
  315. */
  316. public function getDescriptionShortUrl() {
  317. return null;
  318. }
  319. /**
  320. * Return a fully-qualified URL to the file.
  321. * Upload URL paths _may or may not_ be fully qualified, so
  322. * we check. Local paths are assumed to belong on $wgServer.
  323. *
  324. * @return string
  325. */
  326. public function getFullUrl() {
  327. return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE );
  328. }
  329. /**
  330. * @return string
  331. */
  332. public function getCanonicalUrl() {
  333. return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL );
  334. }
  335. /**
  336. * @return string
  337. */
  338. function getViewURL() {
  339. if ( $this->mustRender() ) {
  340. if ( $this->canRender() ) {
  341. return $this->createThumb( $this->getWidth() );
  342. } else {
  343. wfDebug( __METHOD__ . ': supposed to render ' . $this->getName() .
  344. ' (' . $this->getMimeType() . "), but can't!\n" );
  345. return $this->getUrl(); # hm... return NULL?
  346. }
  347. } else {
  348. return $this->getUrl();
  349. }
  350. }
  351. /**
  352. * Return the storage path to the file. Note that this does
  353. * not mean that a file actually exists under that location.
  354. *
  355. * This path depends on whether directory hashing is active or not,
  356. * i.e. whether the files are all found in the same directory,
  357. * or in hashed paths like /images/3/3c.
  358. *
  359. * Most callers don't check the return value, but ForeignAPIFile::getPath
  360. * returns false.
  361. *
  362. * @return string|bool ForeignAPIFile::getPath can return false
  363. */
  364. public function getPath() {
  365. if ( !isset( $this->path ) ) {
  366. $this->assertRepoDefined();
  367. $this->path = $this->repo->getZonePath( 'public' ) . '/' . $this->getRel();
  368. }
  369. return $this->path;
  370. }
  371. /**
  372. * Get an FS copy or original of this file and return the path.
  373. * Returns false on failure. Callers must not alter the file.
  374. * Temporary files are cleared automatically.
  375. *
  376. * @return string|bool False on failure
  377. */
  378. public function getLocalRefPath() {
  379. $this->assertRepoDefined();
  380. if ( !isset( $this->fsFile ) ) {
  381. $starttime = microtime( true );
  382. $this->fsFile = $this->repo->getLocalReference( $this->getPath() );
  383. $statTiming = microtime( true ) - $starttime;
  384. MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
  385. 'media.thumbnail.generate.fetchoriginal', 1000 * $statTiming );
  386. if ( !$this->fsFile ) {
  387. $this->fsFile = false; // null => false; cache negative hits
  388. }
  389. }
  390. return ( $this->fsFile )
  391. ? $this->fsFile->getPath()
  392. : false;
  393. }
  394. /**
  395. * Return the width of the image. Returns false if the width is unknown
  396. * or undefined.
  397. *
  398. * STUB
  399. * Overridden by LocalFile, UnregisteredLocalFile
  400. *
  401. * @param int $page
  402. * @return int|bool
  403. */
  404. public function getWidth( $page = 1 ) {
  405. return false;
  406. }
  407. /**
  408. * Return the height of the image. Returns false if the height is unknown
  409. * or undefined
  410. *
  411. * STUB
  412. * Overridden by LocalFile, UnregisteredLocalFile
  413. *
  414. * @param int $page
  415. * @return bool|int False on failure
  416. */
  417. public function getHeight( $page = 1 ) {
  418. return false;
  419. }
  420. /**
  421. * Return the smallest bucket from $wgThumbnailBuckets which is at least
  422. * $wgThumbnailMinimumBucketDistance larger than $desiredWidth. The returned bucket, if any,
  423. * will always be bigger than $desiredWidth.
  424. *
  425. * @param int $desiredWidth
  426. * @param int $page
  427. * @return bool|int
  428. */
  429. public function getThumbnailBucket( $desiredWidth, $page = 1 ) {
  430. global $wgThumbnailBuckets, $wgThumbnailMinimumBucketDistance;
  431. $imageWidth = $this->getWidth( $page );
  432. if ( $imageWidth === false ) {
  433. return false;
  434. }
  435. if ( $desiredWidth > $imageWidth ) {
  436. return false;
  437. }
  438. if ( !$wgThumbnailBuckets ) {
  439. return false;
  440. }
  441. $sortedBuckets = $wgThumbnailBuckets;
  442. sort( $sortedBuckets );
  443. foreach ( $sortedBuckets as $bucket ) {
  444. if ( $bucket >= $imageWidth ) {
  445. return false;
  446. }
  447. if ( $bucket - $wgThumbnailMinimumBucketDistance > $desiredWidth ) {
  448. return $bucket;
  449. }
  450. }
  451. // Image is bigger than any available bucket
  452. return false;
  453. }
  454. /**
  455. * Returns ID or name of user who uploaded the file
  456. * STUB
  457. *
  458. * @param string $type 'text' or 'id'
  459. * @return string|int
  460. */
  461. public function getUser( $type = 'text' ) {
  462. return null;
  463. }
  464. /**
  465. * Get the duration of a media file in seconds
  466. *
  467. * @return float|int
  468. */
  469. public function getLength() {
  470. $handler = $this->getHandler();
  471. if ( $handler ) {
  472. return $handler->getLength( $this );
  473. } else {
  474. return 0;
  475. }
  476. }
  477. /**
  478. * Return true if the file is vectorized
  479. *
  480. * @return bool
  481. */
  482. public function isVectorized() {
  483. $handler = $this->getHandler();
  484. if ( $handler ) {
  485. return $handler->isVectorized( $this );
  486. } else {
  487. return false;
  488. }
  489. }
  490. /**
  491. * Gives a (possibly empty) list of languages to render
  492. * the file in.
  493. *
  494. * If the file doesn't have translations, or if the file
  495. * format does not support that sort of thing, returns
  496. * an empty array.
  497. *
  498. * @return string[]
  499. * @since 1.23
  500. */
  501. public function getAvailableLanguages() {
  502. $handler = $this->getHandler();
  503. if ( $handler ) {
  504. return $handler->getAvailableLanguages( $this );
  505. } else {
  506. return [];
  507. }
  508. }
  509. /**
  510. * Get the language code from the available languages for this file that matches the language
  511. * requested by the user
  512. *
  513. * @param string $userPreferredLanguage
  514. * @return string|null
  515. */
  516. public function getMatchedLanguage( $userPreferredLanguage ) {
  517. $handler = $this->getHandler();
  518. if ( $handler && method_exists( $handler, 'getMatchedLanguage' ) ) {
  519. return $handler->getMatchedLanguage(
  520. $userPreferredLanguage,
  521. $handler->getAvailableLanguages( $this )
  522. );
  523. } else {
  524. return null;
  525. }
  526. }
  527. /**
  528. * In files that support multiple language, what is the default language
  529. * to use if none specified.
  530. *
  531. * @return string|null Lang code, or null if filetype doesn't support multiple languages.
  532. * @since 1.23
  533. */
  534. public function getDefaultRenderLanguage() {
  535. $handler = $this->getHandler();
  536. if ( $handler ) {
  537. return $handler->getDefaultRenderLanguage( $this );
  538. } else {
  539. return null;
  540. }
  541. }
  542. /**
  543. * Will the thumbnail be animated if one would expect it to be.
  544. *
  545. * Currently used to add a warning to the image description page
  546. *
  547. * @return bool False if the main image is both animated
  548. * and the thumbnail is not. In all other cases must return
  549. * true. If image is not renderable whatsoever, should
  550. * return true.
  551. */
  552. public function canAnimateThumbIfAppropriate() {
  553. $handler = $this->getHandler();
  554. if ( !$handler ) {
  555. // We cannot handle image whatsoever, thus
  556. // one would not expect it to be animated
  557. // so true.
  558. return true;
  559. } else {
  560. if ( $this->allowInlineDisplay()
  561. && $handler->isAnimatedImage( $this )
  562. && !$handler->canAnimateThumbnail( $this )
  563. ) {
  564. // Image is animated, but thumbnail isn't.
  565. // This is unexpected to the user.
  566. return false;
  567. } else {
  568. // Image is not animated, so one would
  569. // not expect thumb to be
  570. return true;
  571. }
  572. }
  573. }
  574. /**
  575. * Get handler-specific metadata
  576. * Overridden by LocalFile, UnregisteredLocalFile
  577. * STUB
  578. * @return bool|array
  579. */
  580. public function getMetadata() {
  581. return false;
  582. }
  583. /**
  584. * Like getMetadata but returns a handler independent array of common values.
  585. * @see MediaHandler::getCommonMetaArray()
  586. * @return array|bool Array or false if not supported
  587. * @since 1.23
  588. */
  589. public function getCommonMetaArray() {
  590. $handler = $this->getHandler();
  591. if ( !$handler ) {
  592. return false;
  593. }
  594. return $handler->getCommonMetaArray( $this );
  595. }
  596. /**
  597. * get versioned metadata
  598. *
  599. * @param array|string $metadata Array or string of (serialized) metadata
  600. * @param int $version Version number.
  601. * @return array Array containing metadata, or what was passed to it on fail
  602. * (unserializing if not array)
  603. */
  604. public function convertMetadataVersion( $metadata, $version ) {
  605. $handler = $this->getHandler();
  606. if ( !is_array( $metadata ) ) {
  607. // Just to make the return type consistent
  608. $metadata = unserialize( $metadata );
  609. }
  610. if ( $handler ) {
  611. return $handler->convertMetadataVersion( $metadata, $version );
  612. } else {
  613. return $metadata;
  614. }
  615. }
  616. /**
  617. * Return the bit depth of the file
  618. * Overridden by LocalFile
  619. * STUB
  620. * @return int
  621. */
  622. public function getBitDepth() {
  623. return 0;
  624. }
  625. /**
  626. * Return the size of the image file, in bytes
  627. * Overridden by LocalFile, UnregisteredLocalFile
  628. * STUB
  629. * @return bool
  630. */
  631. public function getSize() {
  632. return false;
  633. }
  634. /**
  635. * Returns the MIME type of the file.
  636. * Overridden by LocalFile, UnregisteredLocalFile
  637. * STUB
  638. *
  639. * @return string
  640. */
  641. function getMimeType() {
  642. return 'unknown/unknown';
  643. }
  644. /**
  645. * Return the type of the media in the file.
  646. * Use the value returned by this function with the MEDIATYPE_xxx constants.
  647. * Overridden by LocalFile,
  648. * STUB
  649. * @return string
  650. */
  651. function getMediaType() {
  652. return MEDIATYPE_UNKNOWN;
  653. }
  654. /**
  655. * Checks if the output of transform() for this file is likely
  656. * to be valid. If this is false, various user elements will
  657. * display a placeholder instead.
  658. *
  659. * Currently, this checks if the file is an image format
  660. * that can be converted to a format
  661. * supported by all browsers (namely GIF, PNG and JPEG),
  662. * or if it is an SVG image and SVG conversion is enabled.
  663. *
  664. * @return bool
  665. */
  666. function canRender() {
  667. if ( !isset( $this->canRender ) ) {
  668. $this->canRender = $this->getHandler() && $this->handler->canRender( $this ) && $this->exists();
  669. }
  670. return $this->canRender;
  671. }
  672. /**
  673. * Accessor for __get()
  674. * @return bool
  675. */
  676. protected function getCanRender() {
  677. return $this->canRender();
  678. }
  679. /**
  680. * Return true if the file is of a type that can't be directly
  681. * rendered by typical browsers and needs to be re-rasterized.
  682. *
  683. * This returns true for everything but the bitmap types
  684. * supported by all browsers, i.e. JPEG; GIF and PNG. It will
  685. * also return true for any non-image formats.
  686. *
  687. * @return bool
  688. */
  689. function mustRender() {
  690. return $this->getHandler() && $this->handler->mustRender( $this );
  691. }
  692. /**
  693. * Alias for canRender()
  694. *
  695. * @return bool
  696. */
  697. function allowInlineDisplay() {
  698. return $this->canRender();
  699. }
  700. /**
  701. * Determines if this media file is in a format that is unlikely to
  702. * contain viruses or malicious content. It uses the global
  703. * $wgTrustedMediaFormats list to determine if the file is safe.
  704. *
  705. * This is used to show a warning on the description page of non-safe files.
  706. * It may also be used to disallow direct [[media:...]] links to such files.
  707. *
  708. * Note that this function will always return true if allowInlineDisplay()
  709. * or isTrustedFile() is true for this file.
  710. *
  711. * @return bool
  712. */
  713. function isSafeFile() {
  714. if ( !isset( $this->isSafeFile ) ) {
  715. $this->isSafeFile = $this->getIsSafeFileUncached();
  716. }
  717. return $this->isSafeFile;
  718. }
  719. /**
  720. * Accessor for __get()
  721. *
  722. * @return bool
  723. */
  724. protected function getIsSafeFile() {
  725. return $this->isSafeFile();
  726. }
  727. /**
  728. * Uncached accessor
  729. *
  730. * @return bool
  731. */
  732. protected function getIsSafeFileUncached() {
  733. global $wgTrustedMediaFormats;
  734. if ( $this->allowInlineDisplay() ) {
  735. return true;
  736. }
  737. if ( $this->isTrustedFile() ) {
  738. return true;
  739. }
  740. $type = $this->getMediaType();
  741. $mime = $this->getMimeType();
  742. # wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
  743. if ( !$type || $type === MEDIATYPE_UNKNOWN ) {
  744. return false; # unknown type, not trusted
  745. }
  746. if ( in_array( $type, $wgTrustedMediaFormats ) ) {
  747. return true;
  748. }
  749. if ( $mime === "unknown/unknown" ) {
  750. return false; # unknown type, not trusted
  751. }
  752. if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
  753. return true;
  754. }
  755. return false;
  756. }
  757. /**
  758. * Returns true if the file is flagged as trusted. Files flagged that way
  759. * can be linked to directly, even if that is not allowed for this type of
  760. * file normally.
  761. *
  762. * This is a dummy function right now and always returns false. It could be
  763. * implemented to extract a flag from the database. The trusted flag could be
  764. * set on upload, if the user has sufficient privileges, to bypass script-
  765. * and html-filters. It may even be coupled with cryptographics signatures
  766. * or such.
  767. *
  768. * @return bool
  769. */
  770. function isTrustedFile() {
  771. # this could be implemented to check a flag in the database,
  772. # look for signatures, etc
  773. return false;
  774. }
  775. /**
  776. * Load any lazy-loaded file object fields from source
  777. *
  778. * This is only useful when setting $flags
  779. *
  780. * Overridden by LocalFile to actually query the DB
  781. *
  782. * @param int $flags Bitfield of File::READ_* constants
  783. */
  784. public function load( $flags = 0 ) {
  785. }
  786. /**
  787. * Returns true if file exists in the repository.
  788. *
  789. * Overridden by LocalFile to avoid unnecessary stat calls.
  790. *
  791. * @return bool Whether file exists in the repository.
  792. */
  793. public function exists() {
  794. return $this->getPath() && $this->repo->fileExists( $this->path );
  795. }
  796. /**
  797. * Returns true if file exists in the repository and can be included in a page.
  798. * It would be unsafe to include private images, making public thumbnails inadvertently
  799. *
  800. * @return bool Whether file exists in the repository and is includable.
  801. */
  802. public function isVisible() {
  803. return $this->exists();
  804. }
  805. /**
  806. * @return string
  807. */
  808. function getTransformScript() {
  809. if ( !isset( $this->transformScript ) ) {
  810. $this->transformScript = false;
  811. if ( $this->repo ) {
  812. $script = $this->repo->getThumbScriptUrl();
  813. if ( $script ) {
  814. $this->transformScript = wfAppendQuery( $script, [ 'f' => $this->getName() ] );
  815. }
  816. }
  817. }
  818. return $this->transformScript;
  819. }
  820. /**
  821. * Get a ThumbnailImage which is the same size as the source
  822. *
  823. * @param array $handlerParams
  824. *
  825. * @return ThumbnailImage|MediaTransformOutput|bool False on failure
  826. */
  827. function getUnscaledThumb( $handlerParams = [] ) {
  828. $hp =& $handlerParams;
  829. $page = $hp['page'] ?? false;
  830. $width = $this->getWidth( $page );
  831. if ( !$width ) {
  832. return $this->iconThumb();
  833. }
  834. $hp['width'] = $width;
  835. // be sure to ignore any height specification as well (T64258)
  836. unset( $hp['height'] );
  837. return $this->transform( $hp );
  838. }
  839. /**
  840. * Return the file name of a thumbnail with the specified parameters.
  841. * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
  842. * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
  843. *
  844. * @param array $params Handler-specific parameters
  845. * @param int $flags Bitfield that supports THUMB_* constants
  846. * @return string|null
  847. */
  848. public function thumbName( $params, $flags = 0 ) {
  849. $name = ( $this->repo && !( $flags & self::THUMB_FULL_NAME ) )
  850. ? $this->repo->nameForThumb( $this->getName() )
  851. : $this->getName();
  852. return $this->generateThumbName( $name, $params );
  853. }
  854. /**
  855. * Generate a thumbnail file name from a name and specified parameters
  856. *
  857. * @param string $name
  858. * @param array $params Parameters which will be passed to MediaHandler::makeParamString
  859. * @return string|null
  860. */
  861. public function generateThumbName( $name, $params ) {
  862. if ( !$this->getHandler() ) {
  863. return null;
  864. }
  865. $extension = $this->getExtension();
  866. list( $thumbExt, ) = $this->getHandler()->getThumbType(
  867. $extension, $this->getMimeType(), $params );
  868. $thumbName = $this->getHandler()->makeParamString( $params );
  869. if ( $this->repo->supportsSha1URLs() ) {
  870. $thumbName .= '-' . $this->getSha1() . '.' . $thumbExt;
  871. } else {
  872. $thumbName .= '-' . $name;
  873. if ( $thumbExt != $extension ) {
  874. $thumbName .= ".$thumbExt";
  875. }
  876. }
  877. return $thumbName;
  878. }
  879. /**
  880. * Create a thumbnail of the image having the specified width/height.
  881. * The thumbnail will not be created if the width is larger than the
  882. * image's width. Let the browser do the scaling in this case.
  883. * The thumbnail is stored on disk and is only computed if the thumbnail
  884. * file does not exist OR if it is older than the image.
  885. * Returns the URL.
  886. *
  887. * Keeps aspect ratio of original image. If both width and height are
  888. * specified, the generated image will be no bigger than width x height,
  889. * and will also have correct aspect ratio.
  890. *
  891. * @param int $width Maximum width of the generated thumbnail
  892. * @param int $height Maximum height of the image (optional)
  893. *
  894. * @return string
  895. */
  896. public function createThumb( $width, $height = -1 ) {
  897. $params = [ 'width' => $width ];
  898. if ( $height != -1 ) {
  899. $params['height'] = $height;
  900. }
  901. $thumb = $this->transform( $params );
  902. if ( !$thumb || $thumb->isError() ) {
  903. return '';
  904. }
  905. return $thumb->getUrl();
  906. }
  907. /**
  908. * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
  909. *
  910. * @param string $thumbPath Thumbnail storage path
  911. * @param string $thumbUrl Thumbnail URL
  912. * @param array $params
  913. * @param int $flags
  914. * @return MediaTransformOutput
  915. */
  916. protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
  917. global $wgIgnoreImageErrors;
  918. $handler = $this->getHandler();
  919. if ( $handler && $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
  920. return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
  921. } else {
  922. return new MediaTransformError( 'thumbnail_error',
  923. $params['width'], 0, wfMessage( 'thumbnail-dest-create' ) );
  924. }
  925. }
  926. /**
  927. * Transform a media file
  928. *
  929. * @param array $params An associative array of handler-specific parameters.
  930. * Typical keys are width, height and page.
  931. * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
  932. * @return ThumbnailImage|MediaTransformOutput|bool False on failure
  933. */
  934. function transform( $params, $flags = 0 ) {
  935. global $wgThumbnailEpoch;
  936. do {
  937. if ( !$this->canRender() ) {
  938. $thumb = $this->iconThumb();
  939. break; // not a bitmap or renderable image, don't try
  940. }
  941. // Get the descriptionUrl to embed it as comment into the thumbnail. T21791.
  942. $descriptionUrl = $this->getDescriptionUrl();
  943. if ( $descriptionUrl ) {
  944. $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL );
  945. }
  946. $handler = $this->getHandler();
  947. $script = $this->getTransformScript();
  948. if ( $script && !( $flags & self::RENDER_NOW ) ) {
  949. // Use a script to transform on client request, if possible
  950. $thumb = $handler->getScriptedTransform( $this, $script, $params );
  951. if ( $thumb ) {
  952. break;
  953. }
  954. }
  955. $normalisedParams = $params;
  956. $handler->normaliseParams( $this, $normalisedParams );
  957. $thumbName = $this->thumbName( $normalisedParams );
  958. $thumbUrl = $this->getThumbUrl( $thumbName );
  959. $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
  960. if ( $this->repo ) {
  961. // Defer rendering if a 404 handler is set up...
  962. if ( $this->repo->canTransformVia404() && !( $flags & self::RENDER_NOW ) ) {
  963. // XXX: Pass in the storage path even though we are not rendering anything
  964. // and the path is supposed to be an FS path. This is due to getScalerType()
  965. // getting called on the path and clobbering $thumb->getUrl() if it's false.
  966. $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
  967. break;
  968. }
  969. // Check if an up-to-date thumbnail already exists...
  970. wfDebug( __METHOD__ . ": Doing stat for $thumbPath\n" );
  971. if ( !( $flags & self::RENDER_FORCE ) && $this->repo->fileExists( $thumbPath ) ) {
  972. $timestamp = $this->repo->getFileTimestamp( $thumbPath );
  973. if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
  974. // XXX: Pass in the storage path even though we are not rendering anything
  975. // and the path is supposed to be an FS path. This is due to getScalerType()
  976. // getting called on the path and clobbering $thumb->getUrl() if it's false.
  977. $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
  978. $thumb->setStoragePath( $thumbPath );
  979. break;
  980. }
  981. } elseif ( $flags & self::RENDER_FORCE ) {
  982. wfDebug( __METHOD__ . " forcing rendering per flag File::RENDER_FORCE\n" );
  983. }
  984. // If the backend is ready-only, don't keep generating thumbnails
  985. // only to return transformation errors, just return the error now.
  986. if ( $this->repo->getReadOnlyReason() !== false ) {
  987. $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
  988. break;
  989. }
  990. }
  991. $tmpFile = $this->makeTransformTmpFile( $thumbPath );
  992. if ( !$tmpFile ) {
  993. $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
  994. } else {
  995. $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
  996. }
  997. } while ( false );
  998. return is_object( $thumb ) ? $thumb : false;
  999. }
  1000. /**
  1001. * Generates a thumbnail according to the given parameters and saves it to storage
  1002. * @param TempFSFile $tmpFile Temporary file where the rendered thumbnail will be saved
  1003. * @param array $transformParams
  1004. * @param int $flags
  1005. * @return bool|MediaTransformOutput
  1006. */
  1007. public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
  1008. global $wgIgnoreImageErrors;
  1009. $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
  1010. $handler = $this->getHandler();
  1011. $normalisedParams = $transformParams;
  1012. $handler->normaliseParams( $this, $normalisedParams );
  1013. $thumbName = $this->thumbName( $normalisedParams );
  1014. $thumbUrl = $this->getThumbUrl( $thumbName );
  1015. $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
  1016. $tmpThumbPath = $tmpFile->getPath();
  1017. if ( $handler->supportsBucketing() ) {
  1018. $this->generateBucketsIfNeeded( $normalisedParams, $flags );
  1019. }
  1020. $starttime = microtime( true );
  1021. // Actually render the thumbnail...
  1022. $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
  1023. $tmpFile->bind( $thumb ); // keep alive with $thumb
  1024. $statTiming = microtime( true ) - $starttime;
  1025. $stats->timing( 'media.thumbnail.generate.transform', 1000 * $statTiming );
  1026. if ( !$thumb ) { // bad params?
  1027. $thumb = false;
  1028. } elseif ( $thumb->isError() ) { // transform error
  1029. /** @var MediaTransformError $thumb */
  1030. $this->lastError = $thumb->toText();
  1031. // Ignore errors if requested
  1032. if ( $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
  1033. $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
  1034. }
  1035. } elseif ( $this->repo && $thumb->hasFile() && !$thumb->fileIsSource() ) {
  1036. // Copy the thumbnail from the file system into storage...
  1037. $starttime = microtime( true );
  1038. $disposition = $this->getThumbDisposition( $thumbName );
  1039. $status = $this->repo->quickImport( $tmpThumbPath, $thumbPath, $disposition );
  1040. if ( $status->isOK() ) {
  1041. $thumb->setStoragePath( $thumbPath );
  1042. } else {
  1043. $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
  1044. }
  1045. $statTiming = microtime( true ) - $starttime;
  1046. $stats->timing( 'media.thumbnail.generate.store', 1000 * $statTiming );
  1047. // Give extensions a chance to do something with this thumbnail...
  1048. Hooks::run( 'FileTransformed', [ $this, $thumb, $tmpThumbPath, $thumbPath ] );
  1049. }
  1050. return $thumb;
  1051. }
  1052. /**
  1053. * Generates chained bucketed thumbnails if needed
  1054. * @param array $params
  1055. * @param int $flags
  1056. * @return bool Whether at least one bucket was generated
  1057. */
  1058. protected function generateBucketsIfNeeded( $params, $flags = 0 ) {
  1059. if ( !$this->repo
  1060. || !isset( $params['physicalWidth'] )
  1061. || !isset( $params['physicalHeight'] )
  1062. ) {
  1063. return false;
  1064. }
  1065. $bucket = $this->getThumbnailBucket( $params['physicalWidth'] );
  1066. if ( !$bucket || $bucket == $params['physicalWidth'] ) {
  1067. return false;
  1068. }
  1069. $bucketPath = $this->getBucketThumbPath( $bucket );
  1070. if ( $this->repo->fileExists( $bucketPath ) ) {
  1071. return false;
  1072. }
  1073. $starttime = microtime( true );
  1074. $params['physicalWidth'] = $bucket;
  1075. $params['width'] = $bucket;
  1076. $params = $this->getHandler()->sanitizeParamsForBucketing( $params );
  1077. $tmpFile = $this->makeTransformTmpFile( $bucketPath );
  1078. if ( !$tmpFile ) {
  1079. return false;
  1080. }
  1081. $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
  1082. $buckettime = microtime( true ) - $starttime;
  1083. if ( !$thumb || $thumb->isError() ) {
  1084. return false;
  1085. }
  1086. $this->tmpBucketedThumbCache[$bucket] = $tmpFile->getPath();
  1087. // For the caching to work, we need to make the tmp file survive as long as
  1088. // this object exists
  1089. $tmpFile->bind( $this );
  1090. MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
  1091. 'media.thumbnail.generate.bucket', 1000 * $buckettime );
  1092. return true;
  1093. }
  1094. /**
  1095. * Returns the most appropriate source image for the thumbnail, given a target thumbnail size
  1096. * @param array $params
  1097. * @return array Source path and width/height of the source
  1098. */
  1099. public function getThumbnailSource( $params ) {
  1100. if ( $this->repo
  1101. && $this->getHandler()->supportsBucketing()
  1102. && isset( $params['physicalWidth'] )
  1103. && $bucket = $this->getThumbnailBucket( $params['physicalWidth'] )
  1104. ) {
  1105. if ( $this->getWidth() != 0 ) {
  1106. $bucketHeight = round( $this->getHeight() * ( $bucket / $this->getWidth() ) );
  1107. } else {
  1108. $bucketHeight = 0;
  1109. }
  1110. // Try to avoid reading from storage if the file was generated by this script
  1111. if ( isset( $this->tmpBucketedThumbCache[$bucket] ) ) {
  1112. $tmpPath = $this->tmpBucketedThumbCache[$bucket];
  1113. if ( file_exists( $tmpPath ) ) {
  1114. return [
  1115. 'path' => $tmpPath,
  1116. 'width' => $bucket,
  1117. 'height' => $bucketHeight
  1118. ];
  1119. }
  1120. }
  1121. $bucketPath = $this->getBucketThumbPath( $bucket );
  1122. if ( $this->repo->fileExists( $bucketPath ) ) {
  1123. $fsFile = $this->repo->getLocalReference( $bucketPath );
  1124. if ( $fsFile ) {
  1125. return [
  1126. 'path' => $fsFile->getPath(),
  1127. 'width' => $bucket,
  1128. 'height' => $bucketHeight
  1129. ];
  1130. }
  1131. }
  1132. }
  1133. // Thumbnailing a very large file could result in network saturation if
  1134. // everyone does it at once.
  1135. if ( $this->getSize() >= 1e7 ) { // 10MB
  1136. $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $this->getName() ),
  1137. [
  1138. 'doWork' => function () {
  1139. return $this->getLocalRefPath();
  1140. }
  1141. ]
  1142. );
  1143. $srcPath = $work->execute();
  1144. } else {
  1145. $srcPath = $this->getLocalRefPath();
  1146. }
  1147. // Original file
  1148. return [
  1149. 'path' => $srcPath,
  1150. 'width' => $this->getWidth(),
  1151. 'height' => $this->getHeight()
  1152. ];
  1153. }
  1154. /**
  1155. * Returns the repo path of the thumb for a given bucket
  1156. * @param int $bucket
  1157. * @return string
  1158. */
  1159. protected function getBucketThumbPath( $bucket ) {
  1160. $thumbName = $this->getBucketThumbName( $bucket );
  1161. return $this->getThumbPath( $thumbName );
  1162. }
  1163. /**
  1164. * Returns the name of the thumb for a given bucket
  1165. * @param int $bucket
  1166. * @return string
  1167. */
  1168. protected function getBucketThumbName( $bucket ) {
  1169. return $this->thumbName( [ 'physicalWidth' => $bucket ] );
  1170. }
  1171. /**
  1172. * Creates a temp FS file with the same extension and the thumbnail
  1173. * @param string $thumbPath Thumbnail path
  1174. * @return TempFSFile|null
  1175. */
  1176. protected function makeTransformTmpFile( $thumbPath ) {
  1177. $thumbExt = FileBackend::extensionFromPath( $thumbPath );
  1178. return TempFSFile::factory( 'transform_', $thumbExt, wfTempDir() );
  1179. }
  1180. /**
  1181. * @param string $thumbName Thumbnail name
  1182. * @param string $dispositionType Type of disposition (either "attachment" or "inline")
  1183. * @return string Content-Disposition header value
  1184. */
  1185. function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
  1186. $fileName = $this->name; // file name to suggest
  1187. $thumbExt = FileBackend::extensionFromPath( $thumbName );
  1188. if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
  1189. $fileName .= ".$thumbExt";
  1190. }
  1191. return FileBackend::makeContentDisposition( $dispositionType, $fileName );
  1192. }
  1193. /**
  1194. * Hook into transform() to allow migration of thumbnail files
  1195. * STUB
  1196. * Overridden by LocalFile
  1197. * @param string $thumbName
  1198. */
  1199. function migrateThumbFile( $thumbName ) {
  1200. }
  1201. /**
  1202. * Get a MediaHandler instance for this file
  1203. *
  1204. * @return MediaHandler|bool Registered MediaHandler for file's MIME type
  1205. * or false if none found
  1206. */
  1207. function getHandler() {
  1208. if ( !isset( $this->handler ) ) {
  1209. $this->handler = MediaHandler::getHandler( $this->getMimeType() );
  1210. }
  1211. return $this->handler;
  1212. }
  1213. /**
  1214. * Get a ThumbnailImage representing a file type icon
  1215. *
  1216. * @return ThumbnailImage
  1217. */
  1218. function iconThumb() {
  1219. global $wgResourceBasePath, $IP;
  1220. $assetsPath = "$wgResourceBasePath/resources/assets/file-type-icons/";
  1221. $assetsDirectory = "$IP/resources/assets/file-type-icons/";
  1222. $try = [ 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' ];
  1223. foreach ( $try as $icon ) {
  1224. if ( file_exists( $assetsDirectory . $icon ) ) { // always FS
  1225. $params = [ 'width' => 120, 'height' => 120 ];
  1226. return new ThumbnailImage( $this, $assetsPath . $icon, false, $params );
  1227. }
  1228. }
  1229. return null;
  1230. }
  1231. /**
  1232. * Get last thumbnailing error.
  1233. * Largely obsolete.
  1234. * @return string
  1235. */
  1236. function getLastError() {
  1237. return $this->lastError;
  1238. }
  1239. /**
  1240. * Get all thumbnail names previously generated for this file
  1241. * STUB
  1242. * Overridden by LocalFile
  1243. * @return string[]
  1244. */
  1245. function getThumbnails() {
  1246. return [];
  1247. }
  1248. /**
  1249. * Purge shared caches such as thumbnails and DB data caching
  1250. * STUB
  1251. * Overridden by LocalFile
  1252. * @param array $options Options, which include:
  1253. * 'forThumbRefresh' : The purging is only to refresh thumbnails
  1254. */
  1255. function purgeCache( $options = [] ) {
  1256. }
  1257. /**
  1258. * Purge the file description page, but don't go after
  1259. * pages using the file. Use when modifying file history
  1260. * but not the current data.
  1261. */
  1262. function purgeDescription() {
  1263. $title = $this->getTitle();
  1264. if ( $title ) {
  1265. $title->invalidateCache();
  1266. $title->purgeSquid();
  1267. }
  1268. }
  1269. /**
  1270. * Purge metadata and all affected pages when the file is created,
  1271. * deleted, or majorly updated.
  1272. */
  1273. function purgeEverything() {
  1274. // Delete thumbnails and refresh file metadata cache
  1275. $this->purgeCache();
  1276. $this->purgeDescription();
  1277. // Purge cache of all pages using this file
  1278. $title = $this->getTitle();
  1279. if ( $title ) {
  1280. DeferredUpdates::addUpdate(
  1281. new HTMLCacheUpdate( $title, 'imagelinks', 'file-purge' )
  1282. );
  1283. }
  1284. }
  1285. /**
  1286. * Return a fragment of the history of file.
  1287. *
  1288. * STUB
  1289. * @param int|null $limit Limit of rows to return
  1290. * @param string|int|null $start Only revisions older than $start will be returned
  1291. * @param string|int|null $end Only revisions newer than $end will be returned
  1292. * @param bool $inc Include the endpoints of the time range
  1293. *
  1294. * @return File[]
  1295. */
  1296. function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
  1297. return [];
  1298. }
  1299. /**
  1300. * Return the history of this file, line by line. Starts with current version,
  1301. * then old versions. Should return an object similar to an image/oldimage
  1302. * database row.
  1303. *
  1304. * STUB
  1305. * Overridden in LocalFile
  1306. * @return bool
  1307. */
  1308. public function nextHistoryLine() {
  1309. return false;
  1310. }
  1311. /**
  1312. * Reset the history pointer to the first element of the history.
  1313. * Always call this function after using nextHistoryLine() to free db resources
  1314. * STUB
  1315. * Overridden in LocalFile.
  1316. */
  1317. public function resetHistory() {
  1318. }
  1319. /**
  1320. * Get the filename hash component of the directory including trailing slash,
  1321. * e.g. f/fa/
  1322. * If the repository is not hashed, returns an empty string.
  1323. *
  1324. * @return string
  1325. */
  1326. function getHashPath() {
  1327. if ( !isset( $this->hashPath ) ) {
  1328. $this->assertRepoDefined();
  1329. $this->hashPath = $this->repo->getHashPath( $this->getName() );
  1330. }
  1331. return $this->hashPath;
  1332. }
  1333. /**
  1334. * Get the path of the file relative to the public zone root.
  1335. * This function is overridden in OldLocalFile to be like getArchiveRel().
  1336. *
  1337. * @return string
  1338. */
  1339. function getRel() {
  1340. return $this->getHashPath() . $this->getName();
  1341. }
  1342. /**
  1343. * Get the path of an archived file relative to the public zone root
  1344. *
  1345. * @param bool|string $suffix If not false, the name of an archived thumbnail file
  1346. *
  1347. * @return string
  1348. */
  1349. function getArchiveRel( $suffix = false ) {
  1350. $path = 'archive/' . $this->getHashPath();
  1351. if ( $suffix === false ) {
  1352. $path = substr( $path, 0, -1 );
  1353. } else {
  1354. $path .= $suffix;
  1355. }
  1356. return $path;
  1357. }
  1358. /**
  1359. * Get the path, relative to the thumbnail zone root, of the
  1360. * thumbnail directory or a particular file if $suffix is specified
  1361. *
  1362. * @param bool|string $suffix If not false, the name of a thumbnail file
  1363. * @return string
  1364. */
  1365. function getThumbRel( $suffix = false ) {
  1366. $path = $this->getRel();
  1367. if ( $suffix !== false ) {
  1368. $path .= '/' . $suffix;
  1369. }
  1370. return $path;
  1371. }
  1372. /**
  1373. * Get urlencoded path of the file relative to the public zone root.
  1374. * This function is overridden in OldLocalFile to be like getArchiveUrl().
  1375. *
  1376. * @return string
  1377. */
  1378. function getUrlRel() {
  1379. return $this->getHashPath() . rawurlencode( $this->getName() );
  1380. }
  1381. /**
  1382. * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
  1383. * or a specific thumb if the $suffix is given.
  1384. *
  1385. * @param string $archiveName The timestamped name of an archived image
  1386. * @param bool|string $suffix If not false, the name of a thumbnail file
  1387. * @return string
  1388. */
  1389. function getArchiveThumbRel( $archiveName, $suffix = false ) {
  1390. $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
  1391. if ( $suffix === false ) {
  1392. $path = substr( $path, 0, -1 );
  1393. } else {
  1394. $path .= $suffix;
  1395. }
  1396. return $path;
  1397. }
  1398. /**
  1399. * Get the path of the archived file.
  1400. *
  1401. * @param bool|string $suffix If not false, the name of an archived file.
  1402. * @return string
  1403. */
  1404. function getArchivePath( $suffix = false ) {
  1405. $this->assertRepoDefined();
  1406. return $this->repo->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
  1407. }
  1408. /**
  1409. * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
  1410. *
  1411. * @param string $archiveName The timestamped name of an archived image
  1412. * @param bool|string $suffix If not false, the name of a thumbnail file
  1413. * @return string
  1414. */
  1415. function getArchiveThumbPath( $archiveName, $suffix = false ) {
  1416. $this->assertRepoDefined();
  1417. return $this->repo->getZonePath( 'thumb' ) . '/' .
  1418. $this->getArchiveThumbRel( $archiveName, $suffix );
  1419. }
  1420. /**
  1421. * Get the path of the thumbnail directory, or a particular file if $suffix is specified
  1422. *
  1423. * @param bool|string $suffix If not false, the name of a thumbnail file
  1424. * @return string
  1425. */
  1426. function getThumbPath( $suffix = false ) {
  1427. $this->assertRepoDefined();
  1428. return $this->repo->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
  1429. }
  1430. /**
  1431. * Get the path of the transcoded directory, or a particular file if $suffix is specified
  1432. *
  1433. * @param bool|string $suffix If not false, the name of a media file
  1434. * @return string
  1435. */
  1436. function getTranscodedPath( $suffix = false ) {
  1437. $this->assertRepoDefined();
  1438. return $this->repo->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
  1439. }
  1440. /**
  1441. * Get the URL of the archive directory, or a particular file if $suffix is specified
  1442. *
  1443. * @param bool|string $suffix If not false, the name of an archived file
  1444. * @return string
  1445. */
  1446. function getArchiveUrl( $suffix = false ) {
  1447. $this->assertRepoDefined();
  1448. $ext = $this->getExtension();
  1449. $path = $this->repo->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
  1450. if ( $suffix === false ) {
  1451. $path = substr( $path, 0, -1 );
  1452. } else {
  1453. $path .= rawurlencode( $suffix );
  1454. }
  1455. return $path;
  1456. }
  1457. /**
  1458. * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
  1459. *
  1460. * @param string $archiveName The timestamped name of an archived image
  1461. * @param bool|string $suffix If not false, the name of a thumbnail file
  1462. * @return string
  1463. */
  1464. function getArchiveThumbUrl( $archiveName, $suffix = false ) {
  1465. $this->assertRepoDefined();
  1466. $ext = $this->getExtension();
  1467. $path = $this->repo->getZoneUrl( 'thumb', $ext ) . '/archive/' .
  1468. $this->getHashPath() . rawurlencode( $archiveName ) . "/";
  1469. if ( $suffix === false ) {
  1470. $path = substr( $path, 0, -1 );
  1471. } else {
  1472. $path .= rawurlencode( $suffix );
  1473. }
  1474. return $path;
  1475. }
  1476. /**
  1477. * Get the URL of the zone directory, or a particular file if $suffix is specified
  1478. *
  1479. * @param string $zone Name of requested zone
  1480. * @param bool|string $suffix If not false, the name of a file in zone
  1481. * @return string Path
  1482. */
  1483. function getZoneUrl( $zone, $suffix = false ) {
  1484. $this->assertRepoDefined();
  1485. $ext = $this->getExtension();
  1486. $path = $this->repo->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
  1487. if ( $suffix !== false ) {
  1488. $path .= '/' . rawurlencode( $suffix );
  1489. }
  1490. return $path;
  1491. }
  1492. /**
  1493. * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
  1494. *
  1495. * @param bool|string $suffix If not false, the name of a thumbnail file
  1496. * @return string Path
  1497. */
  1498. function getThumbUrl( $suffix = false ) {
  1499. return $this->getZoneUrl( 'thumb', $suffix );
  1500. }
  1501. /**
  1502. * Get the URL of the transcoded directory, or a particular file if $suffix is specified
  1503. *
  1504. * @param bool|string $suffix If not false, the name of a media file
  1505. * @return string Path
  1506. */
  1507. function getTranscodedUrl( $suffix = false ) {
  1508. return $this->getZoneUrl( 'transcoded', $suffix );
  1509. }
  1510. /**
  1511. * Get the public zone virtual URL for a current version source file
  1512. *
  1513. * @param bool|string $suffix If not false, the name of a thumbnail file
  1514. * @return string
  1515. */
  1516. function getVirtualUrl( $suffix = false ) {
  1517. $this->assertRepoDefined();
  1518. $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
  1519. if ( $suffix !== false ) {
  1520. $path .= '/' . rawurlencode( $suffix );
  1521. }
  1522. return $path;
  1523. }
  1524. /**
  1525. * Get the public zone virtual URL for an archived version source file
  1526. *
  1527. * @param bool|string $suffix If not false, the name of a thumbnail file
  1528. * @return string
  1529. */
  1530. function getArchiveVirtualUrl( $suffix = false ) {
  1531. $this->assertRepoDefined();
  1532. $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
  1533. if ( $suffix === false ) {
  1534. $path = substr( $path, 0, -1 );
  1535. } else {
  1536. $path .= rawurlencode( $suffix );
  1537. }
  1538. return $path;
  1539. }
  1540. /**
  1541. * Get the virtual URL for a thumbnail file or directory
  1542. *
  1543. * @param bool|string $suffix If not false, the name of a thumbnail file
  1544. * @return string
  1545. */
  1546. function getThumbVirtualUrl( $suffix = false ) {
  1547. $this->assertRepoDefined();
  1548. $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
  1549. if ( $suffix !== false ) {
  1550. $path .= '/' . rawurlencode( $suffix );
  1551. }
  1552. return $path;
  1553. }
  1554. /**
  1555. * @return bool
  1556. */
  1557. function isHashed() {
  1558. $this->assertRepoDefined();
  1559. return (bool)$this->repo->getHashLevels();
  1560. }
  1561. /**
  1562. * @throws MWException
  1563. */
  1564. function readOnlyError() {
  1565. throw new MWException( static::class . ': write operations are not supported' );
  1566. }
  1567. /**
  1568. * Record a file upload in the upload log and the image table
  1569. * STUB
  1570. * Overridden by LocalFile
  1571. * @param string $oldver
  1572. * @param string $desc
  1573. * @param string $license
  1574. * @param string $copyStatus
  1575. * @param string $source
  1576. * @param bool $watch
  1577. * @param string|bool $timestamp
  1578. * @param null|User $user User object or null to use $wgUser
  1579. * @return bool
  1580. * @throws MWException
  1581. */
  1582. function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
  1583. $watch = false, $timestamp = false, User $user = null
  1584. ) {
  1585. $this->readOnlyError();
  1586. }
  1587. /**
  1588. * Move or copy a file to its public location. If a file exists at the
  1589. * destination, move it to an archive. Returns a Status object with
  1590. * the archive name in the "value" member on success.
  1591. *
  1592. * The archive name should be passed through to recordUpload for database
  1593. * registration.
  1594. *
  1595. * Options to $options include:
  1596. * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
  1597. *
  1598. * @param string|FSFile $src Local filesystem path to the source image
  1599. * @param int $flags A bitwise combination of:
  1600. * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
  1601. * @param array $options Optional additional parameters
  1602. * @return Status On success, the value member contains the
  1603. * archive name, or an empty string if it was a new file.
  1604. *
  1605. * STUB
  1606. * Overridden by LocalFile
  1607. */
  1608. function publish( $src, $flags = 0, array $options = [] ) {
  1609. $this->readOnlyError();
  1610. }
  1611. /**
  1612. * @param bool|IContextSource $context Context to use (optional)
  1613. * @return bool
  1614. */
  1615. function formatMetadata( $context = false ) {
  1616. if ( !$this->getHandler() ) {
  1617. return false;
  1618. }
  1619. return $this->getHandler()->formatMetadata( $this, $context );
  1620. }
  1621. /**
  1622. * Returns true if the file comes from the local file repository.
  1623. *
  1624. * @return bool
  1625. */
  1626. function isLocal() {
  1627. return $this->repo && $this->repo->isLocal();
  1628. }
  1629. /**
  1630. * Returns the name of the repository.
  1631. *
  1632. * @return string
  1633. */
  1634. function getRepoName() {
  1635. return $this->repo ? $this->repo->getName() : 'unknown';
  1636. }
  1637. /**
  1638. * Returns the repository
  1639. *
  1640. * @return FileRepo|LocalRepo|bool
  1641. */
  1642. function getRepo() {
  1643. return $this->repo;
  1644. }
  1645. /**
  1646. * Returns true if the image is an old version
  1647. * STUB
  1648. *
  1649. * @return bool
  1650. */
  1651. function isOld() {
  1652. return false;
  1653. }
  1654. /**
  1655. * Is this file a "deleted" file in a private archive?
  1656. * STUB
  1657. *
  1658. * @param int $field One of DELETED_* bitfield constants
  1659. * @return bool
  1660. */
  1661. function isDeleted( $field ) {
  1662. return false;
  1663. }
  1664. /**
  1665. * Return the deletion bitfield
  1666. * STUB
  1667. * @return int
  1668. */
  1669. function getVisibility() {
  1670. return 0;
  1671. }
  1672. /**
  1673. * Was this file ever deleted from the wiki?
  1674. *
  1675. * @return bool
  1676. */
  1677. function wasDeleted() {
  1678. $title = $this->getTitle();
  1679. return $title && $title->isDeletedQuick();
  1680. }
  1681. /**
  1682. * Move file to the new title
  1683. *
  1684. * Move current, old version and all thumbnails
  1685. * to the new filename. Old file is deleted.
  1686. *
  1687. * Cache purging is done; checks for validity
  1688. * and logging are caller's responsibility
  1689. *
  1690. * @param Title $target New file name
  1691. * @return Status
  1692. */
  1693. function move( $target ) {
  1694. $this->readOnlyError();
  1695. }
  1696. /**
  1697. * Delete all versions of the file.
  1698. *
  1699. * Moves the files into an archive directory (or deletes them)
  1700. * and removes the database rows.
  1701. *
  1702. * Cache purging is done; logging is caller's responsibility.
  1703. *
  1704. * @param string $reason
  1705. * @param bool $suppress Hide content from sysops?
  1706. * @param User|null $user
  1707. * @return Status
  1708. * STUB
  1709. * Overridden by LocalFile
  1710. */
  1711. function delete( $reason, $suppress = false, $user = null ) {
  1712. $this->readOnlyError();
  1713. }
  1714. /**
  1715. * Restore all or specified deleted revisions to the given file.
  1716. * Permissions and logging are left to the caller.
  1717. *
  1718. * May throw database exceptions on error.
  1719. *
  1720. * @param array $versions Set of record ids of deleted items to restore,
  1721. * or empty to restore all revisions.
  1722. * @param bool $unsuppress Remove restrictions on content upon restoration?
  1723. * @return int|bool The number of file revisions restored if successful,
  1724. * or false on failure
  1725. * STUB
  1726. * Overridden by LocalFile
  1727. */
  1728. function restore( $versions = [], $unsuppress = false ) {
  1729. $this->readOnlyError();
  1730. }
  1731. /**
  1732. * Returns 'true' if this file is a type which supports multiple pages,
  1733. * e.g. DJVU or PDF. Note that this may be true even if the file in
  1734. * question only has a single page.
  1735. *
  1736. * @return bool
  1737. */
  1738. function isMultipage() {
  1739. return $this->getHandler() && $this->handler->isMultiPage( $this );
  1740. }
  1741. /**
  1742. * Returns the number of pages of a multipage document, or false for
  1743. * documents which aren't multipage documents
  1744. *
  1745. * @return string|bool|int
  1746. */
  1747. function pageCount() {
  1748. if ( !isset( $this->pageCount ) ) {
  1749. if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
  1750. $this->pageCount = $this->handler->pageCount( $this );
  1751. } else {
  1752. $this->pageCount = false;
  1753. }
  1754. }
  1755. return $this->pageCount;
  1756. }
  1757. /**
  1758. * Calculate the height of a thumbnail using the source and destination width
  1759. *
  1760. * @param int $srcWidth
  1761. * @param int $srcHeight
  1762. * @param int $dstWidth
  1763. *
  1764. * @return int
  1765. */
  1766. static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
  1767. // Exact integer multiply followed by division
  1768. if ( $srcWidth == 0 ) {
  1769. return 0;
  1770. } else {
  1771. return (int)round( $srcHeight * $dstWidth / $srcWidth );
  1772. }
  1773. }
  1774. /**
  1775. * Get an image size array like that returned by getImageSize(), or false if it
  1776. * can't be determined. Loads the image size directly from the file ignoring caches.
  1777. *
  1778. * @note Use getWidth()/getHeight() instead of this method unless you have a
  1779. * a good reason. This method skips all caches.
  1780. *
  1781. * @param string $filePath The path to the file (e.g. From getLocalPathRef() )
  1782. * @return array|false The width, followed by height, with optionally more things after
  1783. */
  1784. function getImageSize( $filePath ) {
  1785. if ( !$this->getHandler() ) {
  1786. return false;
  1787. }
  1788. return $this->getHandler()->getImageSize( $this, $filePath );
  1789. }
  1790. /**
  1791. * Get the URL of the image description page. May return false if it is
  1792. * unknown or not applicable.
  1793. *
  1794. * @return string
  1795. */
  1796. function getDescriptionUrl() {
  1797. if ( $this->repo ) {
  1798. return $this->repo->getDescriptionUrl( $this->getName() );
  1799. } else {
  1800. return false;
  1801. }
  1802. }
  1803. /**
  1804. * Get the HTML text of the description page, if available
  1805. *
  1806. * @param Language|null $lang Optional language to fetch description in
  1807. * @return string|false
  1808. */
  1809. function getDescriptionText( Language $lang = null ) {
  1810. global $wgLang;
  1811. if ( !$this->repo || !$this->repo->fetchDescription ) {
  1812. return false;
  1813. }
  1814. $lang = $lang ?? $wgLang;
  1815. $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
  1816. if ( $renderUrl ) {
  1817. $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
  1818. $key = $this->repo->getLocalCacheKey(
  1819. 'RemoteFileDescription',
  1820. $lang->getCode(),
  1821. md5( $this->getName() )
  1822. );
  1823. return $cache->getWithSetCallback(
  1824. $key,
  1825. $this->repo->descriptionCacheExpiry ?: $cache::TTL_UNCACHEABLE,
  1826. function ( $oldValue, &$ttl, array &$setOpts ) use ( $renderUrl ) {
  1827. wfDebug( "Fetching shared description from $renderUrl\n" );
  1828. $res = Http::get( $renderUrl, [], __METHOD__ );
  1829. if ( !$res ) {
  1830. $ttl = WANObjectCache::TTL_UNCACHEABLE;
  1831. }
  1832. return $res;
  1833. }
  1834. );
  1835. }
  1836. return false;
  1837. }
  1838. /**
  1839. * Get description of file revision
  1840. * STUB
  1841. *
  1842. * @param int $audience One of:
  1843. * File::FOR_PUBLIC to be displayed to all users
  1844. * File::FOR_THIS_USER to be displayed to the given user
  1845. * File::RAW get the description regardless of permissions
  1846. * @param User|null $user User object to check for, only if FOR_THIS_USER is
  1847. * passed to the $audience parameter
  1848. * @return null|string
  1849. */
  1850. function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
  1851. return null;
  1852. }
  1853. /**
  1854. * Get the 14-character timestamp of the file upload
  1855. *
  1856. * @return string|bool TS_MW timestamp or false on failure
  1857. */
  1858. function getTimestamp() {
  1859. $this->assertRepoDefined();
  1860. return $this->repo->getFileTimestamp( $this->getPath() );
  1861. }
  1862. /**
  1863. * Returns the timestamp (in TS_MW format) of the last change of the description page.
  1864. * Returns false if the file does not have a description page, or retrieving the timestamp
  1865. * would be expensive.
  1866. * @since 1.25
  1867. * @return string|bool
  1868. */
  1869. public function getDescriptionTouched() {
  1870. return false;
  1871. }
  1872. /**
  1873. * Get the SHA-1 base 36 hash of the file
  1874. *
  1875. * @return string
  1876. */
  1877. function getSha1() {
  1878. $this->assertRepoDefined();
  1879. return $this->repo->getFileSha1( $this->getPath() );
  1880. }
  1881. /**
  1882. * Get the deletion archive key, "<sha1>.<ext>"
  1883. *
  1884. * @return string|false
  1885. */
  1886. function getStorageKey() {
  1887. $hash = $this->getSha1();
  1888. if ( !$hash ) {
  1889. return false;
  1890. }
  1891. $ext = $this->getExtension();
  1892. $dotExt = $ext === '' ? '' : ".$ext";
  1893. return $hash . $dotExt;
  1894. }
  1895. /**
  1896. * Determine if the current user is allowed to view a particular
  1897. * field of this file, if it's marked as deleted.
  1898. * STUB
  1899. * @param int $field
  1900. * @param User|null $user User object to check, or null to use $wgUser
  1901. * @return bool
  1902. */
  1903. function userCan( $field, User $user = null ) {
  1904. return true;
  1905. }
  1906. /**
  1907. * @deprecated since 1.30, use File::getContentHeaders instead
  1908. */
  1909. function getStreamHeaders() {
  1910. wfDeprecated( __METHOD__, '1.30' );
  1911. return $this->getContentHeaders();
  1912. }
  1913. /**
  1914. * @return string[] HTTP header name/value map to use for HEAD/GET request responses
  1915. * @since 1.30
  1916. */
  1917. function getContentHeaders() {
  1918. $handler = $this->getHandler();
  1919. if ( $handler ) {
  1920. $metadata = $this->getMetadata();
  1921. if ( is_string( $metadata ) ) {
  1922. $metadata = Wikimedia\quietCall( 'unserialize', $metadata );
  1923. }
  1924. if ( !is_array( $metadata ) ) {
  1925. $metadata = [];
  1926. }
  1927. return $handler->getContentHeaders( $metadata );
  1928. }
  1929. return [];
  1930. }
  1931. /**
  1932. * @return string
  1933. */
  1934. function getLongDesc() {
  1935. $handler = $this->getHandler();
  1936. if ( $handler ) {
  1937. return $handler->getLongDesc( $this );
  1938. } else {
  1939. return MediaHandler::getGeneralLongDesc( $this );
  1940. }
  1941. }
  1942. /**
  1943. * @return string
  1944. */
  1945. function getShortDesc() {
  1946. $handler = $this->getHandler();
  1947. if ( $handler ) {
  1948. return $handler->getShortDesc( $this );
  1949. } else {
  1950. return MediaHandler::getGeneralShortDesc( $this );
  1951. }
  1952. }
  1953. /**
  1954. * @return string
  1955. */
  1956. function getDimensionsString() {
  1957. $handler = $this->getHandler();
  1958. if ( $handler ) {
  1959. return $handler->getDimensionsString( $this );
  1960. } else {
  1961. return '';
  1962. }
  1963. }
  1964. /**
  1965. * @return string
  1966. */
  1967. function getRedirected() {
  1968. return $this->redirected;
  1969. }
  1970. /**
  1971. * @return Title|null
  1972. */
  1973. function getRedirectedTitle() {
  1974. if ( $this->redirected ) {
  1975. if ( !$this->redirectTitle ) {
  1976. $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
  1977. }
  1978. return $this->redirectTitle;
  1979. }
  1980. return null;
  1981. }
  1982. /**
  1983. * @param string $from
  1984. * @return void
  1985. */
  1986. function redirectedFrom( $from ) {
  1987. $this->redirected = $from;
  1988. }
  1989. /**
  1990. * @return bool
  1991. */
  1992. function isMissing() {
  1993. return false;
  1994. }
  1995. /**
  1996. * Check if this file object is small and can be cached
  1997. * @return bool
  1998. */
  1999. public function isCacheable() {
  2000. return true;
  2001. }
  2002. /**
  2003. * Assert that $this->repo is set to a valid FileRepo instance
  2004. * @throws MWException
  2005. */
  2006. protected function assertRepoDefined() {
  2007. if ( !( $this->repo instanceof $this->repoClass ) ) {
  2008. throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
  2009. }
  2010. }
  2011. /**
  2012. * Assert that $this->title is set to a Title
  2013. * @throws MWException
  2014. */
  2015. protected function assertTitleDefined() {
  2016. if ( !( $this->title instanceof Title ) ) {
  2017. throw new MWException( "A Title object is not set for this File.\n" );
  2018. }
  2019. }
  2020. /**
  2021. * True if creating thumbnails from the file is large or otherwise resource-intensive.
  2022. * @return bool
  2023. */
  2024. public function isExpensiveToThumbnail() {
  2025. $handler = $this->getHandler();
  2026. return $handler ? $handler->isExpensiveToThumbnail( $this ) : false;
  2027. }
  2028. /**
  2029. * Whether the thumbnails created on the same server as this code is running.
  2030. * @since 1.25
  2031. * @return bool
  2032. */
  2033. public function isTransformedLocally() {
  2034. return true;
  2035. }
  2036. }