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