UploadStash.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. <?php
  2. /**
  3. * Temporary storage for uploaded files.
  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. */
  22. /**
  23. * UploadStash is intended to accomplish a few things:
  24. * - Enable applications to temporarily stash files without publishing them to
  25. * the wiki.
  26. * - Several parts of MediaWiki do this in similar ways: UploadBase,
  27. * UploadWizard, and FirefoggChunkedExtension.
  28. * And there are several that reimplement stashing from scratch, in
  29. * idiosyncratic ways. The idea is to unify them all here.
  30. * Mostly all of them are the same except for storing some custom fields,
  31. * which we subsume into the data array.
  32. * - Enable applications to find said files later, as long as the db table or
  33. * temp files haven't been purged.
  34. * - Enable the uploading user (and *ONLY* the uploading user) to access said
  35. * files, and thumbnails of said files, via a URL. We accomplish this using
  36. * a database table, with ownership checking as you might expect. See
  37. * SpecialUploadStash, which implements a web interface to some files stored
  38. * this way.
  39. *
  40. * UploadStash right now is *mostly* intended to show you one user's slice of
  41. * the entire stash. The user parameter is only optional because there are few
  42. * cases where we clean out the stash from an automated script. In the future we
  43. * might refactor this.
  44. *
  45. * UploadStash represents the entire stash of temporary files.
  46. * UploadStashFile is a filestore for the actual physical disk files.
  47. * UploadFromStash extends UploadBase, and represents a single stashed file as
  48. * it is moved from the stash to the regular file repository
  49. *
  50. * @ingroup Upload
  51. */
  52. class UploadStash {
  53. // Format of the key for files -- has to be suitable as a filename itself (e.g. ab12cd34ef.jpg)
  54. const KEY_FORMAT_REGEX = '/^[\w\-\.]+\.\w*$/';
  55. const MAX_US_PROPS_SIZE = 65535;
  56. /**
  57. * repository that this uses to store temp files
  58. * public because we sometimes need to get a LocalFile within the same repo.
  59. *
  60. * @var LocalRepo
  61. */
  62. public $repo;
  63. // array of initialized repo objects
  64. protected $files = [];
  65. // cache of the file metadata that's stored in the database
  66. protected $fileMetadata = [];
  67. // fileprops cache
  68. protected $fileProps = [];
  69. // current user
  70. protected $user, $userId, $isLoggedIn;
  71. /**
  72. * Represents a temporary filestore, with metadata in the database.
  73. * Designed to be compatible with the session stashing code in UploadBase
  74. * (should replace it eventually).
  75. *
  76. * @param FileRepo $repo
  77. * @param User|null $user
  78. */
  79. public function __construct( FileRepo $repo, $user = null ) {
  80. // this might change based on wiki's configuration.
  81. $this->repo = $repo;
  82. // if a user was passed, use it. otherwise, attempt to use the global.
  83. // this keeps FileRepo from breaking when it creates an UploadStash object
  84. global $wgUser;
  85. $this->user = $user ?: $wgUser;
  86. if ( is_object( $this->user ) ) {
  87. $this->userId = $this->user->getId();
  88. $this->isLoggedIn = $this->user->isLoggedIn();
  89. }
  90. }
  91. /**
  92. * Get a file and its metadata from the stash.
  93. * The noAuth param is a bit janky but is required for automated scripts
  94. * which clean out the stash.
  95. *
  96. * @param string $key Key under which file information is stored
  97. * @param bool $noAuth (optional) Don't check authentication. Used by maintenance scripts.
  98. * @throws UploadStashFileNotFoundException
  99. * @throws UploadStashNotLoggedInException
  100. * @throws UploadStashWrongOwnerException
  101. * @throws UploadStashBadPathException
  102. * @return UploadStashFile
  103. */
  104. public function getFile( $key, $noAuth = false ) {
  105. if ( !preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
  106. throw new UploadStashBadPathException(
  107. wfMessage( 'uploadstash-bad-path-bad-format', $key )
  108. );
  109. }
  110. if ( !$noAuth && !$this->isLoggedIn ) {
  111. throw new UploadStashNotLoggedInException(
  112. wfMessage( 'uploadstash-not-logged-in' )
  113. );
  114. }
  115. if ( !isset( $this->fileMetadata[$key] ) ) {
  116. if ( !$this->fetchFileMetadata( $key ) ) {
  117. // If nothing was received, it's likely due to replication lag.
  118. // Check the master to see if the record is there.
  119. $this->fetchFileMetadata( $key, DB_MASTER );
  120. }
  121. if ( !isset( $this->fileMetadata[$key] ) ) {
  122. throw new UploadStashFileNotFoundException(
  123. wfMessage( 'uploadstash-file-not-found', $key )
  124. );
  125. }
  126. // create $this->files[$key]
  127. $this->initFile( $key );
  128. // fetch fileprops
  129. if ( strlen( $this->fileMetadata[$key]['us_props'] ) ) {
  130. $this->fileProps[$key] = unserialize( $this->fileMetadata[$key]['us_props'] );
  131. } else { // b/c for rows with no us_props
  132. wfDebug( __METHOD__ . " fetched props for $key from file\n" );
  133. $path = $this->fileMetadata[$key]['us_path'];
  134. $this->fileProps[$key] = $this->repo->getFileProps( $path );
  135. }
  136. }
  137. if ( !$this->files[$key]->exists() ) {
  138. wfDebug( __METHOD__ . " tried to get file at $key, but it doesn't exist\n" );
  139. // @todo Is this not an UploadStashFileNotFoundException case?
  140. throw new UploadStashBadPathException(
  141. wfMessage( 'uploadstash-bad-path' )
  142. );
  143. }
  144. if ( !$noAuth && $this->fileMetadata[$key]['us_user'] != $this->userId ) {
  145. throw new UploadStashWrongOwnerException(
  146. wfMessage( 'uploadstash-wrong-owner', $key )
  147. );
  148. }
  149. return $this->files[$key];
  150. }
  151. /**
  152. * Getter for file metadata.
  153. *
  154. * @param string $key Key under which file information is stored
  155. * @return array
  156. */
  157. public function getMetadata( $key ) {
  158. $this->getFile( $key );
  159. return $this->fileMetadata[$key];
  160. }
  161. /**
  162. * Getter for fileProps
  163. *
  164. * @param string $key Key under which file information is stored
  165. * @return array
  166. */
  167. public function getFileProps( $key ) {
  168. $this->getFile( $key );
  169. return $this->fileProps[$key];
  170. }
  171. /**
  172. * Stash a file in a temp directory and record that we did this in the
  173. * database, along with other metadata.
  174. *
  175. * @param string $path Path to file you want stashed
  176. * @param string|null $sourceType The type of upload that generated this file
  177. * (currently, I believe, 'file' or null)
  178. * @throws UploadStashBadPathException
  179. * @throws UploadStashFileException
  180. * @throws UploadStashNotLoggedInException
  181. * @return UploadStashFile|null File, or null on failure
  182. */
  183. public function stashFile( $path, $sourceType = null ) {
  184. if ( !is_file( $path ) ) {
  185. wfDebug( __METHOD__ . " tried to stash file at '$path', but it doesn't exist\n" );
  186. throw new UploadStashBadPathException(
  187. wfMessage( 'uploadstash-bad-path' )
  188. );
  189. }
  190. $mwProps = new MWFileProps( MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer() );
  191. $fileProps = $mwProps->getPropsFromPath( $path, true );
  192. wfDebug( __METHOD__ . " stashing file at '$path'\n" );
  193. // we will be initializing from some tmpnam files that don't have extensions.
  194. // most of MediaWiki assumes all uploaded files have good extensions. So, we fix this.
  195. $extension = self::getExtensionForPath( $path );
  196. if ( !preg_match( "/\\.\\Q$extension\\E$/", $path ) ) {
  197. $pathWithGoodExtension = "$path.$extension";
  198. } else {
  199. $pathWithGoodExtension = $path;
  200. }
  201. // If no key was supplied, make one. a mysql insertid would be totally
  202. // reasonable here, except that for historical reasons, the key is this
  203. // random thing instead. At least it's not guessable.
  204. // Some things that when combined will make a suitably unique key.
  205. // see: http://www.jwz.org/doc/mid.html
  206. list( $usec, $sec ) = explode( ' ', microtime() );
  207. $usec = substr( $usec, 2 );
  208. $key = Wikimedia\base_convert( $sec . $usec, 10, 36 ) . '.' .
  209. Wikimedia\base_convert( mt_rand(), 10, 36 ) . '.' .
  210. $this->userId . '.' .
  211. $extension;
  212. $this->fileProps[$key] = $fileProps;
  213. if ( !preg_match( self::KEY_FORMAT_REGEX, $key ) ) {
  214. throw new UploadStashBadPathException(
  215. wfMessage( 'uploadstash-bad-path-bad-format', $key )
  216. );
  217. }
  218. wfDebug( __METHOD__ . " key for '$path': $key\n" );
  219. // if not already in a temporary area, put it there
  220. $storeStatus = $this->repo->storeTemp( basename( $pathWithGoodExtension ), $path );
  221. if ( !$storeStatus->isOK() ) {
  222. // It is a convention in MediaWiki to only return one error per API
  223. // exception, even if multiple errors are available. We use reset()
  224. // to pick the "first" thing that was wrong, preferring errors to
  225. // warnings. This is a bit lame, as we may have more info in the
  226. // $storeStatus and we're throwing it away, but to fix it means
  227. // redesigning API errors significantly.
  228. // $storeStatus->value just contains the virtual URL (if anything)
  229. // which is probably useless to the caller.
  230. $error = $storeStatus->getErrorsArray();
  231. $error = reset( $error );
  232. if ( !count( $error ) ) {
  233. $error = $storeStatus->getWarningsArray();
  234. $error = reset( $error );
  235. if ( !count( $error ) ) {
  236. $error = [ 'unknown', 'no error recorded' ];
  237. }
  238. }
  239. // At this point, $error should contain the single "most important"
  240. // error, plus any parameters.
  241. $errorMsg = array_shift( $error );
  242. throw new UploadStashFileException( wfMessage( $errorMsg, $error ) );
  243. }
  244. $stashPath = $storeStatus->value;
  245. // fetch the current user ID
  246. if ( !$this->isLoggedIn ) {
  247. throw new UploadStashNotLoggedInException(
  248. wfMessage( 'uploadstash-not-logged-in' )
  249. );
  250. }
  251. // insert the file metadata into the db.
  252. wfDebug( __METHOD__ . " inserting $stashPath under $key\n" );
  253. $dbw = $this->repo->getMasterDB();
  254. $serializedFileProps = serialize( $fileProps );
  255. if ( strlen( $serializedFileProps ) > self::MAX_US_PROPS_SIZE ) {
  256. // Database is going to truncate this and make the field invalid.
  257. // Prioritize important metadata over file handler metadata.
  258. // File handler should be prepared to regenerate invalid metadata if needed.
  259. $fileProps['metadata'] = false;
  260. $serializedFileProps = serialize( $fileProps );
  261. }
  262. $this->fileMetadata[$key] = [
  263. 'us_user' => $this->userId,
  264. 'us_key' => $key,
  265. 'us_orig_path' => $path,
  266. 'us_path' => $stashPath, // virtual URL
  267. 'us_props' => $dbw->encodeBlob( $serializedFileProps ),
  268. 'us_size' => $fileProps['size'],
  269. 'us_sha1' => $fileProps['sha1'],
  270. 'us_mime' => $fileProps['mime'],
  271. 'us_media_type' => $fileProps['media_type'],
  272. 'us_image_width' => $fileProps['width'],
  273. 'us_image_height' => $fileProps['height'],
  274. 'us_image_bits' => $fileProps['bits'],
  275. 'us_source_type' => $sourceType,
  276. 'us_timestamp' => $dbw->timestamp(),
  277. 'us_status' => 'finished'
  278. ];
  279. $dbw->insert(
  280. 'uploadstash',
  281. $this->fileMetadata[$key],
  282. __METHOD__
  283. );
  284. // store the insertid in the class variable so immediate retrieval
  285. // (possibly laggy) isn't necessary.
  286. $this->fileMetadata[$key]['us_id'] = $dbw->insertId();
  287. # create the UploadStashFile object for this file.
  288. $this->initFile( $key );
  289. return $this->getFile( $key );
  290. }
  291. /**
  292. * Remove all files from the stash.
  293. * Does not clean up files in the repo, just the record of them.
  294. *
  295. * @throws UploadStashNotLoggedInException
  296. * @return bool Success
  297. */
  298. public function clear() {
  299. if ( !$this->isLoggedIn ) {
  300. throw new UploadStashNotLoggedInException(
  301. wfMessage( 'uploadstash-not-logged-in' )
  302. );
  303. }
  304. wfDebug( __METHOD__ . ' clearing all rows for user ' . $this->userId . "\n" );
  305. $dbw = $this->repo->getMasterDB();
  306. $dbw->delete(
  307. 'uploadstash',
  308. [ 'us_user' => $this->userId ],
  309. __METHOD__
  310. );
  311. # destroy objects.
  312. $this->files = [];
  313. $this->fileMetadata = [];
  314. return true;
  315. }
  316. /**
  317. * Remove a particular file from the stash. Also removes it from the repo.
  318. *
  319. * @param string $key
  320. * @throws UploadStashNoSuchKeyException|UploadStashNotLoggedInException
  321. * @throws UploadStashWrongOwnerException
  322. * @return bool Success
  323. */
  324. public function removeFile( $key ) {
  325. if ( !$this->isLoggedIn ) {
  326. throw new UploadStashNotLoggedInException(
  327. wfMessage( 'uploadstash-not-logged-in' )
  328. );
  329. }
  330. $dbw = $this->repo->getMasterDB();
  331. // this is a cheap query. it runs on the master so that this function
  332. // still works when there's lag. It won't be called all that often.
  333. $row = $dbw->selectRow(
  334. 'uploadstash',
  335. 'us_user',
  336. [ 'us_key' => $key ],
  337. __METHOD__
  338. );
  339. if ( !$row ) {
  340. throw new UploadStashNoSuchKeyException(
  341. wfMessage( 'uploadstash-no-such-key', $key )
  342. );
  343. }
  344. if ( $row->us_user != $this->userId ) {
  345. throw new UploadStashWrongOwnerException(
  346. wfMessage( 'uploadstash-wrong-owner', $key )
  347. );
  348. }
  349. return $this->removeFileNoAuth( $key );
  350. }
  351. /**
  352. * Remove a file (see removeFile), but doesn't check ownership first.
  353. *
  354. * @param string $key
  355. * @return bool Success
  356. */
  357. public function removeFileNoAuth( $key ) {
  358. wfDebug( __METHOD__ . " clearing row $key\n" );
  359. // Ensure we have the UploadStashFile loaded for this key
  360. $this->getFile( $key, true );
  361. $dbw = $this->repo->getMasterDB();
  362. $dbw->delete(
  363. 'uploadstash',
  364. [ 'us_key' => $key ],
  365. __METHOD__
  366. );
  367. /** @todo Look into UnregisteredLocalFile and find out why the rv here is
  368. * sometimes wrong (false when file was removed). For now, ignore.
  369. */
  370. $this->files[$key]->remove();
  371. unset( $this->files[$key] );
  372. unset( $this->fileMetadata[$key] );
  373. return true;
  374. }
  375. /**
  376. * List all files in the stash.
  377. *
  378. * @throws UploadStashNotLoggedInException
  379. * @return array|false
  380. */
  381. public function listFiles() {
  382. if ( !$this->isLoggedIn ) {
  383. throw new UploadStashNotLoggedInException(
  384. wfMessage( 'uploadstash-not-logged-in' )
  385. );
  386. }
  387. $dbr = $this->repo->getReplicaDB();
  388. $res = $dbr->select(
  389. 'uploadstash',
  390. 'us_key',
  391. [ 'us_user' => $this->userId ],
  392. __METHOD__
  393. );
  394. if ( !is_object( $res ) || $res->numRows() == 0 ) {
  395. // nothing to do.
  396. return false;
  397. }
  398. // finish the read before starting writes.
  399. $keys = [];
  400. foreach ( $res as $row ) {
  401. array_push( $keys, $row->us_key );
  402. }
  403. return $keys;
  404. }
  405. /**
  406. * Find or guess extension -- ensuring that our extension matches our MIME type.
  407. * Since these files are constructed from php tempnames they may not start off
  408. * with an extension.
  409. * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming
  410. * uploads versus the desired filename. Maybe we can get that passed to us...
  411. * @param string $path
  412. * @throws UploadStashFileException
  413. * @return string
  414. */
  415. public static function getExtensionForPath( $path ) {
  416. global $wgFileBlacklist;
  417. // Does this have an extension?
  418. $n = strrpos( $path, '.' );
  419. $extension = null;
  420. if ( $n !== false ) {
  421. $extension = $n ? substr( $path, $n + 1 ) : '';
  422. } else {
  423. // If not, assume that it should be related to the MIME type of the original file.
  424. $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
  425. $mimeType = $magic->guessMimeType( $path );
  426. $extensions = explode( ' ', $magic->getExtensionsForType( $mimeType ) );
  427. if ( count( $extensions ) ) {
  428. $extension = $extensions[0];
  429. }
  430. }
  431. if ( is_null( $extension ) ) {
  432. throw new UploadStashFileException(
  433. wfMessage( 'uploadstash-no-extension' )
  434. );
  435. }
  436. $extension = File::normalizeExtension( $extension );
  437. if ( in_array( $extension, $wgFileBlacklist ) ) {
  438. // The file should already be checked for being evil.
  439. // However, if somehow we got here, we definitely
  440. // don't want to give it an extension of .php and
  441. // put it in a web accesible directory.
  442. return '';
  443. }
  444. return $extension;
  445. }
  446. /**
  447. * Helper function: do the actual database query to fetch file metadata.
  448. *
  449. * @param string $key
  450. * @param int $readFromDB Constant (default: DB_REPLICA)
  451. * @return bool
  452. */
  453. protected function fetchFileMetadata( $key, $readFromDB = DB_REPLICA ) {
  454. // populate $fileMetadata[$key]
  455. $dbr = null;
  456. if ( $readFromDB === DB_MASTER ) {
  457. // sometimes reading from the master is necessary, if there's replication lag.
  458. $dbr = $this->repo->getMasterDB();
  459. } else {
  460. $dbr = $this->repo->getReplicaDB();
  461. }
  462. $row = $dbr->selectRow(
  463. 'uploadstash',
  464. [
  465. 'us_user', 'us_key', 'us_orig_path', 'us_path', 'us_props',
  466. 'us_size', 'us_sha1', 'us_mime', 'us_media_type',
  467. 'us_image_width', 'us_image_height', 'us_image_bits',
  468. 'us_source_type', 'us_timestamp', 'us_status',
  469. ],
  470. [ 'us_key' => $key ],
  471. __METHOD__
  472. );
  473. if ( !is_object( $row ) ) {
  474. // key wasn't present in the database. this will happen sometimes.
  475. return false;
  476. }
  477. $this->fileMetadata[$key] = (array)$row;
  478. $this->fileMetadata[$key]['us_props'] = $dbr->decodeBlob( $row->us_props );
  479. return true;
  480. }
  481. /**
  482. * Helper function: Initialize the UploadStashFile for a given file.
  483. *
  484. * @param string $key Key under which to store the object
  485. * @throws UploadStashZeroLengthFileException
  486. * @return bool
  487. */
  488. protected function initFile( $key ) {
  489. $file = new UploadStashFile( $this->repo, $this->fileMetadata[$key]['us_path'], $key );
  490. if ( $file->getSize() === 0 ) {
  491. throw new UploadStashZeroLengthFileException(
  492. wfMessage( 'uploadstash-zero-length' )
  493. );
  494. }
  495. $this->files[$key] = $file;
  496. return true;
  497. }
  498. }