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