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