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