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