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