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