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