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