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