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