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