Switch some HTMLForms in special pages to OOUI
[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 if ( $this->contentModel !== $this->mTitle->getContentModel() ) {
1675 if ( !$wgContentHandlerUseDB ) {
1676 $status->fatal( 'editpage-cannot-use-custom-model' );
1677 $status->value = self::AS_CANNOT_USE_CUSTOM_MODEL;
1678 return $status;
1679 } elseif ( !$wgUser->isAllowed( 'editcontentmodel' ) ) {
1680 $status->setResult( false, self::AS_NO_CHANGE_CONTENT_MODEL );
1681 return $status;
1682 }
1683 }
1684
1685 if ( $this->changeTags ) {
1686 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
1687 $this->changeTags, $wgUser );
1688 if ( !$changeTagsStatus->isOK() ) {
1689 $changeTagsStatus->value = self::AS_CHANGE_TAG_ERROR;
1690 return $changeTagsStatus;
1691 }
1692 }
1693
1694 if ( wfReadOnly() ) {
1695 $status->fatal( 'readonlytext' );
1696 $status->value = self::AS_READ_ONLY_PAGE;
1697 return $status;
1698 }
1699 if ( $wgUser->pingLimiter() || $wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1700 $status->fatal( 'actionthrottledtext' );
1701 $status->value = self::AS_RATE_LIMITED;
1702 return $status;
1703 }
1704
1705 # If the article has been deleted while editing, don't save it without
1706 # confirmation
1707 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1708 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1709 return $status;
1710 }
1711
1712 # Load the page data from the master. If anything changes in the meantime,
1713 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1714 $this->mArticle->loadPageData( 'fromdbmaster' );
1715 $new = !$this->mArticle->exists();
1716
1717 if ( $new ) {
1718 // Late check for create permission, just in case *PARANOIA*
1719 if ( !$this->mTitle->userCan( 'create', $wgUser ) ) {
1720 $status->fatal( 'nocreatetext' );
1721 $status->value = self::AS_NO_CREATE_PERMISSION;
1722 wfDebug( __METHOD__ . ": no create permission\n" );
1723 return $status;
1724 }
1725
1726 // Don't save a new page if it's blank or if it's a MediaWiki:
1727 // message with content equivalent to default (allow empty pages
1728 // in this case to disable messages, see bug 50124)
1729 $defaultMessageText = $this->mTitle->getDefaultMessageText();
1730 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1731 $defaultText = $defaultMessageText;
1732 } else {
1733 $defaultText = '';
1734 }
1735
1736 if ( !$this->allowBlankArticle && $this->textbox1 === $defaultText ) {
1737 $this->blankArticle = true;
1738 $status->fatal( 'blankarticle' );
1739 $status->setResult( false, self::AS_BLANK_ARTICLE );
1740 return $status;
1741 }
1742
1743 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1744 return $status;
1745 }
1746
1747 $content = $textbox_content;
1748
1749 $result['sectionanchor'] = '';
1750 if ( $this->section == 'new' ) {
1751 if ( $this->sectiontitle !== '' ) {
1752 // Insert the section title above the content.
1753 $content = $content->addSectionHeader( $this->sectiontitle );
1754 } elseif ( $this->summary !== '' ) {
1755 // Insert the section title above the content.
1756 $content = $content->addSectionHeader( $this->summary );
1757 }
1758 $this->summary = $this->newSectionSummary( $result['sectionanchor'] );
1759 }
1760
1761 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1762
1763 } else { # not $new
1764
1765 # Article exists. Check for edit conflict.
1766
1767 $this->mArticle->clear(); # Force reload of dates, etc.
1768 $timestamp = $this->mArticle->getTimestamp();
1769
1770 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1771
1772 if ( $timestamp != $this->edittime ) {
1773 $this->isConflict = true;
1774 if ( $this->section == 'new' ) {
1775 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
1776 $this->mArticle->getComment() == $this->newSectionSummary()
1777 ) {
1778 // Probably a duplicate submission of a new comment.
1779 // This can happen when squid resends a request after
1780 // a timeout but the first one actually went through.
1781 wfDebug( __METHOD__
1782 . ": duplicate new section submission; trigger edit conflict!\n" );
1783 } else {
1784 // New comment; suppress conflict.
1785 $this->isConflict = false;
1786 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1787 }
1788 } elseif ( $this->section == ''
1789 && Revision::userWasLastToEdit(
1790 DB_MASTER, $this->mTitle->getArticleID(),
1791 $wgUser->getId(), $this->edittime
1792 )
1793 ) {
1794 # Suppress edit conflict with self, except for section edits where merging is required.
1795 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1796 $this->isConflict = false;
1797 }
1798 }
1799
1800 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1801 if ( $this->sectiontitle !== '' ) {
1802 $sectionTitle = $this->sectiontitle;
1803 } else {
1804 $sectionTitle = $this->summary;
1805 }
1806
1807 $content = null;
1808
1809 if ( $this->isConflict ) {
1810 wfDebug( __METHOD__
1811 . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1812 . " (article time '{$timestamp}')\n" );
1813
1814 $content = $this->mArticle->replaceSectionContent(
1815 $this->section,
1816 $textbox_content,
1817 $sectionTitle,
1818 $this->edittime
1819 );
1820 } else {
1821 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
1822 $content = $this->mArticle->replaceSectionContent(
1823 $this->section,
1824 $textbox_content,
1825 $sectionTitle
1826 );
1827 }
1828
1829 if ( is_null( $content ) ) {
1830 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1831 $this->isConflict = true;
1832 $content = $textbox_content; // do not try to merge here!
1833 } elseif ( $this->isConflict ) {
1834 # Attempt merge
1835 if ( $this->mergeChangesIntoContent( $content ) ) {
1836 // Successful merge! Maybe we should tell the user the good news?
1837 $this->isConflict = false;
1838 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1839 } else {
1840 $this->section = '';
1841 $this->textbox1 = ContentHandler::getContentText( $content );
1842 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1843 }
1844 }
1845
1846 if ( $this->isConflict ) {
1847 $status->setResult( false, self::AS_CONFLICT_DETECTED );
1848 return $status;
1849 }
1850
1851 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1852 return $status;
1853 }
1854
1855 if ( $this->section == 'new' ) {
1856 // Handle the user preference to force summaries here
1857 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
1858 $this->missingSummary = true;
1859 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1860 $status->value = self::AS_SUMMARY_NEEDED;
1861 return $status;
1862 }
1863
1864 // Do not allow the user to post an empty comment
1865 if ( $this->textbox1 == '' ) {
1866 $this->missingComment = true;
1867 $status->fatal( 'missingcommenttext' );
1868 $status->value = self::AS_TEXTBOX_EMPTY;
1869 return $status;
1870 }
1871 } elseif ( !$this->allowBlankSummary
1872 && !$content->equals( $this->getOriginalContent( $wgUser ) )
1873 && !$content->isRedirect()
1874 && md5( $this->summary ) == $this->autoSumm
1875 ) {
1876 $this->missingSummary = true;
1877 $status->fatal( 'missingsummary' );
1878 $status->value = self::AS_SUMMARY_NEEDED;
1879 return $status;
1880 }
1881
1882 # All's well
1883 $sectionanchor = '';
1884 if ( $this->section == 'new' ) {
1885 $this->summary = $this->newSectionSummary( $sectionanchor );
1886 } elseif ( $this->section != '' ) {
1887 # Try to get a section anchor from the section source, redirect
1888 # to edited section if header found.
1889 # XXX: Might be better to integrate this into Article::replaceSection
1890 # for duplicate heading checking and maybe parsing.
1891 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1892 # We can't deal with anchors, includes, html etc in the header for now,
1893 # headline would need to be parsed to improve this.
1894 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1895 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1896 }
1897 }
1898 $result['sectionanchor'] = $sectionanchor;
1899
1900 // Save errors may fall down to the edit form, but we've now
1901 // merged the section into full text. Clear the section field
1902 // so that later submission of conflict forms won't try to
1903 // replace that into a duplicated mess.
1904 $this->textbox1 = $this->toEditText( $content );
1905 $this->section = '';
1906
1907 $status->value = self::AS_SUCCESS_UPDATE;
1908 }
1909
1910 if ( !$this->allowSelfRedirect
1911 && $content->isRedirect()
1912 && $content->getRedirectTarget()->equals( $this->getTitle() )
1913 ) {
1914 // If the page already redirects to itself, don't warn.
1915 $currentTarget = $this->getCurrentContent()->getRedirectTarget();
1916 if ( !$currentTarget || !$currentTarget->equals( $this->getTitle() ) ) {
1917 $this->selfRedirect = true;
1918 $status->fatal( 'selfredirect' );
1919 $status->value = self::AS_SELF_REDIRECT;
1920 return $status;
1921 }
1922 }
1923
1924 // Check for length errors again now that the section is merged in
1925 $this->kblength = (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1926 if ( $this->kblength > $wgMaxArticleSize ) {
1927 $this->tooBig = true;
1928 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
1929 return $status;
1930 }
1931
1932 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1933 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
1934 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
1935 ( $bot ? EDIT_FORCE_BOT : 0 );
1936
1937 $doEditStatus = $this->mArticle->doEditContent(
1938 $content,
1939 $this->summary,
1940 $flags,
1941 false,
1942 null,
1943 $content->getDefaultFormat()
1944 );
1945
1946 if ( !$doEditStatus->isOK() ) {
1947 // Failure from doEdit()
1948 // Show the edit conflict page for certain recognized errors from doEdit(),
1949 // but don't show it for errors from extension hooks
1950 $errors = $doEditStatus->getErrorsArray();
1951 if ( in_array( $errors[0][0],
1952 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
1953 ) {
1954 $this->isConflict = true;
1955 // Destroys data doEdit() put in $status->value but who cares
1956 $doEditStatus->value = self::AS_END;
1957 }
1958 return $doEditStatus;
1959 }
1960
1961 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1962 if ( $result['nullEdit'] ) {
1963 // We don't know if it was a null edit until now, so increment here
1964 $wgUser->pingLimiter( 'linkpurge' );
1965 }
1966 $result['redirect'] = $content->isRedirect();
1967
1968 $this->updateWatchlist();
1969
1970 if ( $this->changeTags && isset( $doEditStatus->value['revision'] ) ) {
1971 // If a revision was created, apply any change tags that were requested
1972 $addTags = $this->changeTags;
1973 $revId = $doEditStatus->value['revision']->getId();
1974 // Defer this both for performance and so that addTags() sees the rc_id
1975 // since the recentchange entry addition is deferred first (bug T100248)
1976 DeferredUpdates::addCallableUpdate( function() use ( $addTags, $revId ) {
1977 ChangeTags::addTags( $addTags, null, $revId );
1978 } );
1979 }
1980
1981 return $status;
1982 }
1983
1984 /**
1985 * Register the change of watch status
1986 */
1987 protected function updateWatchlist() {
1988 global $wgUser;
1989
1990 if ( $wgUser->isLoggedIn()
1991 && $this->watchthis != $wgUser->isWatched( $this->mTitle, WatchedItem::IGNORE_USER_RIGHTS )
1992 ) {
1993 $fname = __METHOD__;
1994 $title = $this->mTitle;
1995 $watch = $this->watchthis;
1996
1997 // Do this in its own transaction to reduce contention...
1998 $dbw = wfGetDB( DB_MASTER );
1999 $dbw->onTransactionIdle( function () use ( $dbw, $title, $watch, $wgUser, $fname ) {
2000 WatchAction::doWatchOrUnwatch( $watch, $title, $wgUser );
2001 } );
2002 }
2003 }
2004
2005 /**
2006 * Attempts to do 3-way merge of edit content with a base revision
2007 * and current content, in case of edit conflict, in whichever way appropriate
2008 * for the content type.
2009 *
2010 * @since 1.21
2011 *
2012 * @param Content $editContent
2013 *
2014 * @return bool
2015 */
2016 private function mergeChangesIntoContent( &$editContent ) {
2017
2018 $db = wfGetDB( DB_MASTER );
2019
2020 // This is the revision the editor started from
2021 $baseRevision = $this->getBaseRevision();
2022 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
2023
2024 if ( is_null( $baseContent ) ) {
2025 return false;
2026 }
2027
2028 // The current state, we want to merge updates into it
2029 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2030 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
2031
2032 if ( is_null( $currentContent ) ) {
2033 return false;
2034 }
2035
2036 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
2037
2038 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
2039
2040 if ( $result ) {
2041 $editContent = $result;
2042 return true;
2043 }
2044
2045 return false;
2046 }
2047
2048 /**
2049 * @return Revision
2050 */
2051 function getBaseRevision() {
2052 if ( !$this->mBaseRevision ) {
2053 $db = wfGetDB( DB_MASTER );
2054 $this->mBaseRevision = Revision::loadFromTimestamp(
2055 $db, $this->mTitle, $this->edittime );
2056 }
2057 return $this->mBaseRevision;
2058 }
2059
2060 /**
2061 * Check given input text against $wgSpamRegex, and return the text of the first match.
2062 *
2063 * @param string $text
2064 *
2065 * @return string|bool Matching string or false
2066 */
2067 public static function matchSpamRegex( $text ) {
2068 global $wgSpamRegex;
2069 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
2070 $regexes = (array)$wgSpamRegex;
2071 return self::matchSpamRegexInternal( $text, $regexes );
2072 }
2073
2074 /**
2075 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
2076 *
2077 * @param string $text
2078 *
2079 * @return string|bool Matching string or false
2080 */
2081 public static function matchSummarySpamRegex( $text ) {
2082 global $wgSummarySpamRegex;
2083 $regexes = (array)$wgSummarySpamRegex;
2084 return self::matchSpamRegexInternal( $text, $regexes );
2085 }
2086
2087 /**
2088 * @param string $text
2089 * @param array $regexes
2090 * @return bool|string
2091 */
2092 protected static function matchSpamRegexInternal( $text, $regexes ) {
2093 foreach ( $regexes as $regex ) {
2094 $matches = array();
2095 if ( preg_match( $regex, $text, $matches ) ) {
2096 return $matches[0];
2097 }
2098 }
2099 return false;
2100 }
2101
2102 function setHeaders() {
2103 global $wgOut, $wgUser, $wgAjaxEditStash;
2104
2105 $wgOut->addModules( 'mediawiki.action.edit' );
2106 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
2107
2108 if ( $wgUser->getOption( 'showtoolbar' ) ) {
2109 // The addition of default buttons is handled by getEditToolbar() which
2110 // has its own dependency on this module. The call here ensures the module
2111 // is loaded in time (it has position "top") for other modules to register
2112 // buttons (e.g. extensions, gadgets, user scripts).
2113 $wgOut->addModules( 'mediawiki.toolbar' );
2114 }
2115
2116 if ( $wgUser->getOption( 'uselivepreview' ) ) {
2117 $wgOut->addModules( 'mediawiki.action.edit.preview' );
2118 }
2119
2120 if ( $wgUser->getOption( 'useeditwarning' ) ) {
2121 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
2122 }
2123
2124 if ( $wgAjaxEditStash ) {
2125 $wgOut->addModules( 'mediawiki.action.edit.stash' );
2126 }
2127
2128 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2129
2130 # Enabled article-related sidebar, toplinks, etc.
2131 $wgOut->setArticleRelated( true );
2132
2133 $contextTitle = $this->getContextTitle();
2134 if ( $this->isConflict ) {
2135 $msg = 'editconflict';
2136 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2137 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2138 } else {
2139 $msg = $contextTitle->exists()
2140 || ( $contextTitle->getNamespace() == NS_MEDIAWIKI
2141 && $contextTitle->getDefaultMessageText() !== false
2142 )
2143 ? 'editing'
2144 : 'creating';
2145 }
2146
2147 # Use the title defined by DISPLAYTITLE magic word when present
2148 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2149 if ( $displayTitle === false ) {
2150 $displayTitle = $contextTitle->getPrefixedText();
2151 }
2152 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2153 # Transmit the name of the message to JavaScript for live preview
2154 # Keep Resources.php/mediawiki.action.edit.preview in sync with the possible keys
2155 $wgOut->addJsConfigVars( 'wgEditMessage', $msg );
2156 }
2157
2158 /**
2159 * Show all applicable editing introductions
2160 */
2161 protected function showIntro() {
2162 global $wgOut, $wgUser;
2163 if ( $this->suppressIntro ) {
2164 return;
2165 }
2166
2167 $namespace = $this->mTitle->getNamespace();
2168
2169 if ( $namespace == NS_MEDIAWIKI ) {
2170 # Show a warning if editing an interface message
2171 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2172 # If this is a default message (but not css or js),
2173 # show a hint that it is translatable on translatewiki.net
2174 if ( !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2175 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2176 ) {
2177 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2178 if ( $defaultMessageText !== false ) {
2179 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2180 'translateinterface' );
2181 }
2182 }
2183 } elseif ( $namespace == NS_FILE ) {
2184 # Show a hint to shared repo
2185 $file = wfFindFile( $this->mTitle );
2186 if ( $file && !$file->isLocal() ) {
2187 $descUrl = $file->getDescriptionUrl();
2188 # there must be a description url to show a hint to shared repo
2189 if ( $descUrl ) {
2190 if ( !$this->mTitle->exists() ) {
2191 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2192 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2193 ) );
2194 } else {
2195 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2196 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2197 ) );
2198 }
2199 }
2200 }
2201 }
2202
2203 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2204 # Show log extract when the user is currently blocked
2205 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2206 $parts = explode( '/', $this->mTitle->getText(), 2 );
2207 $username = $parts[0];
2208 $user = User::newFromName( $username, false /* allow IP users*/ );
2209 $ip = User::isIP( $username );
2210 $block = Block::newFromTarget( $user, $user );
2211 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2212 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2213 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2214 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
2215 # Show log extract if the user is currently blocked
2216 LogEventsList::showLogExtract(
2217 $wgOut,
2218 'block',
2219 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2220 '',
2221 array(
2222 'lim' => 1,
2223 'showIfEmpty' => false,
2224 'msgKey' => array(
2225 'blocked-notice-logextract',
2226 $user->getName() # Support GENDER in notice
2227 )
2228 )
2229 );
2230 }
2231 }
2232 # Try to add a custom edit intro, or use the standard one if this is not possible.
2233 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2234 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2235 wfMessage( 'helppage' )->inContentLanguage()->text()
2236 ) );
2237 if ( $wgUser->isLoggedIn() ) {
2238 $wgOut->wrapWikiMsg(
2239 // Suppress the external link icon, consider the help url an internal one
2240 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2241 array(
2242 'newarticletext',
2243 $helpLink
2244 )
2245 );
2246 } else {
2247 $wgOut->wrapWikiMsg(
2248 // Suppress the external link icon, consider the help url an internal one
2249 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2250 array(
2251 'newarticletextanon',
2252 $helpLink
2253 )
2254 );
2255 }
2256 }
2257 # Give a notice if the user is editing a deleted/moved page...
2258 if ( !$this->mTitle->exists() ) {
2259 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
2260 '',
2261 array(
2262 'lim' => 10,
2263 'conds' => array( "log_action != 'revision'" ),
2264 'showIfEmpty' => false,
2265 'msgKey' => array( 'recreate-moveddeleted-warn' )
2266 )
2267 );
2268 }
2269 }
2270
2271 /**
2272 * Attempt to show a custom editing introduction, if supplied
2273 *
2274 * @return bool
2275 */
2276 protected function showCustomIntro() {
2277 if ( $this->editintro ) {
2278 $title = Title::newFromText( $this->editintro );
2279 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2280 global $wgOut;
2281 // Added using template syntax, to take <noinclude>'s into account.
2282 $wgOut->addWikiTextTitleTidy(
2283 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2284 $this->mTitle
2285 );
2286 return true;
2287 }
2288 }
2289 return false;
2290 }
2291
2292 /**
2293 * Gets an editable textual representation of $content.
2294 * The textual representation can be turned by into a Content object by the
2295 * toEditContent() method.
2296 *
2297 * If $content is null or false or a string, $content is returned unchanged.
2298 *
2299 * If the given Content object is not of a type that can be edited using
2300 * the text base EditPage, an exception will be raised. Set
2301 * $this->allowNonTextContent to true to allow editing of non-textual
2302 * content.
2303 *
2304 * @param Content|null|bool|string $content
2305 * @return string The editable text form of the content.
2306 *
2307 * @throws MWException If $content is not an instance of TextContent and
2308 * $this->allowNonTextContent is not true.
2309 */
2310 protected function toEditText( $content ) {
2311 if ( $content === null || $content === false || is_string( $content ) ) {
2312 return $content;
2313 }
2314
2315 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2316 throw new MWException( 'This content model is not supported: '
2317 . ContentHandler::getLocalizedName( $content->getModel() ) );
2318 }
2319
2320 return $content->serialize( $this->contentFormat );
2321 }
2322
2323 /**
2324 * Turns the given text into a Content object by unserializing it.
2325 *
2326 * If the resulting Content object is not of a type that can be edited using
2327 * the text base EditPage, an exception will be raised. Set
2328 * $this->allowNonTextContent to true to allow editing of non-textual
2329 * content.
2330 *
2331 * @param string|null|bool $text Text to unserialize
2332 * @return Content The content object created from $text. If $text was false
2333 * or null, false resp. null will be returned instead.
2334 *
2335 * @throws MWException If unserializing the text results in a Content
2336 * object that is not an instance of TextContent and
2337 * $this->allowNonTextContent is not true.
2338 */
2339 protected function toEditContent( $text ) {
2340 if ( $text === false || $text === null ) {
2341 return $text;
2342 }
2343
2344 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2345 $this->contentModel, $this->contentFormat );
2346
2347 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2348 throw new MWException( 'This content model is not supported: '
2349 . ContentHandler::getLocalizedName( $content->getModel() ) );
2350 }
2351
2352 return $content;
2353 }
2354
2355 /**
2356 * Send the edit form and related headers to $wgOut
2357 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2358 * during form output near the top, for captchas and the like.
2359 *
2360 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2361 * use the EditPage::showEditForm:fields hook instead.
2362 */
2363 function showEditForm( $formCallback = null ) {
2364 global $wgOut, $wgUser;
2365
2366 # need to parse the preview early so that we know which templates are used,
2367 # otherwise users with "show preview after edit box" will get a blank list
2368 # we parse this near the beginning so that setHeaders can do the title
2369 # setting work instead of leaving it in getPreviewText
2370 $previewOutput = '';
2371 if ( $this->formtype == 'preview' ) {
2372 $previewOutput = $this->getPreviewText();
2373 }
2374
2375 Hooks::run( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2376
2377 $this->setHeaders();
2378
2379 if ( $this->showHeader() === false ) {
2380 return;
2381 }
2382
2383 $wgOut->addHTML( $this->editFormPageTop );
2384
2385 if ( $wgUser->getOption( 'previewontop' ) ) {
2386 $this->displayPreviewArea( $previewOutput, true );
2387 }
2388
2389 $wgOut->addHTML( $this->editFormTextTop );
2390
2391 $showToolbar = true;
2392 if ( $this->wasDeletedSinceLastEdit() ) {
2393 if ( $this->formtype == 'save' ) {
2394 // Hide the toolbar and edit area, user can click preview to get it back
2395 // Add an confirmation checkbox and explanation.
2396 $showToolbar = false;
2397 } else {
2398 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2399 'deletedwhileediting' );
2400 }
2401 }
2402
2403 // @todo add EditForm plugin interface and use it here!
2404 // search for textarea1 and textares2, and allow EditForm to override all uses.
2405 $wgOut->addHTML( Html::openElement(
2406 'form',
2407 array(
2408 'id' => self::EDITFORM_ID,
2409 'name' => self::EDITFORM_ID,
2410 'method' => 'post',
2411 'action' => $this->getActionURL( $this->getContextTitle() ),
2412 'enctype' => 'multipart/form-data'
2413 )
2414 ) );
2415
2416 if ( is_callable( $formCallback ) ) {
2417 wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2418 call_user_func_array( $formCallback, array( &$wgOut ) );
2419 }
2420
2421 // Add an empty field to trip up spambots
2422 $wgOut->addHTML(
2423 Xml::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2424 . Html::rawElement(
2425 'label',
2426 array( 'for' => 'wpAntiSpam' ),
2427 wfMessage( 'simpleantispam-label' )->parse()
2428 )
2429 . Xml::element(
2430 'input',
2431 array(
2432 'type' => 'text',
2433 'name' => 'wpAntispam',
2434 'id' => 'wpAntispam',
2435 'value' => ''
2436 )
2437 )
2438 . Xml::closeElement( 'div' )
2439 );
2440
2441 Hooks::run( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2442
2443 // Put these up at the top to ensure they aren't lost on early form submission
2444 $this->showFormBeforeText();
2445
2446 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2447 $username = $this->lastDelete->user_name;
2448 $comment = $this->lastDelete->log_comment;
2449
2450 // It is better to not parse the comment at all than to have templates expanded in the middle
2451 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2452 $key = $comment === ''
2453 ? 'confirmrecreate-noreason'
2454 : 'confirmrecreate';
2455 $wgOut->addHTML(
2456 '<div class="mw-confirm-recreate">' .
2457 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2458 Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2459 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2460 ) .
2461 '</div>'
2462 );
2463 }
2464
2465 # When the summary is hidden, also hide them on preview/show changes
2466 if ( $this->nosummary ) {
2467 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2468 }
2469
2470 # If a blank edit summary was previously provided, and the appropriate
2471 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2472 # user being bounced back more than once in the event that a summary
2473 # is not required.
2474 #####
2475 # For a bit more sophisticated detection of blank summaries, hash the
2476 # automatic one and pass that in the hidden field wpAutoSummary.
2477 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2478 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2479 }
2480
2481 if ( $this->undidRev ) {
2482 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2483 }
2484
2485 if ( $this->selfRedirect ) {
2486 $wgOut->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2487 }
2488
2489 if ( $this->hasPresetSummary ) {
2490 // If a summary has been preset using &summary= we don't want to prompt for
2491 // a different summary. Only prompt for a summary if the summary is blanked.
2492 // (Bug 17416)
2493 $this->autoSumm = md5( '' );
2494 }
2495
2496 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2497 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2498
2499 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2500 $wgOut->addHTML( Html::hidden( 'parentRevId',
2501 $this->parentRevId ?: $this->mArticle->getRevIdFetched() ) );
2502
2503 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2504 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2505
2506 if ( $this->section == 'new' ) {
2507 $this->showSummaryInput( true, $this->summary );
2508 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2509 }
2510
2511 $wgOut->addHTML( $this->editFormTextBeforeContent );
2512
2513 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2514 $wgOut->addHTML( EditPage::getEditToolbar() );
2515 }
2516
2517 if ( $this->blankArticle ) {
2518 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2519 }
2520
2521 if ( $this->isConflict ) {
2522 // In an edit conflict bypass the overridable content form method
2523 // and fallback to the raw wpTextbox1 since editconflicts can't be
2524 // resolved between page source edits and custom ui edits using the
2525 // custom edit ui.
2526 $this->textbox2 = $this->textbox1;
2527
2528 $content = $this->getCurrentContent();
2529 $this->textbox1 = $this->toEditText( $content );
2530
2531 $this->showTextbox1();
2532 } else {
2533 $this->showContentForm();
2534 }
2535
2536 $wgOut->addHTML( $this->editFormTextAfterContent );
2537
2538 $this->showStandardInputs();
2539
2540 $this->showFormAfterText();
2541
2542 $this->showTosSummary();
2543
2544 $this->showEditTools();
2545
2546 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2547
2548 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2549 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
2550
2551 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
2552 Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
2553
2554 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'limitreport' ),
2555 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2556
2557 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2558
2559 if ( $this->isConflict ) {
2560 try {
2561 $this->showConflict();
2562 } catch ( MWContentSerializationException $ex ) {
2563 // this can't really happen, but be nice if it does.
2564 $msg = wfMessage(
2565 'content-failed-to-parse',
2566 $this->contentModel,
2567 $this->contentFormat,
2568 $ex->getMessage()
2569 );
2570 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2571 }
2572 }
2573
2574 // Marker for detecting truncated form data. This must be the last
2575 // parameter sent in order to be of use, so do not move me.
2576 $wgOut->addHTML( Html::hidden( 'wpUltimateParam', true ) );
2577 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2578
2579 if ( !$wgUser->getOption( 'previewontop' ) ) {
2580 $this->displayPreviewArea( $previewOutput, false );
2581 }
2582
2583 }
2584
2585 /**
2586 * Extract the section title from current section text, if any.
2587 *
2588 * @param string $text
2589 * @return string|bool String or false
2590 */
2591 public static function extractSectionTitle( $text ) {
2592 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2593 if ( !empty( $matches[2] ) ) {
2594 global $wgParser;
2595 return $wgParser->stripSectionName( trim( $matches[2] ) );
2596 } else {
2597 return false;
2598 }
2599 }
2600
2601 /**
2602 * @return bool
2603 */
2604 protected function showHeader() {
2605 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2606 global $wgAllowUserCss, $wgAllowUserJs;
2607
2608 if ( $this->mTitle->isTalkPage() ) {
2609 $wgOut->addWikiMsg( 'talkpagetext' );
2610 }
2611
2612 // Add edit notices
2613 $editNotices = $this->mTitle->getEditNotices( $this->oldid );
2614 if ( count( $editNotices ) ) {
2615 $wgOut->addHTML( implode( "\n", $editNotices ) );
2616 } else {
2617 $msg = wfMessage( 'editnotice-notext' );
2618 if ( !$msg->isDisabled() ) {
2619 $wgOut->addHTML(
2620 '<div class="mw-editnotice-notext">'
2621 . $msg->parseAsBlock()
2622 . '</div>'
2623 );
2624 }
2625 }
2626
2627 if ( $this->isConflict ) {
2628 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2629 $this->edittime = $this->mArticle->getTimestamp();
2630 } else {
2631 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
2632 // We use $this->section to much before this and getVal('wgSection') directly in other places
2633 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2634 // Someone is welcome to try refactoring though
2635 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2636 return false;
2637 }
2638
2639 if ( $this->section != '' && $this->section != 'new' ) {
2640 if ( !$this->summary && !$this->preview && !$this->diff ) {
2641 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); //FIXME: use Content object
2642 if ( $sectionTitle !== false ) {
2643 $this->summary = "/* $sectionTitle */ ";
2644 }
2645 }
2646 }
2647
2648 if ( $this->missingComment ) {
2649 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2650 }
2651
2652 if ( $this->missingSummary && $this->section != 'new' ) {
2653 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2654 }
2655
2656 if ( $this->missingSummary && $this->section == 'new' ) {
2657 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2658 }
2659
2660 if ( $this->blankArticle ) {
2661 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2662 }
2663
2664 if ( $this->selfRedirect ) {
2665 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2666 }
2667
2668 if ( $this->hookError !== '' ) {
2669 $wgOut->addWikiText( $this->hookError );
2670 }
2671
2672 if ( !$this->checkUnicodeCompliantBrowser() ) {
2673 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2674 }
2675
2676 if ( $this->section != 'new' ) {
2677 $revision = $this->mArticle->getRevisionFetched();
2678 if ( $revision ) {
2679 // Let sysop know that this will make private content public if saved
2680
2681 if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2682 $wgOut->wrapWikiMsg(
2683 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2684 'rev-deleted-text-permission'
2685 );
2686 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2687 $wgOut->wrapWikiMsg(
2688 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2689 'rev-deleted-text-view'
2690 );
2691 }
2692
2693 if ( !$revision->isCurrent() ) {
2694 $this->mArticle->setOldSubtitle( $revision->getId() );
2695 $wgOut->addWikiMsg( 'editingold' );
2696 }
2697 } elseif ( $this->mTitle->exists() ) {
2698 // Something went wrong
2699
2700 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2701 array( 'missing-revision', $this->oldid ) );
2702 }
2703 }
2704 }
2705
2706 if ( wfReadOnly() ) {
2707 $wgOut->wrapWikiMsg(
2708 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2709 array( 'readonlywarning', wfReadOnlyReason() )
2710 );
2711 } elseif ( $wgUser->isAnon() ) {
2712 if ( $this->formtype != 'preview' ) {
2713 $wgOut->wrapWikiMsg(
2714 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2715 array( 'anoneditwarning',
2716 // Log-in link
2717 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2718 // Sign-up link
2719 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2720 );
2721 } else {
2722 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2723 'anonpreviewwarning'
2724 );
2725 }
2726 } else {
2727 if ( $this->isCssJsSubpage ) {
2728 # Check the skin exists
2729 if ( $this->isWrongCaseCssJsPage ) {
2730 $wgOut->wrapWikiMsg(
2731 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2732 array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() )
2733 );
2734 }
2735 if ( $this->getTitle()->isSubpageOf( $wgUser->getUserPage() ) ) {
2736 if ( $this->formtype !== 'preview' ) {
2737 if ( $this->isCssSubpage && $wgAllowUserCss ) {
2738 $wgOut->wrapWikiMsg(
2739 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2740 array( 'usercssyoucanpreview' )
2741 );
2742 }
2743
2744 if ( $this->isJsSubpage && $wgAllowUserJs ) {
2745 $wgOut->wrapWikiMsg(
2746 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2747 array( 'userjsyoucanpreview' )
2748 );
2749 }
2750 }
2751 }
2752 }
2753 }
2754
2755 if ( $this->mTitle->isProtected( 'edit' ) &&
2756 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2757 ) {
2758 # Is the title semi-protected?
2759 if ( $this->mTitle->isSemiProtected() ) {
2760 $noticeMsg = 'semiprotectedpagewarning';
2761 } else {
2762 # Then it must be protected based on static groups (regular)
2763 $noticeMsg = 'protectedpagewarning';
2764 }
2765 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2766 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2767 }
2768 if ( $this->mTitle->isCascadeProtected() ) {
2769 # Is this page under cascading protection from some source pages?
2770 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2771 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2772 $cascadeSourcesCount = count( $cascadeSources );
2773 if ( $cascadeSourcesCount > 0 ) {
2774 # Explain, and list the titles responsible
2775 foreach ( $cascadeSources as $page ) {
2776 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2777 }
2778 }
2779 $notice .= '</div>';
2780 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2781 }
2782 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2783 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2784 array( 'lim' => 1,
2785 'showIfEmpty' => false,
2786 'msgKey' => array( 'titleprotectedwarning' ),
2787 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2788 }
2789
2790 if ( $this->kblength === false ) {
2791 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2792 }
2793
2794 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2795 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2796 array(
2797 'longpageerror',
2798 $wgLang->formatNum( $this->kblength ),
2799 $wgLang->formatNum( $wgMaxArticleSize )
2800 )
2801 );
2802 } else {
2803 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2804 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2805 array(
2806 'longpage-hint',
2807 $wgLang->formatSize( strlen( $this->textbox1 ) ),
2808 strlen( $this->textbox1 )
2809 )
2810 );
2811 }
2812 }
2813 # Add header copyright warning
2814 $this->showHeaderCopyrightWarning();
2815
2816 return true;
2817 }
2818
2819 /**
2820 * Standard summary input and label (wgSummary), abstracted so EditPage
2821 * subclasses may reorganize the form.
2822 * Note that you do not need to worry about the label's for=, it will be
2823 * inferred by the id given to the input. You can remove them both by
2824 * passing array( 'id' => false ) to $userInputAttrs.
2825 *
2826 * @param string $summary The value of the summary input
2827 * @param string $labelText The html to place inside the label
2828 * @param array $inputAttrs Array of attrs to use on the input
2829 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2830 *
2831 * @return array An array in the format array( $label, $input )
2832 */
2833 function getSummaryInput( $summary = "", $labelText = null,
2834 $inputAttrs = null, $spanLabelAttrs = null
2835 ) {
2836 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2837 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2838 'id' => 'wpSummary',
2839 'maxlength' => '200',
2840 'tabindex' => '1',
2841 'size' => 60,
2842 'spellcheck' => 'true',
2843 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2844
2845 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2846 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2847 'id' => "wpSummaryLabel"
2848 );
2849
2850 $label = null;
2851 if ( $labelText ) {
2852 $label = Xml::tags(
2853 'label',
2854 $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null,
2855 $labelText
2856 );
2857 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2858 }
2859
2860 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2861
2862 return array( $label, $input );
2863 }
2864
2865 /**
2866 * @param bool $isSubjectPreview True if this is the section subject/title
2867 * up top, or false if this is the comment summary
2868 * down below the textarea
2869 * @param string $summary The text of the summary to display
2870 */
2871 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2872 global $wgOut, $wgContLang;
2873 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2874 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2875 if ( $isSubjectPreview ) {
2876 if ( $this->nosummary ) {
2877 return;
2878 }
2879 } else {
2880 if ( !$this->mShowSummaryField ) {
2881 return;
2882 }
2883 }
2884 $summary = $wgContLang->recodeForEdit( $summary );
2885 $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
2886 list( $label, $input ) = $this->getSummaryInput(
2887 $summary,
2888 $labelText,
2889 array( 'class' => $summaryClass ),
2890 array()
2891 );
2892 $wgOut->addHTML( "{$label} {$input}" );
2893 }
2894
2895 /**
2896 * @param bool $isSubjectPreview True if this is the section subject/title
2897 * up top, or false if this is the comment summary
2898 * down below the textarea
2899 * @param string $summary The text of the summary to display
2900 * @return string
2901 */
2902 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2903 // avoid spaces in preview, gets always trimmed on save
2904 $summary = trim( $summary );
2905 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
2906 return "";
2907 }
2908
2909 global $wgParser;
2910
2911 if ( $isSubjectPreview ) {
2912 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2913 ->inContentLanguage()->text();
2914 }
2915
2916 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
2917
2918 $summary = wfMessage( $message )->parse()
2919 . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
2920 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2921 }
2922
2923 protected function showFormBeforeText() {
2924 global $wgOut;
2925 $section = htmlspecialchars( $this->section );
2926 $wgOut->addHTML( <<<HTML
2927 <input type='hidden' value="{$section}" name="wpSection"/>
2928 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2929 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2930 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2931
2932 HTML
2933 );
2934 if ( !$this->checkUnicodeCompliantBrowser() ) {
2935 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
2936 }
2937 }
2938
2939 protected function showFormAfterText() {
2940 global $wgOut, $wgUser;
2941 /**
2942 * To make it harder for someone to slip a user a page
2943 * which submits an edit form to the wiki without their
2944 * knowledge, a random token is associated with the login
2945 * session. If it's not passed back with the submission,
2946 * we won't save the page, or render user JavaScript and
2947 * CSS previews.
2948 *
2949 * For anon editors, who may not have a session, we just
2950 * include the constant suffix to prevent editing from
2951 * broken text-mangling proxies.
2952 */
2953 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2954 }
2955
2956 /**
2957 * Subpage overridable method for printing the form for page content editing
2958 * By default this simply outputs wpTextbox1
2959 * Subclasses can override this to provide a custom UI for editing;
2960 * be it a form, or simply wpTextbox1 with a modified content that will be
2961 * reverse modified when extracted from the post data.
2962 * Note that this is basically the inverse for importContentFormData
2963 */
2964 protected function showContentForm() {
2965 $this->showTextbox1();
2966 }
2967
2968 /**
2969 * Method to output wpTextbox1
2970 * The $textoverride method can be used by subclasses overriding showContentForm
2971 * to pass back to this method.
2972 *
2973 * @param array $customAttribs Array of html attributes to use in the textarea
2974 * @param string $textoverride Optional text to override $this->textarea1 with
2975 */
2976 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2977 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2978 $attribs = array( 'style' => 'display:none;' );
2979 } else {
2980 $classes = array(); // Textarea CSS
2981 if ( $this->mTitle->isProtected( 'edit' ) &&
2982 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2983 ) {
2984 # Is the title semi-protected?
2985 if ( $this->mTitle->isSemiProtected() ) {
2986 $classes[] = 'mw-textarea-sprotected';
2987 } else {
2988 # Then it must be protected based on static groups (regular)
2989 $classes[] = 'mw-textarea-protected';
2990 }
2991 # Is the title cascade-protected?
2992 if ( $this->mTitle->isCascadeProtected() ) {
2993 $classes[] = 'mw-textarea-cprotected';
2994 }
2995 }
2996
2997 $attribs = array( 'tabindex' => 1 );
2998
2999 if ( is_array( $customAttribs ) ) {
3000 $attribs += $customAttribs;
3001 }
3002
3003 if ( count( $classes ) ) {
3004 if ( isset( $attribs['class'] ) ) {
3005 $classes[] = $attribs['class'];
3006 }
3007 $attribs['class'] = implode( ' ', $classes );
3008 }
3009 }
3010
3011 $this->showTextbox(
3012 $textoverride !== null ? $textoverride : $this->textbox1,
3013 'wpTextbox1',
3014 $attribs
3015 );
3016 }
3017
3018 protected function showTextbox2() {
3019 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
3020 }
3021
3022 protected function showTextbox( $text, $name, $customAttribs = array() ) {
3023 global $wgOut, $wgUser;
3024
3025 $wikitext = $this->safeUnicodeOutput( $text );
3026 if ( strval( $wikitext ) !== '' ) {
3027 // Ensure there's a newline at the end, otherwise adding lines
3028 // is awkward.
3029 // But don't add a newline if the ext is empty, or Firefox in XHTML
3030 // mode will show an extra newline. A bit annoying.
3031 $wikitext .= "\n";
3032 }
3033
3034 $attribs = $customAttribs + array(
3035 'accesskey' => ',',
3036 'id' => $name,
3037 'cols' => $wgUser->getIntOption( 'cols' ),
3038 'rows' => $wgUser->getIntOption( 'rows' ),
3039 // Avoid PHP notices when appending preferences
3040 // (appending allows customAttribs['style'] to still work).
3041 'style' => ''
3042 );
3043
3044 $pageLang = $this->mTitle->getPageLanguage();
3045 $attribs['lang'] = $pageLang->getHtmlCode();
3046 $attribs['dir'] = $pageLang->getDir();
3047
3048 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
3049 }
3050
3051 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
3052 global $wgOut;
3053 $classes = array();
3054 if ( $isOnTop ) {
3055 $classes[] = 'ontop';
3056 }
3057
3058 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
3059
3060 if ( $this->formtype != 'preview' ) {
3061 $attribs['style'] = 'display: none;';
3062 }
3063
3064 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
3065
3066 if ( $this->formtype == 'preview' ) {
3067 $this->showPreview( $previewOutput );
3068 } else {
3069 // Empty content container for LivePreview
3070 $pageViewLang = $this->mTitle->getPageViewLanguage();
3071 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3072 'class' => 'mw-content-' . $pageViewLang->getDir() );
3073 $wgOut->addHTML( Html::rawElement( 'div', $attribs ) );
3074 }
3075
3076 $wgOut->addHTML( '</div>' );
3077
3078 if ( $this->formtype == 'diff' ) {
3079 try {
3080 $this->showDiff();
3081 } catch ( MWContentSerializationException $ex ) {
3082 $msg = wfMessage(
3083 'content-failed-to-parse',
3084 $this->contentModel,
3085 $this->contentFormat,
3086 $ex->getMessage()
3087 );
3088 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3089 }
3090 }
3091 }
3092
3093 /**
3094 * Append preview output to $wgOut.
3095 * Includes category rendering if this is a category page.
3096 *
3097 * @param string $text The HTML to be output for the preview.
3098 */
3099 protected function showPreview( $text ) {
3100 global $wgOut;
3101 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3102 $this->mArticle->openShowCategory();
3103 }
3104 # This hook seems slightly odd here, but makes things more
3105 # consistent for extensions.
3106 Hooks::run( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3107 $wgOut->addHTML( $text );
3108 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3109 $this->mArticle->closeShowCategory();
3110 }
3111 }
3112
3113 /**
3114 * Get a diff between the current contents of the edit box and the
3115 * version of the page we're editing from.
3116 *
3117 * If this is a section edit, we'll replace the section as for final
3118 * save and then make a comparison.
3119 */
3120 function showDiff() {
3121 global $wgUser, $wgContLang, $wgOut;
3122
3123 $oldtitlemsg = 'currentrev';
3124 # if message does not exist, show diff against the preloaded default
3125 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3126 $oldtext = $this->mTitle->getDefaultMessageText();
3127 if ( $oldtext !== false ) {
3128 $oldtitlemsg = 'defaultmessagetext';
3129 $oldContent = $this->toEditContent( $oldtext );
3130 } else {
3131 $oldContent = null;
3132 }
3133 } else {
3134 $oldContent = $this->getCurrentContent();
3135 }
3136
3137 $textboxContent = $this->toEditContent( $this->textbox1 );
3138
3139 $newContent = $this->mArticle->replaceSectionContent(
3140 $this->section, $textboxContent,
3141 $this->summary, $this->edittime );
3142
3143 if ( $newContent ) {
3144 ContentHandler::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3145 Hooks::run( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3146
3147 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
3148 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
3149 }
3150
3151 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3152 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3153 $newtitle = wfMessage( 'yourtext' )->parse();
3154
3155 if ( !$oldContent ) {
3156 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3157 }
3158
3159 if ( !$newContent ) {
3160 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3161 }
3162
3163 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
3164 $de->setContent( $oldContent, $newContent );
3165
3166 $difftext = $de->getDiff( $oldtitle, $newtitle );
3167 $de->showDiffStyle();
3168 } else {
3169 $difftext = '';
3170 }
3171
3172 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3173 }
3174
3175 /**
3176 * Show the header copyright warning.
3177 */
3178 protected function showHeaderCopyrightWarning() {
3179 $msg = 'editpage-head-copy-warn';
3180 if ( !wfMessage( $msg )->isDisabled() ) {
3181 global $wgOut;
3182 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3183 'editpage-head-copy-warn' );
3184 }
3185 }
3186
3187 /**
3188 * Give a chance for site and per-namespace customizations of
3189 * terms of service summary link that might exist separately
3190 * from the copyright notice.
3191 *
3192 * This will display between the save button and the edit tools,
3193 * so should remain short!
3194 */
3195 protected function showTosSummary() {
3196 $msg = 'editpage-tos-summary';
3197 Hooks::run( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
3198 if ( !wfMessage( $msg )->isDisabled() ) {
3199 global $wgOut;
3200 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3201 $wgOut->addWikiMsg( $msg );
3202 $wgOut->addHTML( '</div>' );
3203 }
3204 }
3205
3206 protected function showEditTools() {
3207 global $wgOut;
3208 $wgOut->addHTML( '<div class="mw-editTools">' .
3209 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3210 '</div>' );
3211 }
3212
3213 /**
3214 * Get the copyright warning
3215 *
3216 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3217 * @return string
3218 */
3219 protected function getCopywarn() {
3220 return self::getCopyrightWarning( $this->mTitle );
3221 }
3222
3223 /**
3224 * Get the copyright warning, by default returns wikitext
3225 *
3226 * @param Title $title
3227 * @param string $format Output format, valid values are any function of a Message object
3228 * @return string
3229 */
3230 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3231 global $wgRightsText;
3232 if ( $wgRightsText ) {
3233 $copywarnMsg = array( 'copyrightwarning',
3234 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3235 $wgRightsText );
3236 } else {
3237 $copywarnMsg = array( 'copyrightwarning2',
3238 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3239 }
3240 // Allow for site and per-namespace customization of contribution/copyright notice.
3241 Hooks::run( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3242
3243 return "<div id=\"editpage-copywarn\">\n" .
3244 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3245 }
3246
3247 /**
3248 * Get the Limit report for page previews
3249 *
3250 * @since 1.22
3251 * @param ParserOutput $output ParserOutput object from the parse
3252 * @return string HTML
3253 */
3254 public static function getPreviewLimitReport( $output ) {
3255 if ( !$output || !$output->getLimitReportData() ) {
3256 return '';
3257 }
3258
3259 $limitReport = Html::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3260 wfMessage( 'limitreport-title' )->parseAsBlock()
3261 );
3262
3263 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3264 $limitReport .= Html::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3265
3266 $limitReport .= Html::openElement( 'table', array(
3267 'class' => 'preview-limit-report wikitable'
3268 ) ) .
3269 Html::openElement( 'tbody' );
3270
3271 foreach ( $output->getLimitReportData() as $key => $value ) {
3272 if ( Hooks::run( 'ParserLimitReportFormat',
3273 array( $key, &$value, &$limitReport, true, true )
3274 ) ) {
3275 $keyMsg = wfMessage( $key );
3276 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3277 if ( !$valueMsg->exists() ) {
3278 $valueMsg = new RawMessage( '$1' );
3279 }
3280 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3281 $limitReport .= Html::openElement( 'tr' ) .
3282 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3283 Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3284 Html::closeElement( 'tr' );
3285 }
3286 }
3287 }
3288
3289 $limitReport .= Html::closeElement( 'tbody' ) .
3290 Html::closeElement( 'table' ) .
3291 Html::closeElement( 'div' );
3292
3293 return $limitReport;
3294 }
3295
3296 protected function showStandardInputs( &$tabindex = 2 ) {
3297 global $wgOut;
3298 $wgOut->addHTML( "<div class='editOptions'>\n" );
3299
3300 if ( $this->section != 'new' ) {
3301 $this->showSummaryInput( false, $this->summary );
3302 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3303 }
3304
3305 $checkboxes = $this->getCheckboxes( $tabindex,
3306 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
3307 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3308
3309 // Show copyright warning.
3310 $wgOut->addWikiText( $this->getCopywarn() );
3311 $wgOut->addHTML( $this->editFormTextAfterWarn );
3312
3313 $wgOut->addHTML( "<div class='editButtons'>\n" );
3314 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3315
3316 $cancel = $this->getCancelLink();
3317 if ( $cancel !== '' ) {
3318 $cancel .= Html::element( 'span',
3319 array( 'class' => 'mw-editButtons-pipe-separator' ),
3320 wfMessage( 'pipe-separator' )->text() );
3321 }
3322
3323 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3324 $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3325 $attrs = array(
3326 'target' => 'helpwindow',
3327 'href' => $edithelpurl,
3328 );
3329 $edithelp = Html::linkButton( wfMessage( 'edithelp' )->text(),
3330 $attrs, array( 'mw-ui-quiet' ) ) .
3331 wfMessage( 'word-separator' )->escaped() .
3332 wfMessage( 'newwindow' )->parse();
3333
3334 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3335 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3336 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3337
3338 Hooks::run( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3339
3340 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3341 }
3342
3343 /**
3344 * Show an edit conflict. textbox1 is already shown in showEditForm().
3345 * If you want to use another entry point to this function, be careful.
3346 */
3347 protected function showConflict() {
3348 global $wgOut;
3349
3350 if ( Hooks::run( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3351 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3352
3353 $content1 = $this->toEditContent( $this->textbox1 );
3354 $content2 = $this->toEditContent( $this->textbox2 );
3355
3356 $handler = ContentHandler::getForModelID( $this->contentModel );
3357 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3358 $de->setContent( $content2, $content1 );
3359 $de->showDiff(
3360 wfMessage( 'yourtext' )->parse(),
3361 wfMessage( 'storedversion' )->text()
3362 );
3363
3364 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3365 $this->showTextbox2();
3366 }
3367 }
3368
3369 /**
3370 * @return string
3371 */
3372 public function getCancelLink() {
3373 $cancelParams = array();
3374 if ( !$this->isConflict && $this->oldid > 0 ) {
3375 $cancelParams['oldid'] = $this->oldid;
3376 }
3377 $attrs = array( 'id' => 'mw-editform-cancel' );
3378
3379 return Linker::linkKnown(
3380 $this->getContextTitle(),
3381 wfMessage( 'cancel' )->parse(),
3382 Html::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ),
3383 $cancelParams
3384 );
3385 }
3386
3387 /**
3388 * Returns the URL to use in the form's action attribute.
3389 * This is used by EditPage subclasses when simply customizing the action
3390 * variable in the constructor is not enough. This can be used when the
3391 * EditPage lives inside of a Special page rather than a custom page action.
3392 *
3393 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3394 * @return string
3395 */
3396 protected function getActionURL( Title $title ) {
3397 return $title->getLocalURL( array( 'action' => $this->action ) );
3398 }
3399
3400 /**
3401 * Check if a page was deleted while the user was editing it, before submit.
3402 * Note that we rely on the logging table, which hasn't been always there,
3403 * but that doesn't matter, because this only applies to brand new
3404 * deletes.
3405 * @return bool
3406 */
3407 protected function wasDeletedSinceLastEdit() {
3408 if ( $this->deletedSinceEdit !== null ) {
3409 return $this->deletedSinceEdit;
3410 }
3411
3412 $this->deletedSinceEdit = false;
3413
3414 if ( $this->mTitle->isDeletedQuick() ) {
3415 $this->lastDelete = $this->getLastDelete();
3416 if ( $this->lastDelete ) {
3417 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3418 if ( $deleteTime > $this->starttime ) {
3419 $this->deletedSinceEdit = true;
3420 }
3421 }
3422 }
3423
3424 return $this->deletedSinceEdit;
3425 }
3426
3427 /**
3428 * @return bool|stdClass
3429 */
3430 protected function getLastDelete() {
3431 $dbr = wfGetDB( DB_SLAVE );
3432 $data = $dbr->selectRow(
3433 array( 'logging', 'user' ),
3434 array(
3435 'log_type',
3436 'log_action',
3437 'log_timestamp',
3438 'log_user',
3439 'log_namespace',
3440 'log_title',
3441 'log_comment',
3442 'log_params',
3443 'log_deleted',
3444 'user_name'
3445 ), array(
3446 'log_namespace' => $this->mTitle->getNamespace(),
3447 'log_title' => $this->mTitle->getDBkey(),
3448 'log_type' => 'delete',
3449 'log_action' => 'delete',
3450 'user_id=log_user'
3451 ),
3452 __METHOD__,
3453 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3454 );
3455 // Quick paranoid permission checks...
3456 if ( is_object( $data ) ) {
3457 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3458 $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
3459 }
3460
3461 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3462 $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
3463 }
3464 }
3465
3466 return $data;
3467 }
3468
3469 /**
3470 * Get the rendered text for previewing.
3471 * @throws MWException
3472 * @return string
3473 */
3474 function getPreviewText() {
3475 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3476 global $wgAllowUserCss, $wgAllowUserJs;
3477
3478 $stats = $wgOut->getContext()->getStats();
3479
3480 if ( $wgRawHtml && !$this->mTokenOk ) {
3481 // Could be an offsite preview attempt. This is very unsafe if
3482 // HTML is enabled, as it could be an attack.
3483 $parsedNote = '';
3484 if ( $this->textbox1 !== '' ) {
3485 // Do not put big scary notice, if previewing the empty
3486 // string, which happens when you initially edit
3487 // a category page, due to automatic preview-on-open.
3488 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3489 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3490 }
3491 $stats->increment( 'edit.failures.session_loss' );
3492 return $parsedNote;
3493 }
3494
3495 $note = '';
3496
3497 try {
3498 $content = $this->toEditContent( $this->textbox1 );
3499
3500 $previewHTML = '';
3501 if ( !Hooks::run(
3502 'AlternateEditPreview',
3503 array( $this, &$content, &$previewHTML, &$this->mParserOutput ) )
3504 ) {
3505 return $previewHTML;
3506 }
3507
3508 # provide a anchor link to the editform
3509 $continueEditing = '<span class="mw-continue-editing">' .
3510 '[[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' .
3511 wfMessage( 'continue-editing' )->text() . ']]</span>';
3512 if ( $this->mTriedSave && !$this->mTokenOk ) {
3513 if ( $this->mTokenOkExceptSuffix ) {
3514 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3515 $stats->increment( 'edit.failures.bad_token' );
3516 } else {
3517 $note = wfMessage( 'session_fail_preview' )->plain();
3518 $stats->increment( 'edit.failures.session_loss' );
3519 }
3520 } elseif ( $this->incompleteForm ) {
3521 $note = wfMessage( 'edit_form_incomplete' )->plain();
3522 if ( $this->mTriedSave ) {
3523 $stats->increment( 'edit.failures.incomplete_form' );
3524 }
3525 } else {
3526 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3527 }
3528
3529 $parserOptions = $this->mArticle->makeParserOptions( $this->mArticle->getContext() );
3530 $parserOptions->setIsPreview( true );
3531 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3532
3533 # don't parse non-wikitext pages, show message about preview
3534 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3535 if ( $this->mTitle->isCssJsSubpage() ) {
3536 $level = 'user';
3537 } elseif ( $this->mTitle->isCssOrJsPage() ) {
3538 $level = 'site';
3539 } else {
3540 $level = false;
3541 }
3542
3543 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3544 $format = 'css';
3545 if ( $level === 'user' && !$wgAllowUserCss ) {
3546 $format = false;
3547 }
3548 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3549 $format = 'js';
3550 if ( $level === 'user' && !$wgAllowUserJs ) {
3551 $format = false;
3552 }
3553 } else {
3554 $format = false;
3555 }
3556
3557 # Used messages to make sure grep find them:
3558 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3559 if ( $level && $format ) {
3560 $note = "<div id='mw-{$level}{$format}preview'>" .
3561 wfMessage( "{$level}{$format}preview" )->text() .
3562 ' ' . $continueEditing . "</div>";
3563 }
3564 }
3565
3566 # If we're adding a comment, we need to show the
3567 # summary as the headline
3568 if ( $this->section === "new" && $this->summary !== "" ) {
3569 $content = $content->addSectionHeader( $this->summary );
3570 }
3571
3572 $hook_args = array( $this, &$content );
3573 ContentHandler::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3574 Hooks::run( 'EditPageGetPreviewContent', $hook_args );
3575
3576 $parserOptions->enableLimitReport();
3577
3578 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3579 # But it's now deprecated, so never mind
3580
3581 $pstContent = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3582 $scopedCallback = $parserOptions->setupFakeRevision(
3583 $this->mTitle, $pstContent, $wgUser );
3584 $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
3585
3586 # Try to stash the edit for the final submission step
3587 # @todo: different date format preferences cause cache misses
3588 ApiStashEdit::stashEditFromPreview(
3589 $this->getArticle(), $content, $pstContent,
3590 $parserOutput, $parserOptions, $parserOptions, wfTimestampNow()
3591 );
3592
3593 $parserOutput->setEditSectionTokens( false ); // no section edit links
3594 $previewHTML = $parserOutput->getText();
3595 $this->mParserOutput = $parserOutput;
3596 $wgOut->addParserOutputMetadata( $parserOutput );
3597
3598 if ( count( $parserOutput->getWarnings() ) ) {
3599 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3600 }
3601 } catch ( MWContentSerializationException $ex ) {
3602 $m = wfMessage(
3603 'content-failed-to-parse',
3604 $this->contentModel,
3605 $this->contentFormat,
3606 $ex->getMessage()
3607 );
3608 $note .= "\n\n" . $m->parse();
3609 $previewHTML = '';
3610 }
3611
3612 if ( $this->isConflict ) {
3613 $conflict = '<h2 id="mw-previewconflict">'
3614 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3615 } else {
3616 $conflict = '<hr />';
3617 }
3618
3619 $previewhead = "<div class='previewnote'>\n" .
3620 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3621 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3622
3623 $pageViewLang = $this->mTitle->getPageViewLanguage();
3624 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3625 'class' => 'mw-content-' . $pageViewLang->getDir() );
3626 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3627
3628 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3629 }
3630
3631 /**
3632 * @return array
3633 */
3634 function getTemplates() {
3635 if ( $this->preview || $this->section != '' ) {
3636 $templates = array();
3637 if ( !isset( $this->mParserOutput ) ) {
3638 return $templates;
3639 }
3640 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3641 foreach ( array_keys( $template ) as $dbk ) {
3642 $templates[] = Title::makeTitle( $ns, $dbk );
3643 }
3644 }
3645 return $templates;
3646 } else {
3647 return $this->mTitle->getTemplateLinksFrom();
3648 }
3649 }
3650
3651 /**
3652 * Shows a bulletin board style toolbar for common editing functions.
3653 * It can be disabled in the user preferences.
3654 *
3655 * @return string
3656 */
3657 static function getEditToolbar() {
3658 global $wgContLang, $wgOut;
3659 global $wgEnableUploads, $wgForeignFileRepos;
3660
3661 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3662
3663 /**
3664 * $toolarray is an array of arrays each of which includes the
3665 * opening tag, the closing tag, optionally a sample text that is
3666 * inserted between the two when no selection is highlighted
3667 * and. The tip text is shown when the user moves the mouse
3668 * over the button.
3669 *
3670 * Images are defined in ResourceLoaderEditToolbarModule.
3671 */
3672 $toolarray = array(
3673 array(
3674 'id' => 'mw-editbutton-bold',
3675 'open' => '\'\'\'',
3676 'close' => '\'\'\'',
3677 'sample' => wfMessage( 'bold_sample' )->text(),
3678 'tip' => wfMessage( 'bold_tip' )->text(),
3679 ),
3680 array(
3681 'id' => 'mw-editbutton-italic',
3682 'open' => '\'\'',
3683 'close' => '\'\'',
3684 'sample' => wfMessage( 'italic_sample' )->text(),
3685 'tip' => wfMessage( 'italic_tip' )->text(),
3686 ),
3687 array(
3688 'id' => 'mw-editbutton-link',
3689 'open' => '[[',
3690 'close' => ']]',
3691 'sample' => wfMessage( 'link_sample' )->text(),
3692 'tip' => wfMessage( 'link_tip' )->text(),
3693 ),
3694 array(
3695 'id' => 'mw-editbutton-extlink',
3696 'open' => '[',
3697 'close' => ']',
3698 'sample' => wfMessage( 'extlink_sample' )->text(),
3699 'tip' => wfMessage( 'extlink_tip' )->text(),
3700 ),
3701 array(
3702 'id' => 'mw-editbutton-headline',
3703 'open' => "\n== ",
3704 'close' => " ==\n",
3705 'sample' => wfMessage( 'headline_sample' )->text(),
3706 'tip' => wfMessage( 'headline_tip' )->text(),
3707 ),
3708 $imagesAvailable ? array(
3709 'id' => 'mw-editbutton-image',
3710 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3711 'close' => ']]',
3712 'sample' => wfMessage( 'image_sample' )->text(),
3713 'tip' => wfMessage( 'image_tip' )->text(),
3714 ) : false,
3715 $imagesAvailable ? array(
3716 'id' => 'mw-editbutton-media',
3717 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3718 'close' => ']]',
3719 'sample' => wfMessage( 'media_sample' )->text(),
3720 'tip' => wfMessage( 'media_tip' )->text(),
3721 ) : false,
3722 array(
3723 'id' => 'mw-editbutton-nowiki',
3724 'open' => "<nowiki>",
3725 'close' => "</nowiki>",
3726 'sample' => wfMessage( 'nowiki_sample' )->text(),
3727 'tip' => wfMessage( 'nowiki_tip' )->text(),
3728 ),
3729 array(
3730 'id' => 'mw-editbutton-signature',
3731 'open' => '--~~~~',
3732 'close' => '',
3733 'sample' => '',
3734 'tip' => wfMessage( 'sig_tip' )->text(),
3735 ),
3736 array(
3737 'id' => 'mw-editbutton-hr',
3738 'open' => "\n----\n",
3739 'close' => '',
3740 'sample' => '',
3741 'tip' => wfMessage( 'hr_tip' )->text(),
3742 )
3743 );
3744
3745 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3746 foreach ( $toolarray as $tool ) {
3747 if ( !$tool ) {
3748 continue;
3749 }
3750
3751 $params = array(
3752 // Images are defined in ResourceLoaderEditToolbarModule
3753 false,
3754 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3755 // Older browsers show a "speedtip" type message only for ALT.
3756 // Ideally these should be different, realistically they
3757 // probably don't need to be.
3758 $tool['tip'],
3759 $tool['open'],
3760 $tool['close'],
3761 $tool['sample'],
3762 $tool['id'],
3763 );
3764
3765 $script .= Xml::encodeJsCall(
3766 'mw.toolbar.addButton',
3767 $params,
3768 ResourceLoader::inDebugMode()
3769 );
3770 }
3771
3772 $script .= '});';
3773 $wgOut->addScript( ResourceLoader::makeInlineScript( $script ) );
3774
3775 $toolbar = '<div id="toolbar"></div>';
3776
3777 Hooks::run( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3778
3779 return $toolbar;
3780 }
3781
3782 /**
3783 * Returns an array of html code of the following checkboxes:
3784 * minor and watch
3785 *
3786 * @param int $tabindex Current tabindex
3787 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3788 * status of the checkbox
3789 *
3790 * @return array
3791 */
3792 public function getCheckboxes( &$tabindex, $checked ) {
3793 global $wgUser, $wgUseMediaWikiUIEverywhere;
3794
3795 $checkboxes = array();
3796
3797 // don't show the minor edit checkbox if it's a new page or section
3798 if ( !$this->isNew ) {
3799 $checkboxes['minor'] = '';
3800 $minorLabel = wfMessage( 'minoredit' )->parse();
3801 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3802 $attribs = array(
3803 'tabindex' => ++$tabindex,
3804 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3805 'id' => 'wpMinoredit',
3806 );
3807 $minorEditHtml =
3808 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3809 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
3810 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3811 ">{$minorLabel}</label>";
3812
3813 if ( $wgUseMediaWikiUIEverywhere ) {
3814 $checkboxes['minor'] = Html::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3815 $minorEditHtml .
3816 Html::closeElement( 'div' );
3817 } else {
3818 $checkboxes['minor'] = $minorEditHtml;
3819 }
3820 }
3821 }
3822
3823 $watchLabel = wfMessage( 'watchthis' )->parse();
3824 $checkboxes['watch'] = '';
3825 if ( $wgUser->isLoggedIn() ) {
3826 $attribs = array(
3827 'tabindex' => ++$tabindex,
3828 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3829 'id' => 'wpWatchthis',
3830 );
3831 $watchThisHtml =
3832 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3833 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
3834 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
3835 ">{$watchLabel}</label>";
3836 if ( $wgUseMediaWikiUIEverywhere ) {
3837 $checkboxes['watch'] = Html::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3838 $watchThisHtml .
3839 Html::closeElement( 'div' );
3840 } else {
3841 $checkboxes['watch'] = $watchThisHtml;
3842 }
3843 }
3844 Hooks::run( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3845 return $checkboxes;
3846 }
3847
3848 /**
3849 * Returns an array of html code of the following buttons:
3850 * save, diff, preview and live
3851 *
3852 * @param int $tabindex Current tabindex
3853 *
3854 * @return array
3855 */
3856 public function getEditButtons( &$tabindex ) {
3857 $buttons = array();
3858
3859 $attribs = array(
3860 'id' => 'wpSave',
3861 'name' => 'wpSave',
3862 'tabindex' => ++$tabindex,
3863 ) + Linker::tooltipAndAccesskeyAttribs( 'save' );
3864 $buttons['save'] = Html::submitButton( wfMessage( 'savearticle' )->text(),
3865 $attribs, array( 'mw-ui-constructive' ) );
3866
3867 ++$tabindex; // use the same for preview and live preview
3868 $attribs = array(
3869 'id' => 'wpPreview',
3870 'name' => 'wpPreview',
3871 'tabindex' => $tabindex,
3872 ) + Linker::tooltipAndAccesskeyAttribs( 'preview' );
3873 $buttons['preview'] = Html::submitButton( wfMessage( 'showpreview' )->text(),
3874 $attribs );
3875 $buttons['live'] = '';
3876
3877 $attribs = array(
3878 'id' => 'wpDiff',
3879 'name' => 'wpDiff',
3880 'tabindex' => ++$tabindex,
3881 ) + Linker::tooltipAndAccesskeyAttribs( 'diff' );
3882 $buttons['diff'] = Html::submitButton( wfMessage( 'showdiff' )->text(),
3883 $attribs );
3884
3885 Hooks::run( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3886 return $buttons;
3887 }
3888
3889 /**
3890 * Creates a basic error page which informs the user that
3891 * they have attempted to edit a nonexistent section.
3892 */
3893 function noSuchSectionPage() {
3894 global $wgOut;
3895
3896 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3897
3898 $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
3899 Hooks::run( 'EditPageNoSuchSection', array( &$this, &$res ) );
3900 $wgOut->addHTML( $res );
3901
3902 $wgOut->returnToMain( false, $this->mTitle );
3903 }
3904
3905 /**
3906 * Show "your edit contains spam" page with your diff and text
3907 *
3908 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
3909 */
3910 public function spamPageWithContent( $match = false ) {
3911 global $wgOut, $wgLang;
3912 $this->textbox2 = $this->textbox1;
3913
3914 if ( is_array( $match ) ) {
3915 $match = $wgLang->listToText( $match );
3916 }
3917 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3918
3919 $wgOut->addHTML( '<div id="spamprotected">' );
3920 $wgOut->addWikiMsg( 'spamprotectiontext' );
3921 if ( $match ) {
3922 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3923 }
3924 $wgOut->addHTML( '</div>' );
3925
3926 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3927 $this->showDiff();
3928
3929 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3930 $this->showTextbox2();
3931
3932 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3933 }
3934
3935 /**
3936 * Check if the browser is on a blacklist of user-agents known to
3937 * mangle UTF-8 data on form submission. Returns true if Unicode
3938 * should make it through, false if it's known to be a problem.
3939 * @return bool
3940 */
3941 private function checkUnicodeCompliantBrowser() {
3942 global $wgBrowserBlackList, $wgRequest;
3943
3944 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3945 if ( $currentbrowser === false ) {
3946 // No User-Agent header sent? Trust it by default...
3947 return true;
3948 }
3949
3950 foreach ( $wgBrowserBlackList as $browser ) {
3951 if ( preg_match( $browser, $currentbrowser ) ) {
3952 return false;
3953 }
3954 }
3955 return true;
3956 }
3957
3958 /**
3959 * Filter an input field through a Unicode de-armoring process if it
3960 * came from an old browser with known broken Unicode editing issues.
3961 *
3962 * @param WebRequest $request
3963 * @param string $field
3964 * @return string
3965 */
3966 protected function safeUnicodeInput( $request, $field ) {
3967 $text = rtrim( $request->getText( $field ) );
3968 return $request->getBool( 'safemode' )
3969 ? $this->unmakeSafe( $text )
3970 : $text;
3971 }
3972
3973 /**
3974 * Filter an output field through a Unicode armoring process if it is
3975 * going to an old browser with known broken Unicode editing issues.
3976 *
3977 * @param string $text
3978 * @return string
3979 */
3980 protected function safeUnicodeOutput( $text ) {
3981 global $wgContLang;
3982 $codedText = $wgContLang->recodeForEdit( $text );
3983 return $this->checkUnicodeCompliantBrowser()
3984 ? $codedText
3985 : $this->makeSafe( $codedText );
3986 }
3987
3988 /**
3989 * A number of web browsers are known to corrupt non-ASCII characters
3990 * in a UTF-8 text editing environment. To protect against this,
3991 * detected browsers will be served an armored version of the text,
3992 * with non-ASCII chars converted to numeric HTML character references.
3993 *
3994 * Preexisting such character references will have a 0 added to them
3995 * to ensure that round-trips do not alter the original data.
3996 *
3997 * @param string $invalue
3998 * @return string
3999 */
4000 private function makeSafe( $invalue ) {
4001 // Armor existing references for reversibility.
4002 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
4003
4004 $bytesleft = 0;
4005 $result = "";
4006 $working = 0;
4007 $valueLength = strlen( $invalue );
4008 for ( $i = 0; $i < $valueLength; $i++ ) {
4009 $bytevalue = ord( $invalue[$i] );
4010 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
4011 $result .= chr( $bytevalue );
4012 $bytesleft = 0;
4013 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
4014 $working = $working << 6;
4015 $working += ( $bytevalue & 0x3F );
4016 $bytesleft--;
4017 if ( $bytesleft <= 0 ) {
4018 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
4019 }
4020 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
4021 $working = $bytevalue & 0x1F;
4022 $bytesleft = 1;
4023 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
4024 $working = $bytevalue & 0x0F;
4025 $bytesleft = 2;
4026 } else { // 1111 0xxx
4027 $working = $bytevalue & 0x07;
4028 $bytesleft = 3;
4029 }
4030 }
4031 return $result;
4032 }
4033
4034 /**
4035 * Reverse the previously applied transliteration of non-ASCII characters
4036 * back to UTF-8. Used to protect data from corruption by broken web browsers
4037 * as listed in $wgBrowserBlackList.
4038 *
4039 * @param string $invalue
4040 * @return string
4041 */
4042 private function unmakeSafe( $invalue ) {
4043 $result = "";
4044 $valueLength = strlen( $invalue );
4045 for ( $i = 0; $i < $valueLength; $i++ ) {
4046 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
4047 $i += 3;
4048 $hexstring = "";
4049 do {
4050 $hexstring .= $invalue[$i];
4051 $i++;
4052 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4053
4054 // Do some sanity checks. These aren't needed for reversibility,
4055 // but should help keep the breakage down if the editor
4056 // breaks one of the entities whilst editing.
4057 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4058 $codepoint = hexdec( $hexstring );
4059 $result .= UtfNormal\Utils::codepointToUtf8( $codepoint );
4060 } else {
4061 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4062 }
4063 } else {
4064 $result .= substr( $invalue, $i, 1 );
4065 }
4066 }
4067 // reverse the transform that we made for reversibility reasons.
4068 return strtr( $result, array( "&#x0" => "&#x" ) );
4069 }
4070 }