Http::getProxy() method to get proxy configuration
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * User interface for page editing.
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 /**
24 * The edit page/HTML interface (split from Article)
25 * The actual database and text munging is still in Article,
26 * but it should get easier to call those from alternate
27 * interfaces.
28 *
29 * EditPage cares about two distinct titles:
30 * $this->mContextTitle is the page that forms submit to, links point to,
31 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
32 * page in the database that is actually being edited. These are
33 * usually the same, but they are now allowed to be different.
34 *
35 * Surgeon General's Warning: prolonged exposure to this class is known to cause
36 * headaches, which may be fatal.
37 */
38 class EditPage {
39 /**
40 * Status: Article successfully updated
41 */
42 const AS_SUCCESS_UPDATE = 200;
43
44 /**
45 * Status: Article successfully created
46 */
47 const AS_SUCCESS_NEW_ARTICLE = 201;
48
49 /**
50 * Status: Article update aborted by a hook function
51 */
52 const AS_HOOK_ERROR = 210;
53
54 /**
55 * Status: A hook function returned an error
56 */
57 const AS_HOOK_ERROR_EXPECTED = 212;
58
59 /**
60 * Status: User is blocked from editing this page
61 */
62 const AS_BLOCKED_PAGE_FOR_USER = 215;
63
64 /**
65 * Status: Content too big (> $wgMaxArticleSize)
66 */
67 const AS_CONTENT_TOO_BIG = 216;
68
69 /**
70 * Status: this anonymous user is not allowed to edit this page
71 */
72 const AS_READ_ONLY_PAGE_ANON = 218;
73
74 /**
75 * Status: this logged in user is not allowed to edit this page
76 */
77 const AS_READ_ONLY_PAGE_LOGGED = 219;
78
79 /**
80 * Status: wiki is in readonly mode (wfReadOnly() == true)
81 */
82 const AS_READ_ONLY_PAGE = 220;
83
84 /**
85 * Status: rate limiter for action 'edit' was tripped
86 */
87 const AS_RATE_LIMITED = 221;
88
89 /**
90 * Status: article was deleted while editing and param wpRecreate == false or form
91 * was not posted
92 */
93 const AS_ARTICLE_WAS_DELETED = 222;
94
95 /**
96 * Status: user tried to create this page, but is not allowed to do that
97 * ( Title->userCan('create') == false )
98 */
99 const AS_NO_CREATE_PERMISSION = 223;
100
101 /**
102 * Status: user tried to create a blank page and wpIgnoreBlankArticle == false
103 */
104 const AS_BLANK_ARTICLE = 224;
105
106 /**
107 * Status: (non-resolvable) edit conflict
108 */
109 const AS_CONFLICT_DETECTED = 225;
110
111 /**
112 * Status: no edit summary given and the user has forceeditsummary set and the user is not
113 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
114 */
115 const AS_SUMMARY_NEEDED = 226;
116
117 /**
118 * Status: user tried to create a new section without content
119 */
120 const AS_TEXTBOX_EMPTY = 228;
121
122 /**
123 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
124 */
125 const AS_MAX_ARTICLE_SIZE_EXCEEDED = 229;
126
127 /**
128 * Status: WikiPage::doEdit() was unsuccessful
129 */
130 const AS_END = 231;
131
132 /**
133 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
134 */
135 const AS_SPAM_ERROR = 232;
136
137 /**
138 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
139 */
140 const AS_IMAGE_REDIRECT_ANON = 233;
141
142 /**
143 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
144 */
145 const AS_IMAGE_REDIRECT_LOGGED = 234;
146
147 /**
148 * Status: user tried to modify the content model, but is not allowed to do that
149 * ( User::isAllowed('editcontentmodel') == false )
150 */
151 const AS_NO_CHANGE_CONTENT_MODEL = 235;
152
153 /**
154 * Status: user tried to create self-redirect (redirect to the same article) and
155 * wpIgnoreSelfRedirect == false
156 */
157 const AS_SELF_REDIRECT = 236;
158
159 /**
160 * Status: an error relating to change tagging. Look at the message key for
161 * more details
162 */
163 const AS_CHANGE_TAG_ERROR = 237;
164
165 /**
166 * Status: can't parse content
167 */
168 const AS_PARSE_ERROR = 240;
169
170 /**
171 * Status: when changing the content model is disallowed due to
172 * $wgContentHandlerUseDB being false
173 */
174 const AS_CANNOT_USE_CUSTOM_MODEL = 241;
175
176 /**
177 * HTML id and name for the beginning of the edit form.
178 */
179 const EDITFORM_ID = 'editform';
180
181 /**
182 * Prefix of key for cookie used to pass post-edit state.
183 * The revision id edited is added after this
184 */
185 const POST_EDIT_COOKIE_KEY_PREFIX = 'PostEditRevision';
186
187 /**
188 * Duration of PostEdit cookie, in seconds.
189 * The cookie will be removed instantly if the JavaScript runs.
190 *
191 * Otherwise, though, we don't want the cookies to accumulate.
192 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible
193 * limit of only 20 cookies per domain. This still applies at least to some
194 * versions of IE without full updates:
195 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
196 *
197 * A value of 20 minutes should be enough to take into account slow loads and minor
198 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
199 */
200 const POST_EDIT_COOKIE_DURATION = 1200;
201
202 /** @var Article */
203 public $mArticle;
204
205 /** @var Title */
206 public $mTitle;
207
208 /** @var null|Title */
209 private $mContextTitle = null;
210
211 /** @var string */
212 public $action = 'submit';
213
214 /** @var bool */
215 public $isConflict = false;
216
217 /** @var bool */
218 public $isCssJsSubpage = false;
219
220 /** @var bool */
221 public $isCssSubpage = false;
222
223 /** @var bool */
224 public $isJsSubpage = false;
225
226 /** @var bool */
227 public $isWrongCaseCssJsPage = false;
228
229 /** @var bool New page or new section */
230 public $isNew = false;
231
232 /** @var bool */
233 public $deletedSinceEdit;
234
235 /** @var string */
236 public $formtype;
237
238 /** @var bool */
239 public $firsttime;
240
241 /** @var bool|stdClass */
242 public $lastDelete;
243
244 /** @var bool */
245 public $mTokenOk = false;
246
247 /** @var bool */
248 public $mTokenOkExceptSuffix = false;
249
250 /** @var bool */
251 public $mTriedSave = false;
252
253 /** @var bool */
254 public $incompleteForm = false;
255
256 /** @var bool */
257 public $tooBig = false;
258
259 /** @var bool */
260 public $kblength = false;
261
262 /** @var bool */
263 public $missingComment = false;
264
265 /** @var bool */
266 public $missingSummary = false;
267
268 /** @var bool */
269 public $allowBlankSummary = false;
270
271 /** @var bool */
272 protected $blankArticle = false;
273
274 /** @var bool */
275 protected $allowBlankArticle = false;
276
277 /** @var bool */
278 protected $selfRedirect = false;
279
280 /** @var bool */
281 protected $allowSelfRedirect = false;
282
283 /** @var string */
284 public $autoSumm = '';
285
286 /** @var string */
287 public $hookError = '';
288
289 /** @var ParserOutput */
290 public $mParserOutput;
291
292 /** @var bool Has a summary been preset using GET parameter &summary= ? */
293 public $hasPresetSummary = false;
294
295 /** @var bool */
296 public $mBaseRevision = false;
297
298 /** @var bool */
299 public $mShowSummaryField = true;
300
301 # Form values
302
303 /** @var bool */
304 public $save = false;
305
306 /** @var bool */
307 public $preview = false;
308
309 /** @var bool */
310 public $diff = false;
311
312 /** @var bool */
313 public $minoredit = false;
314
315 /** @var bool */
316 public $watchthis = false;
317
318 /** @var bool */
319 public $recreate = false;
320
321 /** @var string */
322 public $textbox1 = '';
323
324 /** @var string */
325 public $textbox2 = '';
326
327 /** @var string */
328 public $summary = '';
329
330 /** @var bool */
331 public $nosummary = false;
332
333 /** @var string */
334 public $edittime = '';
335
336 /** @var string */
337 public $section = '';
338
339 /** @var string */
340 public $sectiontitle = '';
341
342 /** @var string */
343 public $starttime = '';
344
345 /** @var int */
346 public $oldid = 0;
347
348 /** @var int */
349 public $parentRevId = 0;
350
351 /** @var string */
352 public $editintro = '';
353
354 /** @var null */
355 public $scrolltop = null;
356
357 /** @var bool */
358 public $bot = true;
359
360 /** @var null|string */
361 public $contentModel = null;
362
363 /** @var null|string */
364 public $contentFormat = null;
365
366 /** @var null|array */
367 public $changeTags = null;
368
369 # Placeholders for text injection by hooks (must be HTML)
370 # extensions should take care to _append_ to the present value
371
372 /** @var string Before even the preview */
373 public $editFormPageTop = '';
374 public $editFormTextTop = '';
375 public $editFormTextBeforeContent = '';
376 public $editFormTextAfterWarn = '';
377 public $editFormTextAfterTools = '';
378 public $editFormTextBottom = '';
379 public $editFormTextAfterContent = '';
380 public $previewTextAfterContent = '';
381 public $mPreloadContent = null;
382
383 /* $didSave should be set to true whenever an article was successfully altered. */
384 public $didSave = false;
385 public $undidRev = 0;
386
387 public $suppressIntro = false;
388
389 /** @var bool */
390 protected $edit;
391
392 /**
393 * @var bool Set in ApiEditPage, based on ContentHandler::allowsDirectApiEditing
394 */
395 private $enableApiEditOverride = false;
396
397 /**
398 * @param Article $article
399 */
400 public function __construct( Article $article ) {
401 $this->mArticle = $article;
402 $this->mTitle = $article->getTitle();
403
404 $this->contentModel = $this->mTitle->getContentModel();
405
406 $handler = ContentHandler::getForModelID( $this->contentModel );
407 $this->contentFormat = $handler->getDefaultFormat();
408 }
409
410 /**
411 * @return Article
412 */
413 public function getArticle() {
414 return $this->mArticle;
415 }
416
417 /**
418 * @since 1.19
419 * @return Title
420 */
421 public function getTitle() {
422 return $this->mTitle;
423 }
424
425 /**
426 * Set the context Title object
427 *
428 * @param Title|null $title Title object or null
429 */
430 public function setContextTitle( $title ) {
431 $this->mContextTitle = $title;
432 }
433
434 /**
435 * Get the context title object.
436 * If not set, $wgTitle will be returned. This behavior might change in
437 * the future to return $this->mTitle instead.
438 *
439 * @return Title
440 */
441 public function getContextTitle() {
442 if ( is_null( $this->mContextTitle ) ) {
443 global $wgTitle;
444 return $wgTitle;
445 } else {
446 return $this->mContextTitle;
447 }
448 }
449
450 /**
451 * Returns if the given content model is editable.
452 *
453 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
454 * @return bool
455 * @throws MWException If $modelId has no known handler
456 */
457 public function isSupportedContentModel( $modelId ) {
458 return $this->enableApiEditOverride === true ||
459 ContentHandler::getForModelID( $modelId )->supportsDirectEditing();
460 }
461
462 /**
463 * Allow editing of content that supports API direct editing, but not general
464 * direct editing. Set to false by default.
465 *
466 * @param bool $enableOverride
467 */
468 public function setApiEditOverride( $enableOverride ) {
469 $this->enableApiEditOverride = $enableOverride;
470 }
471
472 function submit() {
473 $this->edit();
474 }
475
476 /**
477 * This is the function that gets called for "action=edit". It
478 * sets up various member variables, then passes execution to
479 * another function, usually showEditForm()
480 *
481 * The edit form is self-submitting, so that when things like
482 * preview and edit conflicts occur, we get the same form back
483 * with the extra stuff added. Only when the final submission
484 * is made and all is well do we actually save and redirect to
485 * the newly-edited page.
486 */
487 function edit() {
488 global $wgOut, $wgRequest, $wgUser;
489 // Allow extensions to modify/prevent this form or submission
490 if ( !Hooks::run( 'AlternateEdit', array( $this ) ) ) {
491 return;
492 }
493
494 wfDebug( __METHOD__ . ": enter\n" );
495
496 // If they used redlink=1 and the page exists, redirect to the main article
497 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
498 $wgOut->redirect( $this->mTitle->getFullURL() );
499 return;
500 }
501
502 $this->importFormData( $wgRequest );
503 $this->firsttime = false;
504
505 if ( wfReadOnly() && $this->save ) {
506 // Force preview
507 $this->save = false;
508 $this->preview = true;
509 }
510
511 if ( $this->save ) {
512 $this->formtype = 'save';
513 } elseif ( $this->preview ) {
514 $this->formtype = 'preview';
515 } elseif ( $this->diff ) {
516 $this->formtype = 'diff';
517 } else { # First time through
518 $this->firsttime = true;
519 if ( $this->previewOnOpen() ) {
520 $this->formtype = 'preview';
521 } else {
522 $this->formtype = 'initial';
523 }
524 }
525
526 $permErrors = $this->getEditPermissionErrors( $this->save ? 'secure' : 'full' );
527 if ( $permErrors ) {
528 wfDebug( __METHOD__ . ": User can't edit\n" );
529 // Auto-block user's IP if the account was "hard" blocked
530 $user = $wgUser;
531 DeferredUpdates::addCallableUpdate( function() use ( $user ) {
532 $user->spreadAnyEditBlock();
533 } );
534
535 $this->displayPermissionsError( $permErrors );
536
537 return;
538 }
539
540 $revision = $this->mArticle->getRevisionFetched();
541 // Disallow editing revisions with content models different from the current one
542 if ( $revision && $revision->getContentModel() !== $this->contentModel ) {
543 $this->displayViewSourcePage(
544 $this->getContentObject(),
545 wfMessage(
546 'contentmodelediterror',
547 $revision->getContentModel(),
548 $this->contentModel
549 )->plain()
550 );
551 return;
552 }
553
554 $this->isConflict = false;
555 // css / js subpages of user pages get a special treatment
556 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
557 $this->isCssSubpage = $this->mTitle->isCssSubpage();
558 $this->isJsSubpage = $this->mTitle->isJsSubpage();
559 // @todo FIXME: Silly assignment.
560 $this->isWrongCaseCssJsPage = $this->isWrongCaseCssJsPage();
561
562 # Show applicable editing introductions
563 if ( $this->formtype == 'initial' || $this->firsttime ) {
564 $this->showIntro();
565 }
566
567 # Attempt submission here. This will check for edit conflicts,
568 # and redundantly check for locked database, blocked IPs, etc.
569 # that edit() already checked just in case someone tries to sneak
570 # in the back door with a hand-edited submission URL.
571
572 if ( 'save' == $this->formtype ) {
573 $resultDetails = null;
574 $status = $this->attemptSave( $resultDetails );
575 if ( !$this->handleStatus( $status, $resultDetails ) ) {
576 return;
577 }
578 }
579
580 # First time through: get contents, set time for conflict
581 # checking, etc.
582 if ( 'initial' == $this->formtype || $this->firsttime ) {
583 if ( $this->initialiseForm() === false ) {
584 $this->noSuchSectionPage();
585 return;
586 }
587
588 if ( !$this->mTitle->getArticleID() ) {
589 Hooks::run( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
590 } else {
591 Hooks::run( 'EditFormInitialText', array( $this ) );
592 }
593
594 }
595
596 $this->showEditForm();
597 }
598
599 /**
600 * @param string $rigor Same format as Title::getUserPermissionErrors()
601 * @return array
602 */
603 protected function getEditPermissionErrors( $rigor = 'secure' ) {
604 global $wgUser;
605
606 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser, $rigor );
607 # Can this title be created?
608 if ( !$this->mTitle->exists() ) {
609 $permErrors = array_merge(
610 $permErrors,
611 wfArrayDiff2(
612 $this->mTitle->getUserPermissionsErrors( 'create', $wgUser, $rigor ),
613 $permErrors
614 )
615 );
616 }
617 # Ignore some permissions errors when a user is just previewing/viewing diffs
618 $remove = array();
619 foreach ( $permErrors as $error ) {
620 if ( ( $this->preview || $this->diff )
621 && ( $error[0] == 'blockedtext' || $error[0] == 'autoblockedtext' )
622 ) {
623 $remove[] = $error;
624 }
625 }
626 $permErrors = wfArrayDiff2( $permErrors, $remove );
627
628 return $permErrors;
629 }
630
631 /**
632 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
633 * but with the following differences:
634 * - If redlink=1, the user will be redirected to the page
635 * - If there is content to display or the error occurs while either saving,
636 * previewing or showing the difference, it will be a
637 * "View source for ..." page displaying the source code after the error message.
638 *
639 * @since 1.19
640 * @param array $permErrors Array of permissions errors, as returned by
641 * Title::getUserPermissionsErrors().
642 * @throws PermissionsError
643 */
644 protected function displayPermissionsError( array $permErrors ) {
645 global $wgRequest, $wgOut;
646
647 if ( $wgRequest->getBool( 'redlink' ) ) {
648 // The edit page was reached via a red link.
649 // Redirect to the article page and let them click the edit tab if
650 // they really want a permission error.
651 $wgOut->redirect( $this->mTitle->getFullURL() );
652 return;
653 }
654
655 $content = $this->getContentObject();
656
657 # Use the normal message if there's nothing to display
658 if ( $this->firsttime && ( !$content || $content->isEmpty() ) ) {
659 $action = $this->mTitle->exists() ? 'edit' :
660 ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
661 throw new PermissionsError( $action, $permErrors );
662 }
663
664 $this->displayViewSourcePage(
665 $content,
666 $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' )
667 );
668 }
669
670 /**
671 * Display a read-only View Source page
672 * @param Content $content content object
673 * @param string $errorMessage additional wikitext error message to display
674 */
675 protected function displayViewSourcePage( Content $content, $errorMessage = '' ) {
676 global $wgOut;
677
678 Hooks::run( 'EditPage::showReadOnlyForm:initial', array( $this, &$wgOut ) );
679
680 $wgOut->setRobotPolicy( 'noindex,nofollow' );
681 $wgOut->setPageTitle( wfMessage(
682 'viewsource-title',
683 $this->getContextTitle()->getPrefixedText()
684 ) );
685 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
686 $wgOut->addHTML( $this->editFormPageTop );
687 $wgOut->addHTML( $this->editFormTextTop );
688
689 if ( $errorMessage !== '' ) {
690 $wgOut->addWikiText( $errorMessage );
691 $wgOut->addHTML( "<hr />\n" );
692 }
693
694 # If the user made changes, preserve them when showing the markup
695 # (This happens when a user is blocked during edit, for instance)
696 if ( !$this->firsttime ) {
697 $text = $this->textbox1;
698 $wgOut->addWikiMsg( 'viewyourtext' );
699 } else {
700 try {
701 $text = $this->toEditText( $content );
702 } catch ( MWException $e ) {
703 # Serialize using the default format if the content model is not supported
704 # (e.g. for an old revision with a different model)
705 $text = $content->serialize();
706 }
707 $wgOut->addWikiMsg( 'viewsourcetext' );
708 }
709
710 $wgOut->addHTML( $this->editFormTextBeforeContent );
711 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
712 $wgOut->addHTML( $this->editFormTextAfterContent );
713
714 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
715 Linker::formatTemplates( $this->getTemplates() ) ) );
716
717 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
718
719 $wgOut->addHTML( $this->editFormTextBottom );
720 if ( $this->mTitle->exists() ) {
721 $wgOut->returnToMain( null, $this->mTitle );
722 }
723 }
724
725 /**
726 * Should we show a preview when the edit form is first shown?
727 *
728 * @return bool
729 */
730 protected function previewOnOpen() {
731 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
732 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
733 // Explicit override from request
734 return true;
735 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
736 // Explicit override from request
737 return false;
738 } elseif ( $this->section == 'new' ) {
739 // Nothing *to* preview for new sections
740 return false;
741 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() )
742 && $wgUser->getOption( 'previewonfirst' )
743 ) {
744 // Standard preference behavior
745 return true;
746 } elseif ( !$this->mTitle->exists()
747 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
748 && $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()]
749 ) {
750 // Categories are special
751 return true;
752 } else {
753 return false;
754 }
755 }
756
757 /**
758 * Checks whether the user entered a skin name in uppercase,
759 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
760 *
761 * @return bool
762 */
763 protected function isWrongCaseCssJsPage() {
764 if ( $this->mTitle->isCssJsSubpage() ) {
765 $name = $this->mTitle->getSkinFromCssJsSubpage();
766 $skins = array_merge(
767 array_keys( Skin::getSkinNames() ),
768 array( 'common' )
769 );
770 return !in_array( $name, $skins )
771 && in_array( strtolower( $name ), $skins );
772 } else {
773 return false;
774 }
775 }
776
777 /**
778 * Returns whether section editing is supported for the current page.
779 * Subclasses may override this to replace the default behavior, which is
780 * to check ContentHandler::supportsSections.
781 *
782 * @return bool True if this edit page supports sections, false otherwise.
783 */
784 protected function isSectionEditSupported() {
785 $contentHandler = ContentHandler::getForTitle( $this->mTitle );
786 return $contentHandler->supportsSections();
787 }
788
789 /**
790 * This function collects the form data and uses it to populate various member variables.
791 * @param WebRequest $request
792 * @throws ErrorPageError
793 */
794 function importFormData( &$request ) {
795 global $wgContLang, $wgUser;
796
797 # Section edit can come from either the form or a link
798 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
799
800 if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
801 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
802 }
803
804 $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
805
806 if ( $request->wasPosted() ) {
807 # These fields need to be checked for encoding.
808 # Also remove trailing whitespace, but don't remove _initial_
809 # whitespace from the text boxes. This may be significant formatting.
810 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
811 if ( !$request->getCheck( 'wpTextbox2' ) ) {
812 // Skip this if wpTextbox2 has input, it indicates that we came
813 // from a conflict page with raw page text, not a custom form
814 // modified by subclasses
815 $textbox1 = $this->importContentFormData( $request );
816 if ( $textbox1 !== null ) {
817 $this->textbox1 = $textbox1;
818 }
819 }
820
821 # Truncate for whole multibyte characters
822 $this->summary = $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
823
824 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
825 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
826 # section titles.
827 $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
828
829 # Treat sectiontitle the same way as summary.
830 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
831 # currently doing double duty as both edit summary and section title. Right now this
832 # is just to allow API edits to work around this limitation, but this should be
833 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
834 $this->sectiontitle = $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
835 $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
836
837 $this->edittime = $request->getVal( 'wpEdittime' );
838 $this->starttime = $request->getVal( 'wpStarttime' );
839
840 $undidRev = $request->getInt( 'wpUndidRevision' );
841 if ( $undidRev ) {
842 $this->undidRev = $undidRev;
843 }
844
845 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
846
847 if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
848 // wpTextbox1 field is missing, possibly due to being "too big"
849 // according to some filter rules such as Suhosin's setting for
850 // suhosin.request.max_value_length (d'oh)
851 $this->incompleteForm = true;
852 } else {
853 // If we receive the last parameter of the request, we can fairly
854 // claim the POST request has not been truncated.
855
856 // TODO: softened the check for cutover. Once we determine
857 // that it is safe, we should complete the transition by
858 // removing the "edittime" clause.
859 $this->incompleteForm = ( !$request->getVal( 'wpUltimateParam' )
860 && is_null( $this->edittime ) );
861 }
862 if ( $this->incompleteForm ) {
863 # If the form is incomplete, force to preview.
864 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
865 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
866 $this->preview = true;
867 } else {
868 $this->preview = $request->getCheck( 'wpPreview' );
869 $this->diff = $request->getCheck( 'wpDiff' );
870
871 // Remember whether a save was requested, so we can indicate
872 // if we forced preview due to session failure.
873 $this->mTriedSave = !$this->preview;
874
875 if ( $this->tokenOk( $request ) ) {
876 # Some browsers will not report any submit button
877 # if the user hits enter in the comment box.
878 # The unmarked state will be assumed to be a save,
879 # if the form seems otherwise complete.
880 wfDebug( __METHOD__ . ": Passed token check.\n" );
881 } elseif ( $this->diff ) {
882 # Failed token check, but only requested "Show Changes".
883 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
884 } else {
885 # Page might be a hack attempt posted from
886 # an external site. Preview instead of saving.
887 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
888 $this->preview = true;
889 }
890 }
891 $this->save = !$this->preview && !$this->diff;
892 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
893 $this->edittime = null;
894 }
895
896 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
897 $this->starttime = null;
898 }
899
900 $this->recreate = $request->getCheck( 'wpRecreate' );
901
902 $this->minoredit = $request->getCheck( 'wpMinoredit' );
903 $this->watchthis = $request->getCheck( 'wpWatchthis' );
904
905 # Don't force edit summaries when a user is editing their own user or talk page
906 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK )
907 && $this->mTitle->getText() == $wgUser->getName()
908 ) {
909 $this->allowBlankSummary = true;
910 } else {
911 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' )
912 || !$wgUser->getOption( 'forceeditsummary' );
913 }
914
915 $this->autoSumm = $request->getText( 'wpAutoSummary' );
916
917 $this->allowBlankArticle = $request->getBool( 'wpIgnoreBlankArticle' );
918 $this->allowSelfRedirect = $request->getBool( 'wpIgnoreSelfRedirect' );
919
920 $changeTags = $request->getVal( 'wpChangeTags' );
921 if ( is_null( $changeTags ) || $changeTags === '' ) {
922 $this->changeTags = array();
923 } else {
924 $this->changeTags = array_filter( array_map( 'trim', explode( ',',
925 $changeTags ) ) );
926 }
927 } else {
928 # Not a posted form? Start with nothing.
929 wfDebug( __METHOD__ . ": Not a posted form.\n" );
930 $this->textbox1 = '';
931 $this->summary = '';
932 $this->sectiontitle = '';
933 $this->edittime = '';
934 $this->starttime = wfTimestampNow();
935 $this->edit = false;
936 $this->preview = false;
937 $this->save = false;
938 $this->diff = false;
939 $this->minoredit = false;
940 // Watch may be overridden by request parameters
941 $this->watchthis = $request->getBool( 'watchthis', false );
942 $this->recreate = false;
943
944 // When creating a new section, we can preload a section title by passing it as the
945 // preloadtitle parameter in the URL (Bug 13100)
946 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
947 $this->sectiontitle = $request->getVal( 'preloadtitle' );
948 // Once wpSummary isn't being use for setting section titles, we should delete this.
949 $this->summary = $request->getVal( 'preloadtitle' );
950 } elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
951 $this->summary = $request->getText( 'summary' );
952 if ( $this->summary !== '' ) {
953 $this->hasPresetSummary = true;
954 }
955 }
956
957 if ( $request->getVal( 'minor' ) ) {
958 $this->minoredit = true;
959 }
960 }
961
962 $this->oldid = $request->getInt( 'oldid' );
963 $this->parentRevId = $request->getInt( 'parentRevId' );
964
965 $this->bot = $request->getBool( 'bot', true );
966 $this->nosummary = $request->getBool( 'nosummary' );
967
968 // May be overridden by revision.
969 $this->contentModel = $request->getText( 'model', $this->contentModel );
970 // May be overridden by revision.
971 $this->contentFormat = $request->getText( 'format', $this->contentFormat );
972
973 if ( !ContentHandler::getForModelID( $this->contentModel )
974 ->isSupportedFormat( $this->contentFormat )
975 ) {
976 throw new ErrorPageError(
977 'editpage-notsupportedcontentformat-title',
978 'editpage-notsupportedcontentformat-text',
979 array( $this->contentFormat, ContentHandler::getLocalizedName( $this->contentModel ) )
980 );
981 }
982
983 /**
984 * @todo Check if the desired model is allowed in this namespace, and if
985 * a transition from the page's current model to the new model is
986 * allowed.
987 */
988
989 $this->editintro = $request->getText( 'editintro',
990 // Custom edit intro for new sections
991 $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
992
993 // Allow extensions to modify form data
994 Hooks::run( 'EditPage::importFormData', array( $this, $request ) );
995
996 }
997
998 /**
999 * Subpage overridable method for extracting the page content data from the
1000 * posted form to be placed in $this->textbox1, if using customized input
1001 * this method should be overridden and return the page text that will be used
1002 * for saving, preview parsing and so on...
1003 *
1004 * @param WebRequest $request
1005 */
1006 protected function importContentFormData( &$request ) {
1007 return; // Don't do anything, EditPage already extracted wpTextbox1
1008 }
1009
1010 /**
1011 * Initialise form fields in the object
1012 * Called on the first invocation, e.g. when a user clicks an edit link
1013 * @return bool If the requested section is valid
1014 */
1015 function initialiseForm() {
1016 global $wgUser;
1017 $this->edittime = $this->mArticle->getTimestamp();
1018
1019 $content = $this->getContentObject( false ); # TODO: track content object?!
1020 if ( $content === false ) {
1021 return false;
1022 }
1023 $this->textbox1 = $this->toEditText( $content );
1024
1025 // activate checkboxes if user wants them to be always active
1026 # Sort out the "watch" checkbox
1027 if ( $wgUser->getOption( 'watchdefault' ) ) {
1028 # Watch all edits
1029 $this->watchthis = true;
1030 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1031 # Watch creations
1032 $this->watchthis = true;
1033 } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
1034 # Already watched
1035 $this->watchthis = true;
1036 }
1037 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
1038 $this->minoredit = true;
1039 }
1040 if ( $this->textbox1 === false ) {
1041 return false;
1042 }
1043 return true;
1044 }
1045
1046 /**
1047 * @param Content|null $def_content The default value to return
1048 *
1049 * @return Content|null Content on success, $def_content for invalid sections
1050 *
1051 * @since 1.21
1052 */
1053 protected function getContentObject( $def_content = null ) {
1054 global $wgOut, $wgRequest, $wgUser, $wgContLang;
1055
1056 $content = false;
1057
1058 // For message page not locally set, use the i18n message.
1059 // For other non-existent articles, use preload text if any.
1060 if ( !$this->mTitle->exists() || $this->section == 'new' ) {
1061 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
1062 # If this is a system message, get the default text.
1063 $msg = $this->mTitle->getDefaultMessageText();
1064
1065 $content = $this->toEditContent( $msg );
1066 }
1067 if ( $content === false ) {
1068 # If requested, preload some text.
1069 $preload = $wgRequest->getVal( 'preload',
1070 // Custom preload text for new sections
1071 $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
1072 $params = $wgRequest->getArray( 'preloadparams', array() );
1073
1074 $content = $this->getPreloadedContent( $preload, $params );
1075 }
1076 // For existing pages, get text based on "undo" or section parameters.
1077 } else {
1078 if ( $this->section != '' ) {
1079 // Get section edit text (returns $def_text for invalid sections)
1080 $orig = $this->getOriginalContent( $wgUser );
1081 $content = $orig ? $orig->getSection( $this->section ) : null;
1082
1083 if ( !$content ) {
1084 $content = $def_content;
1085 }
1086 } else {
1087 $undoafter = $wgRequest->getInt( 'undoafter' );
1088 $undo = $wgRequest->getInt( 'undo' );
1089
1090 if ( $undo > 0 && $undoafter > 0 ) {
1091 $undorev = Revision::newFromId( $undo );
1092 $oldrev = Revision::newFromId( $undoafter );
1093
1094 # Sanity check, make sure it's the right page,
1095 # the revisions exist and they were not deleted.
1096 # Otherwise, $content will be left as-is.
1097 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
1098 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
1099 !$oldrev->isDeleted( Revision::DELETED_TEXT )
1100 ) {
1101 $content = $this->mArticle->getUndoContent( $undorev, $oldrev );
1102
1103 if ( $content === false ) {
1104 # Warn the user that something went wrong
1105 $undoMsg = 'failure';
1106 } else {
1107 $oldContent = $this->mArticle->getPage()->getContent( Revision::RAW );
1108 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
1109 $newContent = $content->preSaveTransform( $this->mTitle, $wgUser, $popts );
1110
1111 if ( $newContent->equals( $oldContent ) ) {
1112 # Tell the user that the undo results in no change,
1113 # i.e. the revisions were already undone.
1114 $undoMsg = 'nochange';
1115 $content = false;
1116 } else {
1117 # Inform the user of our success and set an automatic edit summary
1118 $undoMsg = 'success';
1119
1120 # If we just undid one rev, use an autosummary
1121 $firstrev = $oldrev->getNext();
1122 if ( $firstrev && $firstrev->getId() == $undo ) {
1123 $userText = $undorev->getUserText();
1124 if ( $userText === '' ) {
1125 $undoSummary = wfMessage(
1126 'undo-summary-username-hidden',
1127 $undo
1128 )->inContentLanguage()->text();
1129 } else {
1130 $undoSummary = wfMessage(
1131 'undo-summary',
1132 $undo,
1133 $userText
1134 )->inContentLanguage()->text();
1135 }
1136 if ( $this->summary === '' ) {
1137 $this->summary = $undoSummary;
1138 } else {
1139 $this->summary = $undoSummary . wfMessage( 'colon-separator' )
1140 ->inContentLanguage()->text() . $this->summary;
1141 }
1142 $this->undidRev = $undo;
1143 }
1144 $this->formtype = 'diff';
1145 }
1146 }
1147 } else {
1148 // Failed basic sanity checks.
1149 // Older revisions may have been removed since the link
1150 // was created, or we may simply have got bogus input.
1151 $undoMsg = 'norev';
1152 }
1153
1154 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
1155 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
1156 $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
1157 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1158 }
1159
1160 if ( $content === false ) {
1161 $content = $this->getOriginalContent( $wgUser );
1162 }
1163 }
1164 }
1165
1166 return $content;
1167 }
1168
1169 /**
1170 * Get the content of the wanted revision, without section extraction.
1171 *
1172 * The result of this function can be used to compare user's input with
1173 * section replaced in its context (using WikiPage::replaceSection())
1174 * to the original text of the edit.
1175 *
1176 * This differs from Article::getContent() that when a missing revision is
1177 * encountered the result will be null and not the
1178 * 'missing-revision' message.
1179 *
1180 * @since 1.19
1181 * @param User $user The user to get the revision for
1182 * @return Content|null
1183 */
1184 private function getOriginalContent( User $user ) {
1185 if ( $this->section == 'new' ) {
1186 return $this->getCurrentContent();
1187 }
1188 $revision = $this->mArticle->getRevisionFetched();
1189 if ( $revision === null ) {
1190 if ( !$this->contentModel ) {
1191 $this->contentModel = $this->getTitle()->getContentModel();
1192 }
1193 $handler = ContentHandler::getForModelID( $this->contentModel );
1194
1195 return $handler->makeEmptyContent();
1196 }
1197 $content = $revision->getContent( Revision::FOR_THIS_USER, $user );
1198 return $content;
1199 }
1200
1201 /**
1202 * Get the current content of the page. This is basically similar to
1203 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1204 * content object is returned instead of null.
1205 *
1206 * @since 1.21
1207 * @return Content
1208 */
1209 protected function getCurrentContent() {
1210 $rev = $this->mArticle->getRevision();
1211 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1212
1213 if ( $content === false || $content === null ) {
1214 if ( !$this->contentModel ) {
1215 $this->contentModel = $this->getTitle()->getContentModel();
1216 }
1217 $handler = ContentHandler::getForModelID( $this->contentModel );
1218
1219 return $handler->makeEmptyContent();
1220 } else {
1221 # nasty side-effect, but needed for consistency
1222 $this->contentModel = $rev->getContentModel();
1223 $this->contentFormat = $rev->getContentFormat();
1224
1225 return $content;
1226 }
1227 }
1228
1229 /**
1230 * Use this method before edit() to preload some content into the edit box
1231 *
1232 * @param Content $content
1233 *
1234 * @since 1.21
1235 */
1236 public function setPreloadedContent( Content $content ) {
1237 $this->mPreloadContent = $content;
1238 }
1239
1240 /**
1241 * Get the contents to be preloaded into the box, either set by
1242 * an earlier setPreloadText() or by loading the given page.
1243 *
1244 * @param string $preload Representing the title to preload from.
1245 * @param array $params Parameters to use (interface-message style) in the preloaded text
1246 *
1247 * @return Content
1248 *
1249 * @since 1.21
1250 */
1251 protected function getPreloadedContent( $preload, $params = array() ) {
1252 global $wgUser;
1253
1254 if ( !empty( $this->mPreloadContent ) ) {
1255 return $this->mPreloadContent;
1256 }
1257
1258 $handler = ContentHandler::getForTitle( $this->getTitle() );
1259
1260 if ( $preload === '' ) {
1261 return $handler->makeEmptyContent();
1262 }
1263
1264 $title = Title::newFromText( $preload );
1265 # Check for existence to avoid getting MediaWiki:Noarticletext
1266 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1267 // TODO: somehow show a warning to the user!
1268 return $handler->makeEmptyContent();
1269 }
1270
1271 $page = WikiPage::factory( $title );
1272 if ( $page->isRedirect() ) {
1273 $title = $page->getRedirectTarget();
1274 # Same as before
1275 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1276 // TODO: somehow show a warning to the user!
1277 return $handler->makeEmptyContent();
1278 }
1279 $page = WikiPage::factory( $title );
1280 }
1281
1282 $parserOptions = ParserOptions::newFromUser( $wgUser );
1283 $content = $page->getContent( Revision::RAW );
1284
1285 if ( !$content ) {
1286 // TODO: somehow show a warning to the user!
1287 return $handler->makeEmptyContent();
1288 }
1289
1290 if ( $content->getModel() !== $handler->getModelID() ) {
1291 $converted = $content->convert( $handler->getModelID() );
1292
1293 if ( !$converted ) {
1294 // TODO: somehow show a warning to the user!
1295 wfDebug( "Attempt to preload incompatible content: " .
1296 "can't convert " . $content->getModel() .
1297 " to " . $handler->getModelID() );
1298
1299 return $handler->makeEmptyContent();
1300 }
1301
1302 $content = $converted;
1303 }
1304
1305 return $content->preloadTransform( $title, $parserOptions, $params );
1306 }
1307
1308 /**
1309 * Make sure the form isn't faking a user's credentials.
1310 *
1311 * @param WebRequest $request
1312 * @return bool
1313 * @private
1314 */
1315 function tokenOk( &$request ) {
1316 global $wgUser;
1317 $token = $request->getVal( 'wpEditToken' );
1318 $this->mTokenOk = $wgUser->matchEditToken( $token );
1319 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
1320 return $this->mTokenOk;
1321 }
1322
1323 /**
1324 * Sets post-edit cookie indicating the user just saved a particular revision.
1325 *
1326 * This uses a temporary cookie for each revision ID so separate saves will never
1327 * interfere with each other.
1328 *
1329 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1330 * the redirect. It must be clearable by JavaScript code, so it must not be
1331 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1332 * variable.
1333 *
1334 * If the variable were set on the server, it would be cached, which is unwanted
1335 * since the post-edit state should only apply to the load right after the save.
1336 *
1337 * @param int $statusValue The status value (to check for new article status)
1338 */
1339 protected function setPostEditCookie( $statusValue ) {
1340 $revisionId = $this->mArticle->getLatest();
1341 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1342
1343 $val = 'saved';
1344 if ( $statusValue == self::AS_SUCCESS_NEW_ARTICLE ) {
1345 $val = 'created';
1346 } elseif ( $this->oldid ) {
1347 $val = 'restored';
1348 }
1349
1350 $response = RequestContext::getMain()->getRequest()->response();
1351 $response->setCookie( $postEditKey, $val, time() + self::POST_EDIT_COOKIE_DURATION, array(
1352 'httpOnly' => false,
1353 ) );
1354 }
1355
1356 /**
1357 * Attempt submission
1358 * @param array $resultDetails See docs for $result in internalAttemptSave
1359 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1360 * @return Status The resulting status object.
1361 */
1362 public function attemptSave( &$resultDetails = false ) {
1363 global $wgUser;
1364
1365 # Allow bots to exempt some edits from bot flagging
1366 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
1367 $status = $this->internalAttemptSave( $resultDetails, $bot );
1368
1369 Hooks::run( 'EditPage::attemptSave:after', array( $this, $status, $resultDetails ) );
1370
1371 return $status;
1372 }
1373
1374 /**
1375 * Handle status, such as after attempt save
1376 *
1377 * @param Status $status
1378 * @param array|bool $resultDetails
1379 *
1380 * @throws ErrorPageError
1381 * @return bool False, if output is done, true if rest of the form should be displayed
1382 */
1383 private function handleStatus( Status $status, $resultDetails ) {
1384 global $wgUser, $wgOut;
1385
1386 /**
1387 * @todo FIXME: once the interface for internalAttemptSave() is made
1388 * nicer, this should use the message in $status
1389 */
1390 if ( $status->value == self::AS_SUCCESS_UPDATE
1391 || $status->value == self::AS_SUCCESS_NEW_ARTICLE
1392 ) {
1393 $this->didSave = true;
1394 if ( !$resultDetails['nullEdit'] ) {
1395 $this->setPostEditCookie( $status->value );
1396 }
1397 }
1398
1399 switch ( $status->value ) {
1400 case self::AS_HOOK_ERROR_EXPECTED:
1401 case self::AS_CONTENT_TOO_BIG:
1402 case self::AS_ARTICLE_WAS_DELETED:
1403 case self::AS_CONFLICT_DETECTED:
1404 case self::AS_SUMMARY_NEEDED:
1405 case self::AS_TEXTBOX_EMPTY:
1406 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1407 case self::AS_END:
1408 case self::AS_BLANK_ARTICLE:
1409 case self::AS_SELF_REDIRECT:
1410 return true;
1411
1412 case self::AS_HOOK_ERROR:
1413 return false;
1414
1415 case self::AS_CANNOT_USE_CUSTOM_MODEL:
1416 case self::AS_PARSE_ERROR:
1417 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1418 return true;
1419
1420 case self::AS_SUCCESS_NEW_ARTICLE:
1421 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1422 $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
1423 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1424 return false;
1425
1426 case self::AS_SUCCESS_UPDATE:
1427 $extraQuery = '';
1428 $sectionanchor = $resultDetails['sectionanchor'];
1429
1430 // Give extensions a chance to modify URL query on update
1431 Hooks::run(
1432 'ArticleUpdateBeforeRedirect',
1433 array( $this->mArticle, &$sectionanchor, &$extraQuery )
1434 );
1435
1436 if ( $resultDetails['redirect'] ) {
1437 if ( $extraQuery == '' ) {
1438 $extraQuery = 'redirect=no';
1439 } else {
1440 $extraQuery = 'redirect=no&' . $extraQuery;
1441 }
1442 }
1443 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1444 return false;
1445
1446 case self::AS_SPAM_ERROR:
1447 $this->spamPageWithContent( $resultDetails['spam'] );
1448 return false;
1449
1450 case self::AS_BLOCKED_PAGE_FOR_USER:
1451 throw new UserBlockedError( $wgUser->getBlock() );
1452
1453 case self::AS_IMAGE_REDIRECT_ANON:
1454 case self::AS_IMAGE_REDIRECT_LOGGED:
1455 throw new PermissionsError( 'upload' );
1456
1457 case self::AS_READ_ONLY_PAGE_ANON:
1458 case self::AS_READ_ONLY_PAGE_LOGGED:
1459 throw new PermissionsError( 'edit' );
1460
1461 case self::AS_READ_ONLY_PAGE:
1462 throw new ReadOnlyError;
1463
1464 case self::AS_RATE_LIMITED:
1465 throw new ThrottledError();
1466
1467 case self::AS_NO_CREATE_PERMISSION:
1468 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1469 throw new PermissionsError( $permission );
1470
1471 case self::AS_NO_CHANGE_CONTENT_MODEL:
1472 throw new PermissionsError( 'editcontentmodel' );
1473
1474 default:
1475 // We don't recognize $status->value. The only way that can happen
1476 // is if an extension hook aborted from inside ArticleSave.
1477 // Render the status object into $this->hookError
1478 // FIXME this sucks, we should just use the Status object throughout
1479 $this->hookError = '<div class="error">' . $status->getWikitext() .
1480 '</div>';
1481 return true;
1482 }
1483 }
1484
1485 /**
1486 * Run hooks that can filter edits just before they get saved.
1487 *
1488 * @param Content $content The Content to filter.
1489 * @param Status $status For reporting the outcome to the caller
1490 * @param User $user The user performing the edit
1491 *
1492 * @return bool
1493 */
1494 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1495 // Run old style post-section-merge edit filter
1496 if ( !ContentHandler::runLegacyHooks( 'EditFilterMerged',
1497 array( $this, $content, &$this->hookError, $this->summary ) )
1498 ) {
1499 # Error messages etc. could be handled within the hook...
1500 $status->fatal( 'hookaborted' );
1501 $status->value = self::AS_HOOK_ERROR;
1502 return false;
1503 } elseif ( $this->hookError != '' ) {
1504 # ...or the hook could be expecting us to produce an error
1505 $status->fatal( 'hookaborted' );
1506 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1507 return false;
1508 }
1509
1510 // Run new style post-section-merge edit filter
1511 if ( !Hooks::run( 'EditFilterMergedContent',
1512 array( $this->mArticle->getContext(), $content, $status, $this->summary,
1513 $user, $this->minoredit ) )
1514 ) {
1515 # Error messages etc. could be handled within the hook...
1516 if ( $status->isGood() ) {
1517 $status->fatal( 'hookaborted' );
1518 // Not setting $this->hookError here is a hack to allow the hook
1519 // to cause a return to the edit page without $this->hookError
1520 // being set. This is used by ConfirmEdit to display a captcha
1521 // without any error message cruft.
1522 } else {
1523 $this->hookError = $status->getWikiText();
1524 }
1525 // Use the existing $status->value if the hook set it
1526 if ( !$status->value ) {
1527 $status->value = self::AS_HOOK_ERROR;
1528 }
1529 return false;
1530 } elseif ( !$status->isOK() ) {
1531 # ...or the hook could be expecting us to produce an error
1532 // FIXME this sucks, we should just use the Status object throughout
1533 $this->hookError = $status->getWikiText();
1534 $status->fatal( 'hookaborted' );
1535 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1536 return false;
1537 }
1538
1539 return true;
1540 }
1541
1542 /**
1543 * Return the summary to be used for a new section.
1544 *
1545 * @param string $sectionanchor Set to the section anchor text
1546 * @return string
1547 */
1548 private function newSectionSummary( &$sectionanchor = null ) {
1549 global $wgParser;
1550
1551 if ( $this->sectiontitle !== '' ) {
1552 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1553 // If no edit summary was specified, create one automatically from the section
1554 // title and have it link to the new section. Otherwise, respect the summary as
1555 // passed.
1556 if ( $this->summary === '' ) {
1557 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1558 return wfMessage( 'newsectionsummary' )
1559 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1560 }
1561 } elseif ( $this->summary !== '' ) {
1562 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1563 # This is a new section, so create a link to the new section
1564 # in the revision summary.
1565 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1566 return wfMessage( 'newsectionsummary' )
1567 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1568 }
1569 return $this->summary;
1570 }
1571
1572 /**
1573 * Attempt submission (no UI)
1574 *
1575 * @param array $result Array to add statuses to, currently with the
1576 * possible keys:
1577 * - spam (string): Spam string from content if any spam is detected by
1578 * matchSpamRegex.
1579 * - sectionanchor (string): Section anchor for a section save.
1580 * - nullEdit (boolean): Set if doEditContent is OK. True if null edit,
1581 * false otherwise.
1582 * - redirect (bool): Set if doEditContent is OK. True if resulting
1583 * revision is a redirect.
1584 * @param bool $bot True if edit is being made under the bot right.
1585 *
1586 * @return Status Status object, possibly with a message, but always with
1587 * one of the AS_* constants in $status->value,
1588 *
1589 * @todo FIXME: This interface is TERRIBLE, but hard to get rid of due to
1590 * various error display idiosyncrasies. There are also lots of cases
1591 * where error metadata is set in the object and retrieved later instead
1592 * of being returned, e.g. AS_CONTENT_TOO_BIG and
1593 * AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some
1594 * time.
1595 */
1596 function internalAttemptSave( &$result, $bot = false ) {
1597 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1598 global $wgContentHandlerUseDB;
1599
1600 $status = Status::newGood();
1601
1602 if ( !Hooks::run( 'EditPage::attemptSave', array( $this ) ) ) {
1603 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1604 $status->fatal( 'hookaborted' );
1605 $status->value = self::AS_HOOK_ERROR;
1606 return $status;
1607 }
1608
1609 $spam = $wgRequest->getText( 'wpAntispam' );
1610 if ( $spam !== '' ) {
1611 wfDebugLog(
1612 'SimpleAntiSpam',
1613 $wgUser->getName() .
1614 ' editing "' .
1615 $this->mTitle->getPrefixedText() .
1616 '" submitted bogus field "' .
1617 $spam .
1618 '"'
1619 );
1620 $status->fatal( 'spamprotectionmatch', false );
1621 $status->value = self::AS_SPAM_ERROR;
1622 return $status;
1623 }
1624
1625 try {
1626 # Construct Content object
1627 $textbox_content = $this->toEditContent( $this->textbox1 );
1628 } catch ( MWContentSerializationException $ex ) {
1629 $status->fatal(
1630 'content-failed-to-parse',
1631 $this->contentModel,
1632 $this->contentFormat,
1633 $ex->getMessage()
1634 );
1635 $status->value = self::AS_PARSE_ERROR;
1636 return $status;
1637 }
1638
1639 # Check image redirect
1640 if ( $this->mTitle->getNamespace() == NS_FILE &&
1641 $textbox_content->isRedirect() &&
1642 !$wgUser->isAllowed( 'upload' )
1643 ) {
1644 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1645 $status->setResult( false, $code );
1646
1647 return $status;
1648 }
1649
1650 # Check for spam
1651 $match = self::matchSummarySpamRegex( $this->summary );
1652 if ( $match === false && $this->section == 'new' ) {
1653 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1654 # regular summaries, it is added to the actual wikitext.
1655 if ( $this->sectiontitle !== '' ) {
1656 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1657 $match = self::matchSpamRegex( $this->sectiontitle );
1658 } else {
1659 # This branch is taken when the "Add Topic" user interface is used, or the API
1660 # is used with the 'summary' parameter.
1661 $match = self::matchSpamRegex( $this->summary );
1662 }
1663 }
1664 if ( $match === false ) {
1665 $match = self::matchSpamRegex( $this->textbox1 );
1666 }
1667 if ( $match !== false ) {
1668 $result['spam'] = $match;
1669 $ip = $wgRequest->getIP();
1670 $pdbk = $this->mTitle->getPrefixedDBkey();
1671 $match = str_replace( "\n", '', $match );
1672 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1673 $status->fatal( 'spamprotectionmatch', $match );
1674 $status->value = self::AS_SPAM_ERROR;
1675 return $status;
1676 }
1677 if ( !Hooks::run(
1678 'EditFilter',
1679 array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) )
1680 ) {
1681 # Error messages etc. could be handled within the hook...
1682 $status->fatal( 'hookaborted' );
1683 $status->value = self::AS_HOOK_ERROR;
1684 return $status;
1685 } elseif ( $this->hookError != '' ) {
1686 # ...or the hook could be expecting us to produce an error
1687 $status->fatal( 'hookaborted' );
1688 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1689 return $status;
1690 }
1691
1692 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1693 // Auto-block user's IP if the account was "hard" blocked
1694 $wgUser->spreadAnyEditBlock();
1695 # Check block state against master, thus 'false'.
1696 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1697 return $status;
1698 }
1699
1700 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1701 if ( $this->kblength > $wgMaxArticleSize ) {
1702 // Error will be displayed by showEditForm()
1703 $this->tooBig = true;
1704 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1705 return $status;
1706 }
1707
1708 if ( !$wgUser->isAllowed( 'edit' ) ) {
1709 if ( $wgUser->isAnon() ) {
1710 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1711 return $status;
1712 } else {
1713 $status->fatal( 'readonlytext' );
1714 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1715 return $status;
1716 }
1717 }
1718
1719 $changingContentModel = false;
1720 if ( $this->contentModel !== $this->mTitle->getContentModel() ) {
1721 if ( !$wgContentHandlerUseDB ) {
1722 $status->fatal( 'editpage-cannot-use-custom-model' );
1723 $status->value = self::AS_CANNOT_USE_CUSTOM_MODEL;
1724 return $status;
1725 } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1726 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1727 return $status;
1728
1729 }
1730 $changingContentModel = true;
1731 $oldContentModel = $this->mTitle->getContentModel();
1732 }
1733
1734 if ( $this->changeTags ) {
1735 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
1736 $this->changeTags, $wgUser );
1737 if ( !$changeTagsStatus->isOK() ) {
1738 $changeTagsStatus->value = self::AS_CHANGE_TAG_ERROR;
1739 return $changeTagsStatus;
1740 }
1741 }
1742
1743 if ( wfReadOnly() ) {
1744 $status->fatal( 'readonlytext' );
1745 $status->value = self::AS_READ_ONLY_PAGE;
1746 return $status;
1747 }
1748 if ( $wgUser->pingLimiter() || $wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1749 $status->fatal( 'actionthrottledtext' );
1750 $status->value = self::AS_RATE_LIMITED;
1751 return $status;
1752 }
1753
1754 # If the article has been deleted while editing, don't save it without
1755 # confirmation
1756 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1757 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1758 return $status;
1759 }
1760
1761 # Load the page data from the master. If anything changes in the meantime,
1762 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1763 $this->mArticle->loadPageData( 'fromdbmaster' );
1764 $new = !$this->mArticle->exists();
1765
1766 if ( $new ) {
1767 // Late check for create permission, just in case *PARANOIA*
1768 if ( !$this->mTitle->userCan( 'create', $wgUser ) ) {
1769 $status->fatal( 'nocreatetext' );
1770 $status->value = self::AS_NO_CREATE_PERMISSION;
1771 wfDebug( __METHOD__ . ": no create permission\n" );
1772 return $status;
1773 }
1774
1775 // Don't save a new page if it's blank or if it's a MediaWiki:
1776 // message with content equivalent to default (allow empty pages
1777 // in this case to disable messages, see bug 50124)
1778 $defaultMessageText = $this->mTitle->getDefaultMessageText();
1779 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1780 $defaultText = $defaultMessageText;
1781 } else {
1782 $defaultText = '';
1783 }
1784
1785 if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
1786 $this->blankArticle = true;
1787 $status->fatal( 'blankarticle' );
1788 $status->setResult( false, self::AS_BLANK_ARTICLE );
1789 return $status;
1790 }
1791
1792 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1793 return $status;
1794 }
1795
1796 $content = $textbox_content;
1797
1798 $result['sectionanchor'] = '';
1799 if ( $this->section == 'new' ) {
1800 if ( $this->sectiontitle !== '' ) {
1801 // Insert the section title above the content.
1802 $content = $content->addSectionHeader( $this->sectiontitle );
1803 } elseif ( $this->summary !== '' ) {
1804 // Insert the section title above the content.
1805 $content = $content->addSectionHeader( $this->summary );
1806 }
1807 $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
1808 }
1809
1810 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1811
1812 } else { # not $new
1813
1814 # Article exists. Check for edit conflict.
1815
1816 $this->mArticle->clear(); # Force reload of dates, etc.
1817 $timestamp = $this->mArticle->getTimestamp();
1818
1819 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1820
1821 if ( $timestamp != $this->edittime ) {
1822 $this->isConflict = true;
1823 if ( $this->section == 'new' ) {
1824 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
1825 $this->mArticle->getComment() == $this->newSectionSummary()
1826 ) {
1827 // Probably a duplicate submission of a new comment.
1828 // This can happen when squid resends a request after
1829 // a timeout but the first one actually went through.
1830 wfDebug( __METHOD__
1831 . ": duplicate new section submission; trigger edit conflict!\n" );
1832 } else {
1833 // New comment; suppress conflict.
1834 $this->isConflict = false;
1835 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1836 }
1837 } elseif ( $this->section == ''
1838 && Revision::userWasLastToEdit(
1839 DB_MASTER, $this->mTitle->getArticleID(),
1840 $wgUser->getId(), $this->edittime
1841 )
1842 ) {
1843 # Suppress edit conflict with self, except for section edits where merging is required.
1844 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1845 $this->isConflict = false;
1846 }
1847 }
1848
1849 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1850 if ( $this->sectiontitle !== '' ) {
1851 $sectionTitle = $this->sectiontitle;
1852 } else {
1853 $sectionTitle = $this->summary;
1854 }
1855
1856 $content = null;
1857
1858 if ( $this->isConflict ) {
1859 wfDebug( __METHOD__
1860 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1861 . " (article time '{$timestamp}')\n" );
1862
1863 $content = $this->mArticle->replaceSectionContent(
1864 $this->section,
1865 $textbox_content,
1866 $sectionTitle,
1867 $this->edittime
1868 );
1869 } else {
1870 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
1871 $content = $this->mArticle->replaceSectionContent(
1872 $this->section,
1873 $textbox_content,
1874 $sectionTitle
1875 );
1876 }
1877
1878 if ( is_null( $content ) ) {
1879 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1880 $this->isConflict = true;
1881 $content = $textbox_content; // do not try to merge here!
1882 } elseif ( $this->isConflict ) {
1883 # Attempt merge
1884 if ( $this->mergeChangesIntoContent( $content ) ) {
1885 // Successful merge! Maybe we should tell the user the good news?
1886 $this->isConflict = false;
1887 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1888 } else {
1889 $this->section = '';
1890 $this->textbox1 = ContentHandler::getContentText( $content );
1891 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1892 }
1893 }
1894
1895 if ( $this->isConflict ) {
1896 $status->setResult( false, self::AS_CONFLICT_DETECTED );
1897 return $status;
1898 }
1899
1900 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1901 return $status;
1902 }
1903
1904 if ( $this->section == 'new' ) {
1905 // Handle the user preference to force summaries here
1906 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
1907 $this->missingSummary = true;
1908 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1909 $status->value = self::AS_SUMMARY_NEEDED;
1910 return $status;
1911 }
1912
1913 // Do not allow the user to post an empty comment
1914 if ( $this->textbox1 == '' ) {
1915 $this->missingComment = true;
1916 $status->fatal( 'missingcommenttext' );
1917 $status->value = self::AS_TEXTBOX_EMPTY;
1918 return $status;
1919 }
1920 } elseif ( !$this->allowBlankSummary
1921 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1922 && !$content->isRedirect()
1923 && md5( $this->summary ) == $this->autoSumm
1924 ) {
1925 $this->missingSummary = true;
1926 $status->fatal( 'missingsummary' );
1927 $status->value = self::AS_SUMMARY_NEEDED;
1928 return $status;
1929 }
1930
1931 # All's well
1932 $sectionanchor = '';
1933 if ( $this->section == 'new' ) {
1934 $this->summary = $this->newSectionSummary( $sectionanchor );
1935 } elseif ( $this->section != '' ) {
1936 # Try to get a section anchor from the section source, redirect
1937 # to edited section if header found.
1938 # XXX: Might be better to integrate this into Article::replaceSection
1939 # for duplicate heading checking and maybe parsing.
1940 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1941 # We can't deal with anchors, includes, html etc in the header for now,
1942 # headline would need to be parsed to improve this.
1943 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1944 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1945 }
1946 }
1947 $result['sectionanchor'] = $sectionanchor;
1948
1949 // Save errors may fall down to the edit form, but we've now
1950 // merged the section into full text. Clear the section field
1951 // so that later submission of conflict forms won't try to
1952 // replace that into a duplicated mess.
1953 $this->textbox1 = $this->toEditText( $content );
1954 $this->section = '';
1955
1956 $status->value = self::AS_SUCCESS_UPDATE;
1957 }
1958
1959 if ( !$this->allowSelfRedirect
1960 && $content->isRedirect()
1961 && $content->getRedirectTarget()->equals( $this->getTitle() )
1962 ) {
1963 // If the page already redirects to itself, don't warn.
1964 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
1965 if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
1966 $this->selfRedirect = true;
1967 $status->fatal( 'selfredirect' );
1968 $status->value = self::AS_SELF_REDIRECT;
1969 return $status;
1970 }
1971 }
1972
1973 // Check for length errors again now that the section is merged in
1974 $this->kblength = (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1975 if ( $this->kblength > $wgMaxArticleSize ) {
1976 $this->tooBig = true;
1977 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
1978 return $status;
1979 }
1980
1981 $flags = EDIT_AUTOSUMMARY |
1982 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
1983 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
1984 ( $bot ? EDIT_FORCE_BOT : 0 );
1985
1986 $doEditStatus = $this->mArticle->doEditContent(
1987 $content,
1988 $this->summary,
1989 $flags,
1990 false,
1991 $wgUser,
1992 $content->getDefaultFormat()
1993 );
1994
1995 if ( !$doEditStatus->isOK() ) {
1996 // Failure from doEdit()
1997 // Show the edit conflict page for certain recognized errors from doEdit(),
1998 // but don't show it for errors from extension hooks
1999 $errors = $doEditStatus->getErrorsArray();
2000 if ( in_array( $errors[0][0],
2001 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
2002 ) {
2003 $this->isConflict = true;
2004 // Destroys data doEdit() put in $status->value but who cares
2005 $doEditStatus->value = self::AS_END;
2006 }
2007 return $doEditStatus;
2008 }
2009
2010 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
2011 if ( $result['nullEdit'] ) {
2012 // We don't know if it was a null edit until now, so increment here
2013 $wgUser->pingLimiter( 'linkpurge' );
2014 }
2015 $result['redirect'] = $content->isRedirect();
2016
2017 $this->updateWatchlist();
2018
2019 if ( $this->changeTags && isset( $doEditStatus->value['revision'] ) ) {
2020 // If a revision was created, apply any change tags that were requested
2021 $addTags = $this->changeTags;
2022 $revId = $doEditStatus->value['revision']->getId();
2023 // Defer this both for performance and so that addTags() sees the rc_id
2024 // since the recentchange entry addition is deferred first (bug T100248)
2025 DeferredUpdates::addCallableUpdate( function() use ( $addTags, $revId ) {
2026 ChangeTags::addTags( $addTags, null, $revId );
2027 } );
2028 }
2029
2030 // If the content model changed, add a log entry
2031 if ( $changingContentModel ) {
2032 $this->addContentModelChangeLogEntry(
2033 $wgUser,
2034 $oldContentModel,
2035 $this->contentModel,
2036 $this->summary
2037 );
2038 }
2039
2040 return $status;
2041 }
2042
2043 /**
2044 * @param User $user
2045 * @param string $oldModel
2046 * @param string $newModel
2047 * @param string $reason
2048 */
2049 protected function addContentModelChangeLogEntry( User $user, $oldModel, $newModel, $reason ) {
2050 $log = new ManualLogEntry( 'contentmodel', 'change' );
2051 $log->setPerformer( $user );
2052 $log->setTarget( $this->mTitle );
2053 $log->setComment( $reason );
2054 $log->setParameters( array(
2055 '4::oldmodel' => $oldModel,
2056 '5::newmodel' => $newModel
2057 ) );
2058 $logid = $log->insert();
2059 $log->publish( $logid );
2060 }
2061
2062 /**
2063 * Register the change of watch status
2064 */
2065 protected function updateWatchlist() {
2066 global $wgUser;
2067
2068 if ( !$wgUser->isLoggedIn() ) {
2069 return;
2070 }
2071
2072 $user = $wgUser;
2073 $title = $this->mTitle;
2074 $watch = $this->watchthis;
2075 // Do this in its own transaction to reduce contention...
2076 DeferredUpdates::addCallableUpdate( function () use ( $user, $title, $watch ) {
2077 if ( $watch == $user->isWatched( $title, WatchedItem::IGNORE_USER_RIGHTS ) ) {
2078 return; // nothing to change
2079 }
2080 WatchAction::doWatchOrUnwatch( $watch, $title, $user );
2081 } );
2082 }
2083
2084 /**
2085 * Attempts to do 3-way merge of edit content with a base revision
2086 * and current content, in case of edit conflict, in whichever way appropriate
2087 * for the content type.
2088 *
2089 * @since 1.21
2090 *
2091 * @param Content $editContent
2092 *
2093 * @return bool
2094 */
2095 private function mergeChangesIntoContent( &$editContent ) {
2096
2097 $db = wfGetDB( DB_MASTER );
2098
2099 // This is the revision the editor started from
2100 $baseRevision = $this->getBaseRevision();
2101 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
2102
2103 if ( is_null( $baseContent ) ) {
2104 return false;
2105 }
2106
2107 // The current state, we want to merge updates into it
2108 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2109 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
2110
2111 if ( is_null( $currentContent ) ) {
2112 return false;
2113 }
2114
2115 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
2116
2117 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2118
2119 if ( $result ) {
2120 $editContent = $result;
2121 return true;
2122 }
2123
2124 return false;
2125 }
2126
2127 /**
2128 * @return Revision
2129 */
2130 function getBaseRevision() {
2131 if ( !$this->mBaseRevision ) {
2132 $db = wfGetDB( DB_MASTER );
2133 $this->mBaseRevision = Revision::loadFromTimestamp(
2134 $db, $this->mTitle, $this->edittime );
2135 }
2136 return $this->mBaseRevision;
2137 }
2138
2139 /**
2140 * Check given input text against $wgSpamRegex, and return the text of the first match.
2141 *
2142 * @param string $text
2143 *
2144 * @return string|bool Matching string or false
2145 */
2146 public static function matchSpamRegex( $text ) {
2147 global $wgSpamRegex;
2148 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2149 $regexes = (array)$wgSpamRegex;
2150 return self::matchSpamRegexInternal( $text, $regexes );
2151 }
2152
2153 /**
2154 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2155 *
2156 * @param string $text
2157 *
2158 * @return string|bool Matching string or false
2159 */
2160 public static function matchSummarySpamRegex( $text ) {
2161 global $wgSummarySpamRegex;
2162 $regexes = (array)$wgSummarySpamRegex;
2163 return self::matchSpamRegexInternal( $text, $regexes );
2164 }
2165
2166 /**
2167 * @param string $text
2168 * @param array $regexes
2169 * @return bool|string
2170 */
2171 protected static function matchSpamRegexInternal( $text, $regexes ) {
2172 foreach ( $regexes as $regex ) {
2173 $matches = array();
2174 if ( preg_match( $regex, $text, $matches ) ) {
2175 return $matches[0];
2176 }
2177 }
2178 return false;
2179 }
2180
2181 function setHeaders() {
2182 global $wgOut, $wgUser, $wgAjaxEditStash;
2183
2184 $wgOut->addModules( 'mediawiki.action.edit' );
2185 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2186
2187 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2188 // The addition of default buttons is handled by getEditToolbar() which
2189 // has its own dependency on this module. The call here ensures the module
2190 // is loaded in time (it has position "top") for other modules to register
2191 // buttons (e.g. extensions, gadgets, user scripts).
2192 $wgOut->addModules( 'mediawiki.toolbar' );
2193 }
2194
2195 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2196 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2197 }
2198
2199 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2200 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2201 }
2202
2203 if ( $wgAjaxEditStash ) {
2204 $wgOut->addModules( 'mediawiki.action.edit.stash' );
2205 }
2206
2207 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2208
2209 # Enabled article-related sidebar, toplinks, etc.
2210 $wgOut->setArticleRelated( true );
2211
2212 $contextTitle = $this->getContextTitle();
2213 if ( $this->isConflict ) {
2214 $msg = 'editconflict';
2215 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2216 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2217 } else {
2218 $msg = $contextTitle->exists()
2219 || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2220 && $contextTitle->getDefaultMessageText() !== false
2221 )
2222 ? 'editing'
2223 : 'creating';
2224 }
2225
2226 # Use the title defined by DISPLAYTITLE magic word when present
2227 # NOTE: getDisplayTitle() returns HTML while getPrefixedText() returns plain text.
2228 # setPageTitle() treats the input as wikitext, which should be safe in either case.
2229 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2230 if ( $displayTitle === false ) {
2231 $displayTitle = $contextTitle->getPrefixedText();
2232 }
2233 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2234 # Transmit the name of the message to JavaScript for live preview
2235 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2236 $wgOut->addJsConfigVars( 'wgEditMessage', $msg );
2237 }
2238
2239 /**
2240 * Show all applicable editing introductions
2241 */
2242 protected function showIntro() {
2243 global $wgOut, $wgUser;
2244 if ( $this->suppressIntro ) {
2245 return;
2246 }
2247
2248 $namespace = $this->mTitle->getNamespace();
2249
2250 if ( $namespace == NS_MEDIAWIKI ) {
2251 # Show a warning if editing an interface message
2252 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2253 # If this is a default message (but not css or js),
2254 # show a hint that it is translatable on translatewiki.net
2255 if ( !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2256 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2257 ) {
2258 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2259 if ( $defaultMessageText !== false ) {
2260 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2261 'translateinterface' );
2262 }
2263 }
2264 } elseif ( $namespace == NS_FILE ) {
2265 # Show a hint to shared repo
2266 $file = wfFindFile( $this->mTitle );
2267 if ( $file && !$file->isLocal() ) {
2268 $descUrl = $file->getDescriptionUrl();
2269 # there must be a description url to show a hint to shared repo
2270 if ( $descUrl ) {
2271 if ( !$this->mTitle->exists() ) {
2272 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2273 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2274 ) );
2275 } else {
2276 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2277 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2278 ) );
2279 }
2280 }
2281 }
2282 }
2283
2284 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2285 # Show log extract when the user is currently blocked
2286 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2287 $parts = explode( '/', $this->mTitle->getText(), 2 );
2288 $username = $parts[0];
2289 $user = User::newFromName( $username, false /* allow IP users*/ );
2290 $ip = User::isIP( $username );
2291 $block = Block::newFromTarget( $user, $user );
2292 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2293 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2294 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2295 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
2296 # Show log extract if the user is currently blocked
2297 LogEventsList::showLogExtract(
2298 $wgOut,
2299 'block',
2300 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2301 '',
2302 array(
2303 'lim' => 1,
2304 'showIfEmpty' => false,
2305 'msgKey' => array(
2306 'blocked-notice-logextract',
2307 $user->getName() # Support GENDER in notice
2308 )
2309 )
2310 );
2311 }
2312 }
2313 # Try to add a custom edit intro, or use the standard one if this is not possible.
2314 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2315 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2316 wfMessage( 'helppage' )->inContentLanguage()->text()
2317 ) );
2318 if ( $wgUser->isLoggedIn() ) {
2319 $wgOut->wrapWikiMsg(
2320 // Suppress the external link icon, consider the help url an internal one
2321 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2322 array(
2323 'newarticletext',
2324 $helpLink
2325 )
2326 );
2327 } else {
2328 $wgOut->wrapWikiMsg(
2329 // Suppress the external link icon, consider the help url an internal one
2330 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2331 array(
2332 'newarticletextanon',
2333 $helpLink
2334 )
2335 );
2336 }
2337 }
2338 # Give a notice if the user is editing a deleted/moved page...
2339 if ( !$this->mTitle->exists() ) {
2340 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
2341 '',
2342 array(
2343 'lim' => 10,
2344 'conds' => array( "log_action != 'revision'" ),
2345 'showIfEmpty' => false,
2346 'msgKey' => array( 'recreate-moveddeleted-warn' )
2347 )
2348 );
2349 }
2350 }
2351
2352 /**
2353 * Attempt to show a custom editing introduction, if supplied
2354 *
2355 * @return bool
2356 */
2357 protected function showCustomIntro() {
2358 if ( $this->editintro ) {
2359 $title = Title::newFromText( $this->editintro );
2360 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2361 global $wgOut;
2362 // Added using template syntax, to take <noinclude>'s into account.
2363 $wgOut->addWikiTextTitleTidy(
2364 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2365 $this->mTitle
2366 );
2367 return true;
2368 }
2369 }
2370 return false;
2371 }
2372
2373 /**
2374 * Gets an editable textual representation of $content.
2375 * The textual representation can be turned by into a Content object by the
2376 * toEditContent() method.
2377 *
2378 * If $content is null or false or a string, $content is returned unchanged.
2379 *
2380 * If the given Content object is not of a type that can be edited using
2381 * the text base EditPage, an exception will be raised. Set
2382 * $this->allowNonTextContent to true to allow editing of non-textual
2383 * content.
2384 *
2385 * @param Content|null|bool|string $content
2386 * @return string The editable text form of the content.
2387 *
2388 * @throws MWException If $content is not an instance of TextContent and
2389 * $this->allowNonTextContent is not true.
2390 */
2391 protected function toEditText( $content ) {
2392 if ( $content === null || $content === false || is_string( $content ) ) {
2393 return $content;
2394 }
2395
2396 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2397 throw new MWException( 'This content model is not supported: '
2398 . ContentHandler::getLocalizedName( $content->getModel() ) );
2399 }
2400
2401 return $content->serialize( $this->contentFormat );
2402 }
2403
2404 /**
2405 * Turns the given text into a Content object by unserializing it.
2406 *
2407 * If the resulting Content object is not of a type that can be edited using
2408 * the text base EditPage, an exception will be raised. Set
2409 * $this->allowNonTextContent to true to allow editing of non-textual
2410 * content.
2411 *
2412 * @param string|null|bool $text Text to unserialize
2413 * @return Content The content object created from $text. If $text was false
2414 * or null, false resp. null will be returned instead.
2415 *
2416 * @throws MWException If unserializing the text results in a Content
2417 * object that is not an instance of TextContent and
2418 * $this->allowNonTextContent is not true.
2419 */
2420 protected function toEditContent( $text ) {
2421 if ( $text === false || $text === null ) {
2422 return $text;
2423 }
2424
2425 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2426 $this->contentModel, $this->contentFormat );
2427
2428 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2429 throw new MWException( 'This content model is not supported: '
2430 . ContentHandler::getLocalizedName( $content->getModel() ) );
2431 }
2432
2433 return $content;
2434 }
2435
2436 /**
2437 * Send the edit form and related headers to $wgOut
2438 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2439 * during form output near the top, for captchas and the like.
2440 *
2441 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2442 * use the EditPage::showEditForm:fields hook instead.
2443 */
2444 function showEditForm( $formCallback = null ) {
2445 global $wgOut, $wgUser;
2446
2447 # need to parse the preview early so that we know which templates are used,
2448 # otherwise users with "show preview after edit box" will get a blank list
2449 # we parse this near the beginning so that setHeaders can do the title
2450 # setting work instead of leaving it in getPreviewText
2451 $previewOutput = '';
2452 if ( $this->formtype == 'preview' ) {
2453 $previewOutput = $this->getPreviewText();
2454 }
2455
2456 Hooks::run( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2457
2458 $this->setHeaders();
2459
2460 if ( $this->showHeader() === false ) {
2461 return;
2462 }
2463
2464 $wgOut->addHTML( $this->editFormPageTop );
2465
2466 if ( $wgUser->getOption( 'previewontop' ) ) {
2467 $this->displayPreviewArea( $previewOutput, true );
2468 }
2469
2470 $wgOut->addHTML( $this->editFormTextTop );
2471
2472 $showToolbar = true;
2473 if ( $this->wasDeletedSinceLastEdit() ) {
2474 if ( $this->formtype == 'save' ) {
2475 // Hide the toolbar and edit area, user can click preview to get it back
2476 // Add an confirmation checkbox and explanation.
2477 $showToolbar = false;
2478 } else {
2479 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2480 'deletedwhileediting' );
2481 }
2482 }
2483
2484 // @todo add EditForm plugin interface and use it here!
2485 // search for textarea1 and textares2, and allow EditForm to override all uses.
2486 $wgOut->addHTML( Html::openElement(
2487 'form',
2488 array(
2489 'id' => self::EDITFORM_ID,
2490 'name' => self::EDITFORM_ID,
2491 'method' => 'post',
2492 'action' => $this->getActionURL( $this->getContextTitle() ),
2493 'enctype' => 'multipart/form-data'
2494 )
2495 ) );
2496
2497 if ( is_callable( $formCallback ) ) {
2498 wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2499 call_user_func_array( $formCallback, array( &$wgOut ) );
2500 }
2501
2502 // Add an empty field to trip up spambots
2503 $wgOut->addHTML(
2504 Xml::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2505 . Html::rawElement(
2506 'label',
2507 array( 'for' => 'wpAntiSpam' ),
2508 wfMessage( 'simpleantispam-label' )->parse()
2509 )
2510 . Xml::element(
2511 'input',
2512 array(
2513 'type' => 'text',
2514 'name' => 'wpAntispam',
2515 'id' => 'wpAntispam',
2516 'value' => ''
2517 )
2518 )
2519 . Xml::closeElement( 'div' )
2520 );
2521
2522 Hooks::run( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2523
2524 // Put these up at the top to ensure they aren't lost on early form submission
2525 $this->showFormBeforeText();
2526
2527 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2528 $username = $this->lastDelete->user_name;
2529 $comment = $this->lastDelete->log_comment;
2530
2531 // It is better to not parse the comment at all than to have templates expanded in the middle
2532 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2533 $key = $comment === ''
2534 ? 'confirmrecreate-noreason'
2535 : 'confirmrecreate';
2536 $wgOut->addHTML(
2537 '<div class="mw-confirm-recreate">' .
2538 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2539 Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2540 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2541 ) .
2542 '</div>'
2543 );
2544 }
2545
2546 # When the summary is hidden, also hide them on preview/show changes
2547 if ( $this->nosummary ) {
2548 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2549 }
2550
2551 # If a blank edit summary was previously provided, and the appropriate
2552 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2553 # user being bounced back more than once in the event that a summary
2554 # is not required.
2555 # ####
2556 # For a bit more sophisticated detection of blank summaries, hash the
2557 # automatic one and pass that in the hidden field wpAutoSummary.
2558 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2559 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2560 }
2561
2562 if ( $this->undidRev ) {
2563 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2564 }
2565
2566 if ( $this->selfRedirect ) {
2567 $wgOut->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2568 }
2569
2570 if ( $this->hasPresetSummary ) {
2571 // If a summary has been preset using &summary= we don't want to prompt for
2572 // a different summary. Only prompt for a summary if the summary is blanked.
2573 // (Bug 17416)
2574 $this->autoSumm = md5( '' );
2575 }
2576
2577 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2578 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2579
2580 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2581 $wgOut->addHTML( Html::hidden( 'parentRevId',
2582 $this->parentRevId ?: $this->mArticle->getRevIdFetched() ) );
2583
2584 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2585 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2586
2587 if ( $this->section == 'new' ) {
2588 $this->showSummaryInput( true, $this->summary );
2589 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2590 }
2591
2592 $wgOut->addHTML( $this->editFormTextBeforeContent );
2593
2594 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2595 $wgOut->addHTML( EditPage::getEditToolbar( $this->mTitle ) );
2596 }
2597
2598 if ( $this->blankArticle ) {
2599 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2600 }
2601
2602 if ( $this->isConflict ) {
2603 // In an edit conflict bypass the overridable content form method
2604 // and fallback to the raw wpTextbox1 since editconflicts can't be
2605 // resolved between page source edits and custom ui edits using the
2606 // custom edit ui.
2607 $this->textbox2 = $this->textbox1;
2608
2609 $content = $this->getCurrentContent();
2610 $this->textbox1 = $this->toEditText( $content );
2611
2612 $this->showTextbox1();
2613 } else {
2614 $this->showContentForm();
2615 }
2616
2617 $wgOut->addHTML( $this->editFormTextAfterContent );
2618
2619 $this->showStandardInputs();
2620
2621 $this->showFormAfterText();
2622
2623 $this->showTosSummary();
2624
2625 $this->showEditTools();
2626
2627 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2628
2629 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2630 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
2631
2632 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
2633 Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
2634
2635 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'limitreport' ),
2636 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2637
2638 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2639
2640 if ( $this->isConflict ) {
2641 try {
2642 $this->showConflict();
2643 } catch ( MWContentSerializationException $ex ) {
2644 // this can't really happen, but be nice if it does.
2645 $msg = wfMessage(
2646 'content-failed-to-parse',
2647 $this->contentModel,
2648 $this->contentFormat,
2649 $ex->getMessage()
2650 );
2651 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2652 }
2653 }
2654
2655 // Marker for detecting truncated form data. This must be the last
2656 // parameter sent in order to be of use, so do not move me.
2657 $wgOut->addHTML( Html::hidden( 'wpUltimateParam', true ) );
2658 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2659
2660 if ( !$wgUser->getOption( 'previewontop' ) ) {
2661 $this->displayPreviewArea( $previewOutput, false );
2662 }
2663
2664 }
2665
2666 /**
2667 * Extract the section title from current section text, if any.
2668 *
2669 * @param string $text
2670 * @return string|bool String or false
2671 */
2672 public static function extractSectionTitle( $text ) {
2673 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2674 if ( !empty( $matches[2] ) ) {
2675 global $wgParser;
2676 return $wgParser->stripSectionName( trim( $matches[2] ) );
2677 } else {
2678 return false;
2679 }
2680 }
2681
2682 /**
2683 * @return bool
2684 */
2685 protected function showHeader() {
2686 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2687 global $wgAllowUserCss, $wgAllowUserJs;
2688
2689 if ( $this->mTitle->isTalkPage() ) {
2690 $wgOut->addWikiMsg( 'talkpagetext' );
2691 }
2692
2693 // Add edit notices
2694 $editNotices = $this->mTitle->getEditNotices( $this->oldid );
2695 if ( count( $editNotices ) ) {
2696 $wgOut->addHTML( implode( "\n", $editNotices ) );
2697 } else {
2698 $msg = wfMessage( 'editnotice-notext' );
2699 if ( !$msg->isDisabled() ) {
2700 $wgOut->addHTML(
2701 '<div class="mw-editnotice-notext">'
2702 . $msg->parseAsBlock()
2703 . '</div>'
2704 );
2705 }
2706 }
2707
2708 if ( $this->isConflict ) {
2709 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2710 $this->edittime = $this->mArticle->getTimestamp();
2711 } else {
2712 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
2713 // We use $this->section to much before this and getVal('wgSection') directly in other places
2714 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2715 // Someone is welcome to try refactoring though
2716 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2717 return false;
2718 }
2719
2720 if ( $this->section != '' && $this->section != 'new' ) {
2721 if ( !$this->summary && !$this->preview && !$this->diff ) {
2722 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); // FIXME: use Content object
2723 if ( $sectionTitle !== false ) {
2724 $this->summary = "/* $sectionTitle */ ";
2725 }
2726 }
2727 }
2728
2729 if ( $this->missingComment ) {
2730 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2731 }
2732
2733 if ( $this->missingSummary && $this->section != 'new' ) {
2734 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2735 }
2736
2737 if ( $this->missingSummary && $this->section == 'new' ) {
2738 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2739 }
2740
2741 if ( $this->blankArticle ) {
2742 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2743 }
2744
2745 if ( $this->selfRedirect ) {
2746 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2747 }
2748
2749 if ( $this->hookError !== '' ) {
2750 $wgOut->addWikiText( $this->hookError );
2751 }
2752
2753 if ( !$this->checkUnicodeCompliantBrowser() ) {
2754 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2755 }
2756
2757 if ( $this->section != 'new' ) {
2758 $revision = $this->mArticle->getRevisionFetched();
2759 if ( $revision ) {
2760 // Let sysop know that this will make private content public if saved
2761
2762 if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2763 $wgOut->wrapWikiMsg(
2764 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2765 'rev-deleted-text-permission'
2766 );
2767 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2768 $wgOut->wrapWikiMsg(
2769 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2770 'rev-deleted-text-view'
2771 );
2772 }
2773
2774 if ( !$revision->isCurrent() ) {
2775 $this->mArticle->setOldSubtitle( $revision->getId() );
2776 $wgOut->addWikiMsg( 'editingold' );
2777 }
2778 } elseif ( $this->mTitle->exists() ) {
2779 // Something went wrong
2780
2781 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2782 array( 'missing-revision', $this->oldid ) );
2783 }
2784 }
2785 }
2786
2787 if ( wfReadOnly() ) {
2788 $wgOut->wrapWikiMsg(
2789 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2790 array( 'readonlywarning', wfReadOnlyReason() )
2791 );
2792 } elseif ( $wgUser->isAnon() ) {
2793 if ( $this->formtype != 'preview' ) {
2794 $wgOut->wrapWikiMsg(
2795 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2796 array( 'anoneditwarning',
2797 // Log-in link
2798 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2799 // Sign-up link
2800 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2801 );
2802 } else {
2803 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2804 'anonpreviewwarning'
2805 );
2806 }
2807 } else {
2808 if ( $this->isCssJsSubpage ) {
2809 # Check the skin exists
2810 if ( $this->isWrongCaseCssJsPage ) {
2811 $wgOut->wrapWikiMsg(
2812 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2813 array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() )
2814 );
2815 }
2816 if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
2817 if ( $this->formtype !== 'preview' ) {
2818 if ( $this->isCssSubpage && $wgAllowUserCss ) {
2819 $wgOut->wrapWikiMsg(
2820 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2821 array( 'usercssyoucanpreview' )
2822 );
2823 }
2824
2825 if ( $this->isJsSubpage && $wgAllowUserJs ) {
2826 $wgOut->wrapWikiMsg(
2827 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2828 array( 'userjsyoucanpreview' )
2829 );
2830 }
2831 }
2832 }
2833 }
2834 }
2835
2836 if ( $this->mTitle->isProtected( 'edit' ) &&
2837 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2838 ) {
2839 # Is the title semi-protected?
2840 if ( $this->mTitle->isSemiProtected() ) {
2841 $noticeMsg = 'semiprotectedpagewarning';
2842 } else {
2843 # Then it must be protected based on static groups (regular)
2844 $noticeMsg = 'protectedpagewarning';
2845 }
2846 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2847 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2848 }
2849 if ( $this->mTitle->isCascadeProtected() ) {
2850 # Is this page under cascading protection from some source pages?
2851 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2852 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2853 $cascadeSourcesCount = count( $cascadeSources );
2854 if ( $cascadeSourcesCount > 0 ) {
2855 # Explain, and list the titles responsible
2856 foreach ( $cascadeSources as $page ) {
2857 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2858 }
2859 }
2860 $notice .= '</div>';
2861 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2862 }
2863 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2864 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2865 array( 'lim' => 1,
2866 'showIfEmpty' => false,
2867 'msgKey' => array( 'titleprotectedwarning' ),
2868 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2869 }
2870
2871 if ( $this->kblength === false ) {
2872 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2873 }
2874
2875 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2876 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2877 array(
2878 'longpageerror',
2879 $wgLang->formatNum( $this->kblength ),
2880 $wgLang->formatNum( $wgMaxArticleSize )
2881 )
2882 );
2883 } else {
2884 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2885 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2886 array(
2887 'longpage-hint',
2888 $wgLang->formatSize( strlen( $this->textbox1 ) ),
2889 strlen( $this->textbox1 )
2890 )
2891 );
2892 }
2893 }
2894 # Add header copyright warning
2895 $this->showHeaderCopyrightWarning();
2896
2897 return true;
2898 }
2899
2900 /**
2901 * Standard summary input and label (wgSummary), abstracted so EditPage
2902 * subclasses may reorganize the form.
2903 * Note that you do not need to worry about the label's for=, it will be
2904 * inferred by the id given to the input. You can remove them both by
2905 * passing array( 'id' => false ) to $userInputAttrs.
2906 *
2907 * @param string $summary The value of the summary input
2908 * @param string $labelText The html to place inside the label
2909 * @param array $inputAttrs Array of attrs to use on the input
2910 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2911 *
2912 * @return array An array in the format array( $label, $input )
2913 */
2914 function getSummaryInput( $summary = "", $labelText = null,
2915 $inputAttrs = null, $spanLabelAttrs = null
2916 ) {
2917 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2918 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2919 'id' => 'wpSummary',
2920 'maxlength' => '200',
2921 'tabindex' => '1',
2922 'size' => 60,
2923 'spellcheck' => 'true',
2924 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2925
2926 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2927 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2928 'id' => "wpSummaryLabel"
2929 );
2930
2931 $label = null;
2932 if ( $labelText ) {
2933 $label = Xml::tags(
2934 'label',
2935 $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null,
2936 $labelText
2937 );
2938 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2939 }
2940
2941 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2942
2943 return array( $label, $input );
2944 }
2945
2946 /**
2947 * @param bool $isSubjectPreview True if this is the section subject/title
2948 * up top, or false if this is the comment summary
2949 * down below the textarea
2950 * @param string $summary The text of the summary to display
2951 */
2952 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2953 global $wgOut, $wgContLang;
2954 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2955 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2956 if ( $isSubjectPreview ) {
2957 if ( $this->nosummary ) {
2958 return;
2959 }
2960 } else {
2961 if ( !$this->mShowSummaryField ) {
2962 return;
2963 }
2964 }
2965 $summary = $wgContLang->recodeForEdit( $summary );
2966 $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
2967 list( $label, $input ) = $this->getSummaryInput(
2968 $summary,
2969 $labelText,
2970 array( 'class' => $summaryClass ),
2971 array()
2972 );
2973 $wgOut->addHTML( "{$label} {$input}" );
2974 }
2975
2976 /**
2977 * @param bool $isSubjectPreview True if this is the section subject/title
2978 * up top, or false if this is the comment summary
2979 * down below the textarea
2980 * @param string $summary The text of the summary to display
2981 * @return string
2982 */
2983 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2984 // avoid spaces in preview, gets always trimmed on save
2985 $summary = trim( $summary );
2986 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
2987 return "";
2988 }
2989
2990 global $wgParser;
2991
2992 if ( $isSubjectPreview ) {
2993 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2994 ->inContentLanguage()->text();
2995 }
2996
2997 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
2998
2999 $summary = wfMessage( $message )->parse()
3000 . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
3001 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
3002 }
3003
3004 protected function showFormBeforeText() {
3005 global $wgOut;
3006 $section = htmlspecialchars( $this->section );
3007 $wgOut->addHTML( <<<HTML
3008 <input type='hidden' value="{$section}" name="wpSection"/>
3009 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
3010 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
3011 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
3012
3013 HTML
3014 );
3015 if ( !$this->checkUnicodeCompliantBrowser() ) {
3016 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
3017 }
3018 }
3019
3020 protected function showFormAfterText() {
3021 global $wgOut, $wgUser;
3022 /**
3023 * To make it harder for someone to slip a user a page
3024 * which submits an edit form to the wiki without their
3025 * knowledge, a random token is associated with the login
3026 * session. If it's not passed back with the submission,
3027 * we won't save the page, or render user JavaScript and
3028 * CSS previews.
3029 *
3030 * For anon editors, who may not have a session, we just
3031 * include the constant suffix to prevent editing from
3032 * broken text-mangling proxies.
3033 */
3034 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
3035 }
3036
3037 /**
3038 * Subpage overridable method for printing the form for page content editing
3039 * By default this simply outputs wpTextbox1
3040 * Subclasses can override this to provide a custom UI for editing;
3041 * be it a form, or simply wpTextbox1 with a modified content that will be
3042 * reverse modified when extracted from the post data.
3043 * Note that this is basically the inverse for importContentFormData
3044 */
3045 protected function showContentForm() {
3046 $this->showTextbox1();
3047 }
3048
3049 /**
3050 * Method to output wpTextbox1
3051 * The $textoverride method can be used by subclasses overriding showContentForm
3052 * to pass back to this method.
3053 *
3054 * @param array $customAttribs Array of html attributes to use in the textarea
3055 * @param string $textoverride Optional text to override $this->textarea1 with
3056 */
3057 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
3058 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
3059 $attribs = array( 'style' => 'display:none;' );
3060 } else {
3061 $classes = array(); // Textarea CSS
3062 if ( $this->mTitle->isProtected( 'edit' ) &&
3063 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
3064 ) {
3065 # Is the title semi-protected?
3066 if ( $this->mTitle->isSemiProtected() ) {
3067 $classes[] = 'mw-textarea-sprotected';
3068 } else {
3069 # Then it must be protected based on static groups (regular)
3070 $classes[] = 'mw-textarea-protected';
3071 }
3072 # Is the title cascade-protected?
3073 if ( $this->mTitle->isCascadeProtected() ) {
3074 $classes[] = 'mw-textarea-cprotected';
3075 }
3076 }
3077
3078 $attribs = array( 'tabindex' => 1 );
3079
3080 if ( is_array( $customAttribs ) ) {
3081 $attribs += $customAttribs;
3082 }
3083
3084 if ( count( $classes ) ) {
3085 if ( isset( $attribs['class'] ) ) {
3086 $classes[] = $attribs['class'];
3087 }
3088 $attribs['class'] = implode( ' ', $classes );
3089 }
3090 }
3091
3092 $this->showTextbox(
3093 $textoverride !== null ? $textoverride : $this->textbox1,
3094 'wpTextbox1',
3095 $attribs
3096 );
3097 }
3098
3099 protected function showTextbox2() {
3100 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
3101 }
3102
3103 protected function showTextbox( $text, $name, $customAttribs = array() ) {
3104 global $wgOut, $wgUser;
3105
3106 $wikitext = $this->safeUnicodeOutput( $text );
3107 if ( strval( $wikitext ) !== '' ) {
3108 // Ensure there's a newline at the end, otherwise adding lines
3109 // is awkward.
3110 // But don't add a newline if the ext is empty, or Firefox in XHTML
3111 // mode will show an extra newline. A bit annoying.
3112 $wikitext .= "\n";
3113 }
3114
3115 $attribs = $customAttribs + array(
3116 'accesskey' => ',',
3117 'id' => $name,
3118 'cols' => $wgUser->getIntOption( 'cols' ),
3119 'rows' => $wgUser->getIntOption( 'rows' ),
3120 // Avoid PHP notices when appending preferences
3121 // (appending allows customAttribs['style'] to still work).
3122 'style' => ''
3123 );
3124
3125 $pageLang = $this->mTitle->getPageLanguage();
3126 $attribs['lang'] = $pageLang->getHtmlCode();
3127 $attribs['dir'] = $pageLang->getDir();
3128
3129 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
3130 }
3131
3132 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3133 global $wgOut;
3134 $classes = array();
3135 if ( $isOnTop ) {
3136 $classes[] = 'ontop';
3137 }
3138
3139 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
3140
3141 if ( $this->formtype != 'preview' ) {
3142 $attribs['style'] = 'display: none;';
3143 }
3144
3145 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
3146
3147 if ( $this->formtype == 'preview' ) {
3148 $this->showPreview( $previewOutput );
3149 } else {
3150 // Empty content container for LivePreview
3151 $pageViewLang = $this->mTitle->getPageViewLanguage();
3152 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3153 'class' => 'mw-content-' . $pageViewLang->getDir() );
3154 $wgOut->addHTML( Html::rawElement( 'div', $attribs ) );
3155 }
3156
3157 $wgOut->addHTML( '</div>' );
3158
3159 if ( $this->formtype == 'diff' ) {
3160 try {
3161 $this->showDiff();
3162 } catch ( MWContentSerializationException $ex ) {
3163 $msg = wfMessage(
3164 'content-failed-to-parse',
3165 $this->contentModel,
3166 $this->contentFormat,
3167 $ex->getMessage()
3168 );
3169 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3170 }
3171 }
3172 }
3173
3174 /**
3175 * Append preview output to $wgOut.
3176 * Includes category rendering if this is a category page.
3177 *
3178 * @param string $text The HTML to be output for the preview.
3179 */
3180 protected function showPreview( $text ) {
3181 global $wgOut;
3182 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3183 $this->mArticle->openShowCategory();
3184 }
3185 # This hook seems slightly odd here, but makes things more
3186 # consistent for extensions.
3187 Hooks::run( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3188 $wgOut->addHTML( $text );
3189 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3190 $this->mArticle->closeShowCategory();
3191 }
3192 }
3193
3194 /**
3195 * Get a diff between the current contents of the edit box and the
3196 * version of the page we're editing from.
3197 *
3198 * If this is a section edit, we'll replace the section as for final
3199 * save and then make a comparison.
3200 */
3201 function showDiff() {
3202 global $wgUser, $wgContLang, $wgOut;
3203
3204 $oldtitlemsg = 'currentrev';
3205 # if message does not exist, show diff against the preloaded default
3206 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3207 $oldtext = $this->mTitle->getDefaultMessageText();
3208 if ( $oldtext !== false ) {
3209 $oldtitlemsg = 'defaultmessagetext';
3210 $oldContent = $this->toEditContent( $oldtext );
3211 } else {
3212 $oldContent = null;
3213 }
3214 } else {
3215 $oldContent = $this->getCurrentContent();
3216 }
3217
3218 $textboxContent = $this->toEditContent( $this->textbox1 );
3219
3220 $newContent = $this->mArticle->replaceSectionContent(
3221 $this->section, $textboxContent,
3222 $this->summary, $this->edittime );
3223
3224 if ( $newContent ) {
3225 ContentHandler::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3226 Hooks::run( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3227
3228 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
3229 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
3230 }
3231
3232 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3233 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3234 $newtitle = wfMessage( 'yourtext' )->parse();
3235
3236 if ( !$oldContent ) {
3237 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3238 }
3239
3240 if ( !$newContent ) {
3241 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3242 }
3243
3244 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
3245 $de->setContent( $oldContent, $newContent );
3246
3247 $difftext = $de->getDiff( $oldtitle, $newtitle );
3248 $de->showDiffStyle();
3249 } else {
3250 $difftext = '';
3251 }
3252
3253 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3254 }
3255
3256 /**
3257 * Show the header copyright warning.
3258 */
3259 protected function showHeaderCopyrightWarning() {
3260 $msg = 'editpage-head-copy-warn';
3261 if ( !wfMessage( $msg )->isDisabled() ) {
3262 global $wgOut;
3263 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3264 'editpage-head-copy-warn' );
3265 }
3266 }
3267
3268 /**
3269 * Give a chance for site and per-namespace customizations of
3270 * terms of service summary link that might exist separately
3271 * from the copyright notice.
3272 *
3273 * This will display between the save button and the edit tools,
3274 * so should remain short!
3275 */
3276 protected function showTosSummary() {
3277 $msg = 'editpage-tos-summary';
3278 Hooks::run( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
3279 if ( !wfMessage( $msg )->isDisabled() ) {
3280 global $wgOut;
3281 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3282 $wgOut->addWikiMsg( $msg );
3283 $wgOut->addHTML( '</div>' );
3284 }
3285 }
3286
3287 protected function showEditTools() {
3288 global $wgOut;
3289 $wgOut->addHTML( '<div class="mw-editTools">' .
3290 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3291 '</div>' );
3292 }
3293
3294 /**
3295 * Get the copyright warning
3296 *
3297 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3298 * @return string
3299 */
3300 protected function getCopywarn() {
3301 return self::getCopyrightWarning( $this->mTitle );
3302 }
3303
3304 /**
3305 * Get the copyright warning, by default returns wikitext
3306 *
3307 * @param Title $title
3308 * @param string $format Output format, valid values are any function of a Message object
3309 * @return string
3310 */
3311 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3312 global $wgRightsText;
3313 if ( $wgRightsText ) {
3314 $copywarnMsg = array( 'copyrightwarning',
3315 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3316 $wgRightsText );
3317 } else {
3318 $copywarnMsg = array( 'copyrightwarning2',
3319 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3320 }
3321 // Allow for site and per-namespace customization of contribution/copyright notice.
3322 Hooks::run( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3323
3324 return "<div id=\"editpage-copywarn\">\n" .
3325 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3326 }
3327
3328 /**
3329 * Get the Limit report for page previews
3330 *
3331 * @since 1.22
3332 * @param ParserOutput $output ParserOutput object from the parse
3333 * @return string HTML
3334 */
3335 public static function getPreviewLimitReport( $output ) {
3336 if ( !$output || !$output->getLimitReportData() ) {
3337 return '';
3338 }
3339
3340 $limitReport = Html::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3341 wfMessage( 'limitreport-title' )->parseAsBlock()
3342 );
3343
3344 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3345 $limitReport .= Html::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3346
3347 $limitReport .= Html::openElement( 'table', array(
3348 'class' => 'preview-limit-report wikitable'
3349 ) ) .
3350 Html::openElement( 'tbody' );
3351
3352 foreach ( $output->getLimitReportData() as $key => $value ) {
3353 if ( Hooks::run( 'ParserLimitReportFormat',
3354 array( $key, &$value, &$limitReport, true, true )
3355 ) ) {
3356 $keyMsg = wfMessage( $key );
3357 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3358 if ( !$valueMsg->exists() ) {
3359 $valueMsg = new RawMessage( '$1' );
3360 }
3361 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3362 $limitReport .= Html::openElement( 'tr' ) .
3363 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3364 Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3365 Html::closeElement( 'tr' );
3366 }
3367 }
3368 }
3369
3370 $limitReport .= Html::closeElement( 'tbody' ) .
3371 Html::closeElement( 'table' ) .
3372 Html::closeElement( 'div' );
3373
3374 return $limitReport;
3375 }
3376
3377 protected function showStandardInputs( &$tabindex = 2 ) {
3378 global $wgOut;
3379 $wgOut->addHTML( "<div class='editOptions'>\n" );
3380
3381 if ( $this->section != 'new' ) {
3382 $this->showSummaryInput( false, $this->summary );
3383 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3384 }
3385
3386 $checkboxes = $this->getCheckboxes( $tabindex,
3387 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
3388 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3389
3390 // Show copyright warning.
3391 $wgOut->addWikiText( $this->getCopywarn() );
3392 $wgOut->addHTML( $this->editFormTextAfterWarn );
3393
3394 $wgOut->addHTML( "<div class='editButtons'>\n" );
3395 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3396
3397 $cancel = $this->getCancelLink();
3398 if ( $cancel !== '' ) {
3399 $cancel .= Html::element( 'span',
3400 array( 'class' => 'mw-editButtons-pipe-separator' ),
3401 wfMessage( 'pipe-separator' )->text() );
3402 }
3403
3404 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3405 $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3406 $attrs = array(
3407 'target' => 'helpwindow',
3408 'href' => $edithelpurl,
3409 );
3410 $edithelp = Html::linkButton( wfMessage( 'edithelp' )->text(),
3411 $attrs, array( 'mw-ui-quiet' ) ) .
3412 wfMessage( 'word-separator' )->escaped() .
3413 wfMessage( 'newwindow' )->parse();
3414
3415 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3416 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3417 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3418
3419 Hooks::run( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3420
3421 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3422 }
3423
3424 /**
3425 * Show an edit conflict. textbox1 is already shown in showEditForm().
3426 * If you want to use another entry point to this function, be careful.
3427 */
3428 protected function showConflict() {
3429 global $wgOut;
3430
3431 if ( Hooks::run( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3432 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3433
3434 $content1 = $this->toEditContent( $this->textbox1 );
3435 $content2 = $this->toEditContent( $this->textbox2 );
3436
3437 $handler = ContentHandler::getForModelID( $this->contentModel );
3438 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3439 $de->setContent( $content2, $content1 );
3440 $de->showDiff(
3441 wfMessage( 'yourtext' )->parse(),
3442 wfMessage( 'storedversion' )->text()
3443 );
3444
3445 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3446 $this->showTextbox2();
3447 }
3448 }
3449
3450 /**
3451 * @return string
3452 */
3453 public function getCancelLink() {
3454 $cancelParams = array();
3455 if ( !$this->isConflict && $this->oldid > 0 ) {
3456 $cancelParams['oldid'] = $this->oldid;
3457 }
3458 $attrs = array( 'id' => 'mw-editform-cancel' );
3459
3460 return Linker::linkKnown(
3461 $this->getContextTitle(),
3462 wfMessage( 'cancel' )->parse(),
3463 Html::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ),
3464 $cancelParams
3465 );
3466 }
3467
3468 /**
3469 * Returns the URL to use in the form's action attribute.
3470 * This is used by EditPage subclasses when simply customizing the action
3471 * variable in the constructor is not enough. This can be used when the
3472 * EditPage lives inside of a Special page rather than a custom page action.
3473 *
3474 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3475 * @return string
3476 */
3477 protected function getActionURL( Title $title ) {
3478 return $title->getLocalURL( array( 'action' => $this->action ) );
3479 }
3480
3481 /**
3482 * Check if a page was deleted while the user was editing it, before submit.
3483 * Note that we rely on the logging table, which hasn't been always there,
3484 * but that doesn't matter, because this only applies to brand new
3485 * deletes.
3486 * @return bool
3487 */
3488 protected function wasDeletedSinceLastEdit() {
3489 if ( $this->deletedSinceEdit !== null ) {
3490 return $this->deletedSinceEdit;
3491 }
3492
3493 $this->deletedSinceEdit = false;
3494
3495 if ( !$this->mTitle->exists() && $this->mTitle->isDeletedQuick() ) {
3496 $this->lastDelete = $this->getLastDelete();
3497 if ( $this->lastDelete ) {
3498 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3499 if ( $deleteTime > $this->starttime ) {
3500 $this->deletedSinceEdit = true;
3501 }
3502 }
3503 }
3504
3505 return $this->deletedSinceEdit;
3506 }
3507
3508 /**
3509 * @return bool|stdClass
3510 */
3511 protected function getLastDelete() {
3512 $dbr = wfGetDB( DB_SLAVE );
3513 $data = $dbr->selectRow(
3514 array( 'logging', 'user' ),
3515 array(
3516 'log_type',
3517 'log_action',
3518 'log_timestamp',
3519 'log_user',
3520 'log_namespace',
3521 'log_title',
3522 'log_comment',
3523 'log_params',
3524 'log_deleted',
3525 'user_name'
3526 ), array(
3527 'log_namespace' => $this->mTitle->getNamespace(),
3528 'log_title' => $this->mTitle->getDBkey(),
3529 'log_type' => 'delete',
3530 'log_action' => 'delete',
3531 'user_id=log_user'
3532 ),
3533 __METHOD__,
3534 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3535 );
3536 // Quick paranoid permission checks...
3537 if ( is_object( $data ) ) {
3538 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3539 $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
3540 }
3541
3542 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3543 $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
3544 }
3545 }
3546
3547 return $data;
3548 }
3549
3550 /**
3551 * Get the rendered text for previewing.
3552 * @throws MWException
3553 * @return string
3554 */
3555 function getPreviewText() {
3556 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3557 global $wgAllowUserCss, $wgAllowUserJs;
3558
3559 $stats = $wgOut->getContext()->getStats();
3560
3561 if ( $wgRawHtml && !$this->mTokenOk ) {
3562 // Could be an offsite preview attempt. This is very unsafe if
3563 // HTML is enabled, as it could be an attack.
3564 $parsedNote = '';
3565 if ( $this->textbox1 !== '' ) {
3566 // Do not put big scary notice, if previewing the empty
3567 // string, which happens when you initially edit
3568 // a category page, due to automatic preview-on-open.
3569 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3570 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3571 }
3572 $stats->increment( 'edit.failures.session_loss' );
3573 return $parsedNote;
3574 }
3575
3576 $note = '';
3577
3578 try {
3579 $content = $this->toEditContent( $this->textbox1 );
3580
3581 $previewHTML = '';
3582 if ( !Hooks::run(
3583 'AlternateEditPreview',
3584 array( $this, &$content, &$previewHTML, &$this->mParserOutput ) )
3585 ) {
3586 return $previewHTML;
3587 }
3588
3589 # provide a anchor link to the editform
3590 $continueEditing = '<span class="mw-continue-editing">' .
3591 '[[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' .
3592 wfMessage( 'continue-editing' )->text() . ']]</span>';
3593 if ( $this->mTriedSave && !$this->mTokenOk ) {
3594 if ( $this->mTokenOkExceptSuffix ) {
3595 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3596 $stats->increment( 'edit.failures.bad_token' );
3597 } else {
3598 $note = wfMessage( 'session_fail_preview' )->plain();
3599 $stats->increment( 'edit.failures.session_loss' );
3600 }
3601 } elseif ( $this->incompleteForm ) {
3602 $note = wfMessage( 'edit_form_incomplete' )->plain();
3603 if ( $this->mTriedSave ) {
3604 $stats->increment( 'edit.failures.incomplete_form' );
3605 }
3606 } else {
3607 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3608 }
3609
3610 $parserOptions = $this->mArticle->makeParserOptions( $this->mArticle->getContext() );
3611 $parserOptions->setIsPreview( true );
3612 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3613
3614 # don't parse non-wikitext pages, show message about preview
3615 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3616 if ( $this->mTitle->isCssJsSubpage() ) {
3617 $level = 'user';
3618 } elseif ( $this->mTitle->isCssOrJsPage() ) {
3619 $level = 'site';
3620 } else {
3621 $level = false;
3622 }
3623
3624 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3625 $format = 'css';
3626 if ( $level === 'user' && !$wgAllowUserCss ) {
3627 $format = false;
3628 }
3629 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3630 $format = 'js';
3631 if ( $level === 'user' && !$wgAllowUserJs ) {
3632 $format = false;
3633 }
3634 } else {
3635 $format = false;
3636 }
3637
3638 # Used messages to make sure grep find them:
3639 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3640 if ( $level && $format ) {
3641 $note = "<div id='mw-{$level}{$format}preview'>" .
3642 wfMessage( "{$level}{$format}preview" )->text() .
3643 ' ' . $continueEditing . "</div>";
3644 }
3645 }
3646
3647 # If we're adding a comment, we need to show the
3648 # summary as the headline
3649 if ( $this->section === "new" && $this->summary !== "" ) {
3650 $content = $content->addSectionHeader( $this->summary );
3651 }
3652
3653 $hook_args = array( $this, &$content );
3654 ContentHandler::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3655 Hooks::run( 'EditPageGetPreviewContent', $hook_args );
3656
3657 $parserOptions->enableLimitReport();
3658
3659 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3660 # But it's now deprecated, so never mind
3661
3662 $pstContent = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3663 $scopedCallback = $parserOptions->setupFakeRevision(
3664 $this->mTitle, $pstContent, $wgUser );
3665 $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
3666
3667 # Try to stash the edit for the final submission step
3668 # @todo: different date format preferences cause cache misses
3669 ApiStashEdit::stashEditFromPreview(
3670 $this->getArticle(), $content, $pstContent,
3671 $parserOutput, $parserOptions, $parserOptions, wfTimestampNow()
3672 );
3673
3674 $parserOutput->setEditSectionTokens( false ); // no section edit links
3675 $previewHTML = $parserOutput->getText();
3676 $this->mParserOutput = $parserOutput;
3677 $wgOut->addParserOutputMetadata( $parserOutput );
3678
3679 if ( count( $parserOutput->getWarnings() ) ) {
3680 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3681 }
3682 } catch ( MWContentSerializationException $ex ) {
3683 $m = wfMessage(
3684 'content-failed-to-parse',
3685 $this->contentModel,
3686 $this->contentFormat,
3687 $ex->getMessage()
3688 );
3689 $note .= "\n\n" . $m->parse();
3690 $previewHTML = '';
3691 }
3692
3693 if ( $this->isConflict ) {
3694 $conflict = '<h2 id="mw-previewconflict">'
3695 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3696 } else {
3697 $conflict = '<hr />';
3698 }
3699
3700 $previewhead = "<div class='previewnote'>\n" .
3701 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3702 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3703
3704 $pageViewLang = $this->mTitle->getPageViewLanguage();
3705 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3706 'class' => 'mw-content-' . $pageViewLang->getDir() );
3707 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3708
3709 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3710 }
3711
3712 /**
3713 * @return array
3714 */
3715 function getTemplates() {
3716 if ( $this->preview || $this->section != '' ) {
3717 $templates = array();
3718 if ( !isset( $this->mParserOutput ) ) {
3719 return $templates;
3720 }
3721 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3722 foreach ( array_keys( $template ) as $dbk ) {
3723 $templates[] = Title::makeTitle( $ns, $dbk );
3724 }
3725 }
3726 return $templates;
3727 } else {
3728 return $this->mTitle->getTemplateLinksFrom();
3729 }
3730 }
3731
3732 /**
3733 * Shows a bulletin board style toolbar for common editing functions.
3734 * It can be disabled in the user preferences.
3735 *
3736 * @param $title Title object for the page being edited (optional)
3737 * @return string
3738 */
3739 static function getEditToolbar( $title = null ) {
3740 global $wgContLang, $wgOut;
3741 global $wgEnableUploads, $wgForeignFileRepos;
3742
3743 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3744 $showSignature = true;
3745 if ( $title ) {
3746 $showSignature = MWNamespace::wantSignatures( $title->getNamespace() );
3747 }
3748
3749 /**
3750 * $toolarray is an array of arrays each of which includes the
3751 * opening tag, the closing tag, optionally a sample text that is
3752 * inserted between the two when no selection is highlighted
3753 * and. The tip text is shown when the user moves the mouse
3754 * over the button.
3755 *
3756 * Images are defined in ResourceLoaderEditToolbarModule.
3757 */
3758 $toolarray = array(
3759 array(
3760 'id' => 'mw-editbutton-bold',
3761 'open' => '\'\'\'',
3762 'close' => '\'\'\'',
3763 'sample' => wfMessage( 'bold_sample' )->text(),
3764 'tip' => wfMessage( 'bold_tip' )->text(),
3765 ),
3766 array(
3767 'id' => 'mw-editbutton-italic',
3768 'open' => '\'\'',
3769 'close' => '\'\'',
3770 'sample' => wfMessage( 'italic_sample' )->text(),
3771 'tip' => wfMessage( 'italic_tip' )->text(),
3772 ),
3773 array(
3774 'id' => 'mw-editbutton-link',
3775 'open' => '[[',
3776 'close' => ']]',
3777 'sample' => wfMessage( 'link_sample' )->text(),
3778 'tip' => wfMessage( 'link_tip' )->text(),
3779 ),
3780 array(
3781 'id' => 'mw-editbutton-extlink',
3782 'open' => '[',
3783 'close' => ']',
3784 'sample' => wfMessage( 'extlink_sample' )->text(),
3785 'tip' => wfMessage( 'extlink_tip' )->text(),
3786 ),
3787 array(
3788 'id' => 'mw-editbutton-headline',
3789 'open' => "\n== ",
3790 'close' => " ==\n",
3791 'sample' => wfMessage( 'headline_sample' )->text(),
3792 'tip' => wfMessage( 'headline_tip' )->text(),
3793 ),
3794 $imagesAvailable ? array(
3795 'id' => 'mw-editbutton-image',
3796 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3797 'close' => ']]',
3798 'sample' => wfMessage( 'image_sample' )->text(),
3799 'tip' => wfMessage( 'image_tip' )->text(),
3800 ) : false,
3801 $imagesAvailable ? array(
3802 'id' => 'mw-editbutton-media',
3803 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3804 'close' => ']]',
3805 'sample' => wfMessage( 'media_sample' )->text(),
3806 'tip' => wfMessage( 'media_tip' )->text(),
3807 ) : false,
3808 array(
3809 'id' => 'mw-editbutton-nowiki',
3810 'open' => "<nowiki>",
3811 'close' => "</nowiki>",
3812 'sample' => wfMessage( 'nowiki_sample' )->text(),
3813 'tip' => wfMessage( 'nowiki_tip' )->text(),
3814 ),
3815 $showSignature ? array(
3816 'id' => 'mw-editbutton-signature',
3817 'open' => '--~~~~',
3818 'close' => '',
3819 'sample' => '',
3820 'tip' => wfMessage( 'sig_tip' )->text(),
3821 ) : false,
3822 array(
3823 'id' => 'mw-editbutton-hr',
3824 'open' => "\n----\n",
3825 'close' => '',
3826 'sample' => '',
3827 'tip' => wfMessage( 'hr_tip' )->text(),
3828 )
3829 );
3830
3831 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3832 foreach ( $toolarray as $tool ) {
3833 if ( !$tool ) {
3834 continue;
3835 }
3836
3837 $params = array(
3838 // Images are defined in ResourceLoaderEditToolbarModule
3839 false,
3840 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3841 // Older browsers show a "speedtip" type message only for ALT.
3842 // Ideally these should be different, realistically they
3843 // probably don't need to be.
3844 $tool['tip'],
3845 $tool['open'],
3846 $tool['close'],
3847 $tool['sample'],
3848 $tool['id'],
3849 );
3850
3851 $script .= Xml::encodeJsCall(
3852 'mw.toolbar.addButton',
3853 $params,
3854 ResourceLoader::inDebugMode()
3855 );
3856 }
3857
3858 $script .= '});';
3859 $wgOut->addScript( ResourceLoader::makeInlineScript( $script ) );
3860
3861 $toolbar = '<div id="toolbar"></div>';
3862
3863 Hooks::run( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3864
3865 return $toolbar;
3866 }
3867
3868 /**
3869 * Returns an array of html code of the following checkboxes:
3870 * minor and watch
3871 *
3872 * @param int $tabindex Current tabindex
3873 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3874 * status of the checkbox
3875 *
3876 * @return array
3877 */
3878 public function getCheckboxes( &$tabindex, $checked ) {
3879 global $wgUser, $wgUseMediaWikiUIEverywhere;
3880
3881 $checkboxes = array();
3882
3883 // don't show the minor edit checkbox if it's a new page or section
3884 if ( !$this->isNew ) {
3885 $checkboxes['minor'] = '';
3886 $minorLabel = wfMessage( 'minoredit' )->parse();
3887 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3888 $attribs = array(
3889 'tabindex' => ++$tabindex,
3890 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3891 'id' => 'wpMinoredit',
3892 );
3893 $minorEditHtml =
3894 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3895 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
3896 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3897 ">{$minorLabel}</label>";
3898
3899 if ( $wgUseMediaWikiUIEverywhere ) {
3900 $checkboxes['minor'] = Html::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3901 $minorEditHtml .
3902 Html::closeElement( 'div' );
3903 } else {
3904 $checkboxes['minor'] = $minorEditHtml;
3905 }
3906 }
3907 }
3908
3909 $watchLabel = wfMessage( 'watchthis' )->parse();
3910 $checkboxes['watch'] = '';
3911 if ( $wgUser->isLoggedIn() ) {
3912 $attribs = array(
3913 'tabindex' => ++$tabindex,
3914 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3915 'id' => 'wpWatchthis',
3916 );
3917 $watchThisHtml =
3918 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3919 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
3920 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
3921 ">{$watchLabel}</label>";
3922 if ( $wgUseMediaWikiUIEverywhere ) {
3923 $checkboxes['watch'] = Html::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3924 $watchThisHtml .
3925 Html::closeElement( 'div' );
3926 } else {
3927 $checkboxes['watch'] = $watchThisHtml;
3928 }
3929 }
3930 Hooks::run( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3931 return $checkboxes;
3932 }
3933
3934 /**
3935 * Returns an array of html code of the following buttons:
3936 * save, diff, preview and live
3937 *
3938 * @param int $tabindex Current tabindex
3939 *
3940 * @return array
3941 */
3942 public function getEditButtons( &$tabindex ) {
3943 $buttons = array();
3944
3945 $attribs = array(
3946 'id' => 'wpSave',
3947 'name' => 'wpSave',
3948 'tabindex' => ++$tabindex,
3949 ) + Linker::tooltipAndAccesskeyAttribs( 'save' );
3950 $buttons['save'] = Html::submitButton( wfMessage( 'savearticle' )->text(),
3951 $attribs, array( 'mw-ui-constructive' ) );
3952
3953 ++$tabindex; // use the same for preview and live preview
3954 $attribs = array(
3955 'id' => 'wpPreview',
3956 'name' => 'wpPreview',
3957 'tabindex' => $tabindex,
3958 ) + Linker::tooltipAndAccesskeyAttribs( 'preview' );
3959 $buttons['preview'] = Html::submitButton( wfMessage( 'showpreview' )->text(),
3960 $attribs );
3961 $buttons['live'] = '';
3962
3963 $attribs = array(
3964 'id' => 'wpDiff',
3965 'name' => 'wpDiff',
3966 'tabindex' => ++$tabindex,
3967 ) + Linker::tooltipAndAccesskeyAttribs( 'diff' );
3968 $buttons['diff'] = Html::submitButton( wfMessage( 'showdiff' )->text(),
3969 $attribs );
3970
3971 Hooks::run( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3972 return $buttons;
3973 }
3974
3975 /**
3976 * Creates a basic error page which informs the user that
3977 * they have attempted to edit a nonexistent section.
3978 */
3979 function noSuchSectionPage() {
3980 global $wgOut;
3981
3982 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3983
3984 $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
3985 Hooks::run( 'EditPageNoSuchSection', array( &$this, &$res ) );
3986 $wgOut->addHTML( $res );
3987
3988 $wgOut->returnToMain( false, $this->mTitle );
3989 }
3990
3991 /**
3992 * Show "your edit contains spam" page with your diff and text
3993 *
3994 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
3995 */
3996 public function spamPageWithContent( $match = false ) {
3997 global $wgOut, $wgLang;
3998 $this->textbox2 = $this->textbox1;
3999
4000 if ( is_array( $match ) ) {
4001 $match = $wgLang->listToText( $match );
4002 }
4003 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
4004
4005 $wgOut->addHTML( '<div id="spamprotected">' );
4006 $wgOut->addWikiMsg( 'spamprotectiontext' );
4007 if ( $match ) {
4008 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
4009 }
4010 $wgOut->addHTML( '</div>' );
4011
4012 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
4013 $this->showDiff();
4014
4015 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
4016 $this->showTextbox2();
4017
4018 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
4019 }
4020
4021 /**
4022 * Check if the browser is on a blacklist of user-agents known to
4023 * mangle UTF-8 data on form submission. Returns true if Unicode
4024 * should make it through, false if it's known to be a problem.
4025 * @return bool
4026 */
4027 private function checkUnicodeCompliantBrowser() {
4028 global $wgBrowserBlackList, $wgRequest;
4029
4030 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
4031 if ( $currentbrowser === false ) {
4032 // No User-Agent header sent? Trust it by default...
4033 return true;
4034 }
4035
4036 foreach ( $wgBrowserBlackList as $browser ) {
4037 if ( preg_match( $browser, $currentbrowser ) ) {
4038 return false;
4039 }
4040 }
4041 return true;
4042 }
4043
4044 /**
4045 * Filter an input field through a Unicode de-armoring process if it
4046 * came from an old browser with known broken Unicode editing issues.
4047 *
4048 * @param WebRequest $request
4049 * @param string $field
4050 * @return string
4051 */
4052 protected function safeUnicodeInput( $request, $field ) {
4053 $text = rtrim( $request->getText( $field ) );
4054 return $request->getBool( 'safemode' )
4055 ? $this->unmakeSafe( $text )
4056 : $text;
4057 }
4058
4059 /**
4060 * Filter an output field through a Unicode armoring process if it is
4061 * going to an old browser with known broken Unicode editing issues.
4062 *
4063 * @param string $text
4064 * @return string
4065 */
4066 protected function safeUnicodeOutput( $text ) {
4067 global $wgContLang;
4068 $codedText = $wgContLang->recodeForEdit( $text );
4069 return $this->checkUnicodeCompliantBrowser()
4070 ? $codedText
4071 : $this->makeSafe( $codedText );
4072 }
4073
4074 /**
4075 * A number of web browsers are known to corrupt non-ASCII characters
4076 * in a UTF-8 text editing environment. To protect against this,
4077 * detected browsers will be served an armored version of the text,
4078 * with non-ASCII chars converted to numeric HTML character references.
4079 *
4080 * Preexisting such character references will have a 0 added to them
4081 * to ensure that round-trips do not alter the original data.
4082 *
4083 * @param string $invalue
4084 * @return string
4085 */
4086 private function makeSafe( $invalue ) {
4087 // Armor existing references for reversibility.
4088 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
4089
4090 $bytesleft = 0;
4091 $result = "";
4092 $working = 0;
4093 $valueLength = strlen( $invalue );
4094 for ( $i = 0; $i < $valueLength; $i++ ) {
4095 $bytevalue = ord( $invalue[$i] );
4096 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4097 $result .= chr( $bytevalue );
4098 $bytesleft = 0;
4099 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4100 $working = $working << 6;
4101 $working += ( $bytevalue & 0x3F );
4102 $bytesleft--;
4103 if ( $bytesleft <= 0 ) {
4104 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4105 }
4106 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4107 $working = $bytevalue & 0x1F;
4108 $bytesleft = 1;
4109 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4110 $working = $bytevalue & 0x0F;
4111 $bytesleft = 2;
4112 } else { // 1111 0xxx
4113 $working = $bytevalue & 0x07;
4114 $bytesleft = 3;
4115 }
4116 }
4117 return $result;
4118 }
4119
4120 /**
4121 * Reverse the previously applied transliteration of non-ASCII characters
4122 * back to UTF-8. Used to protect data from corruption by broken web browsers
4123 * as listed in $wgBrowserBlackList.
4124 *
4125 * @param string $invalue
4126 * @return string
4127 */
4128 private function unmakeSafe( $invalue ) {
4129 $result = "";
4130 $valueLength = strlen( $invalue );
4131 for ( $i = 0; $i < $valueLength; $i++ ) {
4132 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
4133 $i += 3;
4134 $hexstring = "";
4135 do {
4136 $hexstring .= $invalue[$i];
4137 $i++;
4138 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4139
4140 // Do some sanity checks. These aren't needed for reversibility,
4141 // but should help keep the breakage down if the editor
4142 // breaks one of the entities whilst editing.
4143 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4144 $codepoint = hexdec( $hexstring );
4145 $result .= UtfNormal\Utils::codepointToUtf8( $codepoint );
4146 } else {
4147 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4148 }
4149 } else {
4150 $result .= substr( $invalue, $i, 1 );
4151 }
4152 }
4153 // reverse the transform that we made for reversibility reasons.
4154 return strtr( $result, array( "&#x0" => "&#x" ) );
4155 }
4156 }