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