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