SpecialUpload.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. <?php
  2. /**
  3. * Implements Special:Upload
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. * @ingroup SpecialPage
  22. * @ingroup Upload
  23. */
  24. use MediaWiki\MediaWikiServices;
  25. /**
  26. * Form for handling uploads and special page.
  27. *
  28. * @ingroup SpecialPage
  29. * @ingroup Upload
  30. */
  31. class SpecialUpload extends SpecialPage {
  32. /**
  33. * Get data POSTed through the form and assign them to the object
  34. * @param WebRequest|null $request Data posted.
  35. */
  36. public function __construct( $request = null ) {
  37. parent::__construct( 'Upload', 'upload' );
  38. }
  39. public function doesWrites() {
  40. return true;
  41. }
  42. /** Misc variables */
  43. /** @var WebRequest|FauxRequest The request this form is supposed to handle */
  44. public $mRequest;
  45. public $mSourceType;
  46. /** @var UploadBase */
  47. public $mUpload;
  48. /** @var LocalFile */
  49. public $mLocalFile;
  50. public $mUploadClicked;
  51. /** User input variables from the "description" section */
  52. /** @var string The requested target file name */
  53. public $mDesiredDestName;
  54. public $mComment;
  55. public $mLicense;
  56. /** User input variables from the root section */
  57. public $mIgnoreWarning;
  58. public $mWatchthis;
  59. public $mCopyrightStatus;
  60. public $mCopyrightSource;
  61. /** Hidden variables */
  62. public $mDestWarningAck;
  63. /** @var bool The user followed an "overwrite this file" link */
  64. public $mForReUpload;
  65. /** @var bool The user clicked "Cancel and return to upload form" button */
  66. public $mCancelUpload;
  67. public $mTokenOk;
  68. /** @var bool Subclasses can use this to determine whether a file was uploaded */
  69. public $mUploadSuccessful = false;
  70. /** Text injection points for hooks not using HTMLForm */
  71. public $uploadFormTextTop;
  72. public $uploadFormTextAfterSummary;
  73. /**
  74. * Initialize instance variables from request and create an Upload handler
  75. */
  76. protected function loadRequest() {
  77. $this->mRequest = $request = $this->getRequest();
  78. $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
  79. $this->mUpload = UploadBase::createFromRequest( $request );
  80. $this->mUploadClicked = $request->wasPosted()
  81. && ( $request->getCheck( 'wpUpload' )
  82. || $request->getCheck( 'wpUploadIgnoreWarning' ) );
  83. // Guess the desired name from the filename if not provided
  84. $this->mDesiredDestName = $request->getText( 'wpDestFile' );
  85. if ( !$this->mDesiredDestName && $request->getFileName( 'wpUploadFile' ) !== null ) {
  86. $this->mDesiredDestName = $request->getFileName( 'wpUploadFile' );
  87. }
  88. $this->mLicense = $request->getText( 'wpLicense' );
  89. $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
  90. $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
  91. || $request->getCheck( 'wpUploadIgnoreWarning' );
  92. $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
  93. $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
  94. $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
  95. $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
  96. $commentDefault = '';
  97. $commentMsg = $this->msg( 'upload-default-description' )->inContentLanguage();
  98. if ( !$this->mForReUpload && !$commentMsg->isDisabled() ) {
  99. $commentDefault = $commentMsg->plain();
  100. }
  101. $this->mComment = $request->getText( 'wpUploadDescription', $commentDefault );
  102. $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
  103. || $request->getCheck( 'wpReUpload' ); // b/w compat
  104. // If it was posted check for the token (no remote POST'ing with user credentials)
  105. $token = $request->getVal( 'wpEditToken' );
  106. $this->mTokenOk = $this->getUser()->matchEditToken( $token );
  107. $this->uploadFormTextTop = '';
  108. $this->uploadFormTextAfterSummary = '';
  109. }
  110. /**
  111. * This page can be shown if uploading is enabled.
  112. * Handle permission checking elsewhere in order to be able to show
  113. * custom error messages.
  114. *
  115. * @param User $user
  116. * @return bool
  117. */
  118. public function userCanExecute( User $user ) {
  119. return UploadBase::isEnabled() && parent::userCanExecute( $user );
  120. }
  121. /**
  122. * @param string|null $par
  123. * @throws ErrorPageError
  124. * @throws Exception
  125. * @throws FatalError
  126. * @throws MWException
  127. * @throws PermissionsError
  128. * @throws ReadOnlyError
  129. * @throws UserBlockedError
  130. */
  131. public function execute( $par ) {
  132. $this->useTransactionalTimeLimit();
  133. $this->setHeaders();
  134. $this->outputHeader();
  135. # Check uploading enabled
  136. if ( !UploadBase::isEnabled() ) {
  137. throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
  138. }
  139. $this->addHelpLink( 'Help:Managing files' );
  140. # Check permissions
  141. $user = $this->getUser();
  142. $permissionRequired = UploadBase::isAllowed( $user );
  143. if ( $permissionRequired !== true ) {
  144. throw new PermissionsError( $permissionRequired );
  145. }
  146. # Check blocks
  147. if ( $user->isBlockedFromUpload() ) {
  148. throw new UserBlockedError( $user->getBlock() );
  149. }
  150. // Global blocks
  151. if ( $user->isBlockedGlobally() ) {
  152. throw new UserBlockedError( $user->getGlobalBlock() );
  153. }
  154. # Check whether we actually want to allow changing stuff
  155. $this->checkReadOnly();
  156. $this->loadRequest();
  157. # Unsave the temporary file in case this was a cancelled upload
  158. if ( $this->mCancelUpload && !$this->unsaveUploadedFile() ) {
  159. # Something went wrong, so unsaveUploadedFile showed a warning
  160. return;
  161. }
  162. # Process upload or show a form
  163. if (
  164. $this->mTokenOk && !$this->mCancelUpload &&
  165. ( $this->mUpload && $this->mUploadClicked )
  166. ) {
  167. $this->processUpload();
  168. } else {
  169. # Backwards compatibility hook
  170. // Avoid PHP 7.1 warning of passing $this by reference
  171. $upload = $this;
  172. if ( !Hooks::run( 'UploadForm:initial', [ &$upload ] ) ) {
  173. wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
  174. return;
  175. }
  176. $this->showUploadForm( $this->getUploadForm() );
  177. }
  178. # Cleanup
  179. if ( $this->mUpload ) {
  180. $this->mUpload->cleanupTempFile();
  181. }
  182. }
  183. /**
  184. * Show the main upload form
  185. *
  186. * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
  187. */
  188. protected function showUploadForm( $form ) {
  189. # Add links if file was previously deleted
  190. if ( $this->mDesiredDestName ) {
  191. $this->showViewDeletedLinks();
  192. }
  193. if ( $form instanceof HTMLForm ) {
  194. $form->show();
  195. } else {
  196. $this->getOutput()->addHTML( $form );
  197. }
  198. }
  199. /**
  200. * Get an UploadForm instance with title and text properly set.
  201. *
  202. * @param string $message HTML string to add to the form
  203. * @param string $sessionKey Session key in case this is a stashed upload
  204. * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
  205. * @return UploadForm
  206. */
  207. protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
  208. # Initialize form
  209. $context = new DerivativeContext( $this->getContext() );
  210. $context->setTitle( $this->getPageTitle() ); // Remove subpage
  211. $form = new UploadForm( [
  212. 'watch' => $this->getWatchCheck(),
  213. 'forreupload' => $this->mForReUpload,
  214. 'sessionkey' => $sessionKey,
  215. 'hideignorewarning' => $hideIgnoreWarning,
  216. 'destwarningack' => (bool)$this->mDestWarningAck,
  217. 'description' => $this->mComment,
  218. 'texttop' => $this->uploadFormTextTop,
  219. 'textaftersummary' => $this->uploadFormTextAfterSummary,
  220. 'destfile' => $this->mDesiredDestName,
  221. ], $context, $this->getLinkRenderer() );
  222. # Check the token, but only if necessary
  223. if (
  224. !$this->mTokenOk && !$this->mCancelUpload &&
  225. ( $this->mUpload && $this->mUploadClicked )
  226. ) {
  227. $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
  228. }
  229. # Give a notice if the user is uploading a file that has been deleted or moved
  230. # Note that this is independent from the message 'filewasdeleted'
  231. $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
  232. $delNotice = ''; // empty by default
  233. if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
  234. $dbr = wfGetDB( DB_REPLICA );
  235. LogEventsList::showLogExtract( $delNotice, [ 'delete', 'move' ],
  236. $desiredTitleObj,
  237. '', [ 'lim' => 10,
  238. 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
  239. 'showIfEmpty' => false,
  240. 'msgKey' => [ 'upload-recreate-warning' ] ]
  241. );
  242. }
  243. $form->addPreText( $delNotice );
  244. # Add text to form
  245. $form->addPreText( '<div id="uploadtext">' .
  246. $this->msg( 'uploadtext', [ $this->mDesiredDestName ] )->parseAsBlock() .
  247. '</div>' );
  248. # Add upload error message
  249. $form->addPreText( $message );
  250. # Add footer to form
  251. $uploadFooter = $this->msg( 'uploadfooter' );
  252. if ( !$uploadFooter->isDisabled() ) {
  253. $form->addPostText( '<div id="mw-upload-footer-message">'
  254. . $uploadFooter->parseAsBlock() . "</div>\n" );
  255. }
  256. return $form;
  257. }
  258. /**
  259. * Shows the "view X deleted revivions link""
  260. */
  261. protected function showViewDeletedLinks() {
  262. $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
  263. $user = $this->getUser();
  264. $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
  265. // Show a subtitle link to deleted revisions (to sysops et al only)
  266. if ( $title instanceof Title ) {
  267. $count = $title->isDeleted();
  268. if ( $count > 0 && $permissionManager->userHasRight( $user, 'deletedhistory' ) ) {
  269. $restorelink = $this->getLinkRenderer()->makeKnownLink(
  270. SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
  271. $this->msg( 'restorelink' )->numParams( $count )->text()
  272. );
  273. $link = $this->msg(
  274. $permissionManager->userHasRight( $user, 'delete' ) ? 'thisisdeleted' : 'viewdeleted'
  275. )->rawParams( $restorelink )->parseAsBlock();
  276. $this->getOutput()->addHTML(
  277. Html::rawElement(
  278. 'div',
  279. [ 'id' => 'contentSub2' ],
  280. $link
  281. )
  282. );
  283. }
  284. }
  285. }
  286. /**
  287. * Stashes the upload and shows the main upload form.
  288. *
  289. * Note: only errors that can be handled by changing the name or
  290. * description should be redirected here. It should be assumed that the
  291. * file itself is sane and has passed UploadBase::verifyFile. This
  292. * essentially means that UploadBase::VERIFICATION_ERROR and
  293. * UploadBase::EMPTY_FILE should not be passed here.
  294. *
  295. * @param string $message HTML message to be passed to mainUploadForm
  296. */
  297. protected function showRecoverableUploadError( $message ) {
  298. $stashStatus = $this->mUpload->tryStashFile( $this->getUser() );
  299. if ( $stashStatus->isGood() ) {
  300. $sessionKey = $stashStatus->getValue()->getFileKey();
  301. $uploadWarning = 'upload-tryagain';
  302. } else {
  303. $sessionKey = null;
  304. $uploadWarning = 'upload-tryagain-nostash';
  305. }
  306. $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
  307. '<div class="error">' . $message . "</div>\n";
  308. $form = $this->getUploadForm( $message, $sessionKey );
  309. $form->setSubmitText( $this->msg( $uploadWarning )->escaped() );
  310. $this->showUploadForm( $form );
  311. }
  312. /**
  313. * Stashes the upload, shows the main form, but adds a "continue anyway button".
  314. * Also checks whether there are actually warnings to display.
  315. *
  316. * @param array $warnings
  317. * @return bool True if warnings were displayed, false if there are no
  318. * warnings and it should continue processing
  319. */
  320. protected function showUploadWarning( $warnings ) {
  321. # If there are no warnings, or warnings we can ignore, return early.
  322. # mDestWarningAck is set when some javascript has shown the warning
  323. # to the user. mForReUpload is set when the user clicks the "upload a
  324. # new version" link.
  325. if ( !$warnings || ( count( $warnings ) == 1
  326. && isset( $warnings['exists'] )
  327. && ( $this->mDestWarningAck || $this->mForReUpload ) )
  328. ) {
  329. return false;
  330. }
  331. $stashStatus = $this->mUpload->tryStashFile( $this->getUser() );
  332. if ( $stashStatus->isGood() ) {
  333. $sessionKey = $stashStatus->getValue()->getFileKey();
  334. $uploadWarning = 'uploadwarning-text';
  335. } else {
  336. $sessionKey = null;
  337. $uploadWarning = 'uploadwarning-text-nostash';
  338. }
  339. // Add styles for the warning, reused from the live preview
  340. $this->getOutput()->addModuleStyles( 'mediawiki.special' );
  341. $linkRenderer = $this->getLinkRenderer();
  342. $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
  343. . '<div class="mw-destfile-warning"><ul>';
  344. foreach ( $warnings as $warning => $args ) {
  345. if ( $warning == 'badfilename' ) {
  346. $this->mDesiredDestName = Title::makeTitle( NS_FILE, $args )->getText();
  347. }
  348. if ( $warning == 'exists' ) {
  349. $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
  350. } elseif ( $warning == 'no-change' ) {
  351. $file = $args;
  352. $filename = $file->getTitle()->getPrefixedText();
  353. $msg = "\t<li>" . $this->msg( 'fileexists-no-change', $filename )->parse() . "</li>\n";
  354. } elseif ( $warning == 'duplicate-version' ) {
  355. $file = $args[0];
  356. $count = count( $args );
  357. $filename = $file->getTitle()->getPrefixedText();
  358. $message = $this->msg( 'fileexists-duplicate-version' )
  359. ->params( $filename )
  360. ->numParams( $count );
  361. $msg = "\t<li>" . $message->parse() . "</li>\n";
  362. } elseif ( $warning == 'was-deleted' ) {
  363. # If the file existed before and was deleted, warn the user of this
  364. $ltitle = SpecialPage::getTitleFor( 'Log' );
  365. $llink = $linkRenderer->makeKnownLink(
  366. $ltitle,
  367. $this->msg( 'deletionlog' )->text(),
  368. [],
  369. [
  370. 'type' => 'delete',
  371. 'page' => Title::makeTitle( NS_FILE, $args )->getPrefixedText(),
  372. ]
  373. );
  374. $msg = "\t<li>" . $this->msg( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
  375. } elseif ( $warning == 'duplicate' ) {
  376. $msg = $this->getDupeWarning( $args );
  377. } elseif ( $warning == 'duplicate-archive' ) {
  378. if ( $args === '' ) {
  379. $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
  380. . "</li>\n";
  381. } else {
  382. $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
  383. Title::makeTitle( NS_FILE, $args )->getPrefixedText() )->parse()
  384. . "</li>\n";
  385. }
  386. } else {
  387. if ( $args === true ) {
  388. $args = [];
  389. } elseif ( !is_array( $args ) ) {
  390. $args = [ $args ];
  391. }
  392. $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
  393. }
  394. $warningHtml .= $msg;
  395. }
  396. $warningHtml .= "</ul></div>\n";
  397. $warningHtml .= $this->msg( $uploadWarning )->parseAsBlock();
  398. $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
  399. $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
  400. $form->addButton( [
  401. 'name' => 'wpUploadIgnoreWarning',
  402. 'value' => $this->msg( 'ignorewarning' )->text()
  403. ] );
  404. $form->addButton( [
  405. 'name' => 'wpCancelUpload',
  406. 'value' => $this->msg( 'reuploaddesc' )->text()
  407. ] );
  408. $this->showUploadForm( $form );
  409. # Indicate that we showed a form
  410. return true;
  411. }
  412. /**
  413. * Show the upload form with error message, but do not stash the file.
  414. *
  415. * @param string $message HTML string
  416. */
  417. protected function showUploadError( $message ) {
  418. $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
  419. '<div class="error">' . $message . "</div>\n";
  420. $this->showUploadForm( $this->getUploadForm( $message ) );
  421. }
  422. /**
  423. * Do the upload.
  424. * Checks are made in SpecialUpload::execute()
  425. */
  426. protected function processUpload() {
  427. // Fetch the file if required
  428. $status = $this->mUpload->fetchFile();
  429. if ( !$status->isOK() ) {
  430. $this->showUploadError( $this->getOutput()->parseAsInterface(
  431. $status->getWikiText( false, false, $this->getLanguage() )
  432. ) );
  433. return;
  434. }
  435. // Avoid PHP 7.1 warning of passing $this by reference
  436. $upload = $this;
  437. if ( !Hooks::run( 'UploadForm:BeforeProcessing', [ &$upload ] ) ) {
  438. wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
  439. // This code path is deprecated. If you want to break upload processing
  440. // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
  441. // and UploadBase::verifyFile.
  442. // If you use this hook to break uploading, the user will be returned
  443. // an empty form with no error message whatsoever.
  444. return;
  445. }
  446. // Upload verification
  447. $details = $this->mUpload->verifyUpload();
  448. if ( $details['status'] != UploadBase::OK ) {
  449. $this->processVerificationError( $details );
  450. return;
  451. }
  452. // Verify permissions for this title
  453. $permErrors = $this->mUpload->verifyTitlePermissions( $this->getUser() );
  454. if ( $permErrors !== true ) {
  455. $code = array_shift( $permErrors[0] );
  456. $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
  457. return;
  458. }
  459. $this->mLocalFile = $this->mUpload->getLocalFile();
  460. // Check warnings if necessary
  461. if ( !$this->mIgnoreWarning ) {
  462. $warnings = $this->mUpload->checkWarnings();
  463. if ( $this->showUploadWarning( $warnings ) ) {
  464. return;
  465. }
  466. }
  467. // This is as late as we can throttle, after expected issues have been handled
  468. if ( UploadBase::isThrottled( $this->getUser() ) ) {
  469. $this->showRecoverableUploadError(
  470. $this->msg( 'actionthrottledtext' )->escaped()
  471. );
  472. return;
  473. }
  474. // Get the page text if this is not a reupload
  475. if ( !$this->mForReUpload ) {
  476. $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
  477. $this->mCopyrightStatus, $this->mCopyrightSource, $this->getConfig() );
  478. } else {
  479. $pageText = false;
  480. }
  481. $changeTags = $this->getRequest()->getVal( 'wpChangeTags' );
  482. if ( is_null( $changeTags ) || $changeTags === '' ) {
  483. $changeTags = [];
  484. } else {
  485. $changeTags = array_filter( array_map( 'trim', explode( ',', $changeTags ) ) );
  486. }
  487. if ( $changeTags ) {
  488. $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
  489. $changeTags, $this->getUser() );
  490. if ( !$changeTagsStatus->isOK() ) {
  491. $this->showUploadError( $this->getOutput()->parseAsInterface(
  492. $changeTagsStatus->getWikiText( false, false, $this->getLanguage() )
  493. ) );
  494. return;
  495. }
  496. }
  497. $status = $this->mUpload->performUpload(
  498. $this->mComment,
  499. $pageText,
  500. $this->mWatchthis,
  501. $this->getUser(),
  502. $changeTags
  503. );
  504. if ( !$status->isGood() ) {
  505. $this->showRecoverableUploadError(
  506. $this->getOutput()->parseAsInterface(
  507. $status->getWikiText( false, false, $this->getLanguage() )
  508. )
  509. );
  510. return;
  511. }
  512. // Success, redirect to description page
  513. $this->mUploadSuccessful = true;
  514. // Avoid PHP 7.1 warning of passing $this by reference
  515. $upload = $this;
  516. Hooks::run( 'SpecialUploadComplete', [ &$upload ] );
  517. $this->getOutput()->redirect( $this->mLocalFile->getTitle()->getFullURL() );
  518. }
  519. /**
  520. * Get the initial image page text based on a comment and optional file status information
  521. * @param string $comment
  522. * @param string $license
  523. * @param string $copyStatus
  524. * @param string $source
  525. * @param Config|null $config Configuration object to load data from
  526. * @return string
  527. */
  528. public static function getInitialPageText( $comment = '', $license = '',
  529. $copyStatus = '', $source = '', Config $config = null
  530. ) {
  531. if ( $config === null ) {
  532. wfDebug( __METHOD__ . ' called without a Config instance passed to it' );
  533. $config = MediaWikiServices::getInstance()->getMainConfig();
  534. }
  535. $msg = [];
  536. $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
  537. /* These messages are transcluded into the actual text of the description page.
  538. * Thus, forcing them as content messages makes the upload to produce an int: template
  539. * instead of hardcoding it there in the uploader language.
  540. */
  541. foreach ( [ 'license-header', 'filedesc', 'filestatus', 'filesource' ] as $msgName ) {
  542. if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
  543. $msg[$msgName] = "{{int:$msgName}}";
  544. } else {
  545. $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
  546. }
  547. }
  548. $licenseText = '';
  549. if ( $license !== '' ) {
  550. $licenseText = '== ' . $msg['license-header'] . " ==\n{{" . $license . "}}\n";
  551. }
  552. $pageText = $comment . "\n";
  553. $headerText = '== ' . $msg['filedesc'] . ' ==';
  554. if ( $comment !== '' && strpos( $comment, $headerText ) === false ) {
  555. // prepend header to page text unless it's already there (or there is no content)
  556. $pageText = $headerText . "\n" . $pageText;
  557. }
  558. if ( $config->get( 'UseCopyrightUpload' ) ) {
  559. $pageText .= '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n";
  560. $pageText .= $licenseText;
  561. $pageText .= '== ' . $msg['filesource'] . " ==\n" . $source;
  562. } else {
  563. $pageText .= $licenseText;
  564. }
  565. // allow extensions to modify the content
  566. Hooks::run( 'UploadForm:getInitialPageText', [ &$pageText, $msg, $config ] );
  567. return $pageText;
  568. }
  569. /**
  570. * See if we should check the 'watch this page' checkbox on the form
  571. * based on the user's preferences and whether we're being asked
  572. * to create a new file or update an existing one.
  573. *
  574. * In the case where 'watch edits' is off but 'watch creations' is on,
  575. * we'll leave the box unchecked.
  576. *
  577. * Note that the page target can be changed *on the form*, so our check
  578. * state can get out of sync.
  579. * @return bool|string
  580. */
  581. protected function getWatchCheck() {
  582. if ( $this->getUser()->getOption( 'watchdefault' ) ) {
  583. // Watch all edits!
  584. return true;
  585. }
  586. $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
  587. if ( $desiredTitleObj instanceof Title && $this->getUser()->isWatched( $desiredTitleObj ) ) {
  588. // Already watched, don't change that
  589. return true;
  590. }
  591. $local = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()
  592. ->newFile( $this->mDesiredDestName );
  593. if ( $local && $local->exists() ) {
  594. // We're uploading a new version of an existing file.
  595. // No creation, so don't watch it if we're not already.
  596. return false;
  597. } else {
  598. // New page should get watched if that's our option.
  599. return $this->getUser()->getOption( 'watchcreations' ) ||
  600. $this->getUser()->getOption( 'watchuploads' );
  601. }
  602. }
  603. /**
  604. * Provides output to the user for a result of UploadBase::verifyUpload
  605. *
  606. * @param array $details Result of UploadBase::verifyUpload
  607. * @throws MWException
  608. */
  609. protected function processVerificationError( $details ) {
  610. switch ( $details['status'] ) {
  611. /** Statuses that only require name changing */
  612. case UploadBase::MIN_LENGTH_PARTNAME:
  613. $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
  614. break;
  615. case UploadBase::ILLEGAL_FILENAME:
  616. $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
  617. $details['filtered'] )->parse() );
  618. break;
  619. case UploadBase::FILENAME_TOO_LONG:
  620. $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
  621. break;
  622. case UploadBase::FILETYPE_MISSING:
  623. $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
  624. break;
  625. case UploadBase::WINDOWS_NONASCII_FILENAME:
  626. $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
  627. break;
  628. /** Statuses that require reuploading */
  629. case UploadBase::EMPTY_FILE:
  630. $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
  631. break;
  632. case UploadBase::FILE_TOO_LARGE:
  633. $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
  634. break;
  635. case UploadBase::FILETYPE_BADTYPE:
  636. $msg = $this->msg( 'filetype-banned-type' );
  637. if ( isset( $details['blacklistedExt'] ) ) {
  638. $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
  639. } else {
  640. $msg->params( $details['finalExt'] );
  641. }
  642. $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
  643. $msg->params( $this->getLanguage()->commaList( $extensions ),
  644. count( $extensions ) );
  645. // Add PLURAL support for the first parameter. This results
  646. // in a bit unlogical parameter sequence, but does not break
  647. // old translations
  648. if ( isset( $details['blacklistedExt'] ) ) {
  649. $msg->params( count( $details['blacklistedExt'] ) );
  650. } else {
  651. $msg->params( 1 );
  652. }
  653. $this->showUploadError( $msg->parse() );
  654. break;
  655. case UploadBase::VERIFICATION_ERROR:
  656. unset( $details['status'] );
  657. $code = array_shift( $details['details'] );
  658. $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
  659. break;
  660. case UploadBase::HOOK_ABORTED:
  661. if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
  662. $args = $details['error'];
  663. $error = array_shift( $args );
  664. } else {
  665. $error = $details['error'];
  666. $args = null;
  667. }
  668. $this->showUploadError( $this->msg( $error, $args )->parse() );
  669. break;
  670. default:
  671. throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
  672. }
  673. }
  674. /**
  675. * Remove a temporarily kept file stashed by saveTempUploadedFile().
  676. *
  677. * @return bool Success
  678. */
  679. protected function unsaveUploadedFile() {
  680. if ( !( $this->mUpload instanceof UploadFromStash ) ) {
  681. return true;
  682. }
  683. $success = $this->mUpload->unsaveUploadedFile();
  684. if ( !$success ) {
  685. $this->getOutput()->showFatalError(
  686. $this->msg( 'filedeleteerror' )
  687. ->params( $this->mUpload->getTempPath() )
  688. ->escaped()
  689. );
  690. return false;
  691. } else {
  692. return true;
  693. }
  694. }
  695. /** Functions for formatting warnings */
  696. /**
  697. * Formats a result of UploadBase::getExistsWarning as HTML
  698. * This check is static and can be done pre-upload via AJAX
  699. *
  700. * @param array $exists The result of UploadBase::getExistsWarning
  701. * @return string Empty string if there is no warning or an HTML fragment
  702. */
  703. public static function getExistsWarning( $exists ) {
  704. if ( !$exists ) {
  705. return '';
  706. }
  707. $file = $exists['file'];
  708. $filename = $file->getTitle()->getPrefixedText();
  709. $warnMsg = null;
  710. if ( $exists['warning'] == 'exists' ) {
  711. // Exact match
  712. $warnMsg = wfMessage( 'fileexists', $filename );
  713. } elseif ( $exists['warning'] == 'page-exists' ) {
  714. // Page exists but file does not
  715. $warnMsg = wfMessage( 'filepageexists', $filename );
  716. } elseif ( $exists['warning'] == 'exists-normalized' ) {
  717. $warnMsg = wfMessage( 'fileexists-extension', $filename,
  718. $exists['normalizedFile']->getTitle()->getPrefixedText() );
  719. } elseif ( $exists['warning'] == 'thumb' ) {
  720. // Swapped argument order compared with other messages for backwards compatibility
  721. $warnMsg = wfMessage( 'fileexists-thumbnail-yes',
  722. $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
  723. } elseif ( $exists['warning'] == 'thumb-name' ) {
  724. // Image w/o '180px-' does not exists, but we do not like these filenames
  725. $name = $file->getName();
  726. $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
  727. $warnMsg = wfMessage( 'file-thumbnail-no', $badPart );
  728. } elseif ( $exists['warning'] == 'bad-prefix' ) {
  729. $warnMsg = wfMessage( 'filename-bad-prefix', $exists['prefix'] );
  730. }
  731. return $warnMsg ? $warnMsg->title( $file->getTitle() )->parse() : '';
  732. }
  733. /**
  734. * Construct a warning and a gallery from an array of duplicate files.
  735. * @param array $dupes
  736. * @return string
  737. */
  738. public function getDupeWarning( $dupes ) {
  739. if ( !$dupes ) {
  740. return '';
  741. }
  742. $gallery = ImageGalleryBase::factory( false, $this->getContext() );
  743. $gallery->setShowBytes( false );
  744. $gallery->setShowDimensions( false );
  745. foreach ( $dupes as $file ) {
  746. $gallery->add( $file->getTitle() );
  747. }
  748. return '<li>' .
  749. $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
  750. $gallery->toHTML() . "</li>\n";
  751. }
  752. protected function getGroupName() {
  753. return 'media';
  754. }
  755. /**
  756. * Should we rotate images in the preview on Special:Upload.
  757. *
  758. * This controls js: mw.config.get( 'wgFileCanRotate' )
  759. *
  760. * @todo What about non-BitmapHandler handled files?
  761. * @return bool
  762. */
  763. public static function rotationEnabled() {
  764. $bitmapHandler = new BitmapHandler();
  765. return $bitmapHandler->autoRotateEnabled();
  766. }
  767. }