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