Merge "mediawiki.helplink: Use a SVG+PNG icon"
[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 }
2102
2103 /**
2104 * Show all applicable editing introductions
2105 */
2106 protected function showIntro() {
2107 global $wgOut, $wgUser;
2108 if ( $this->suppressIntro ) {
2109 return;
2110 }
2111
2112 $namespace = $this->mTitle->getNamespace();
2113
2114 if ( $namespace == NS_MEDIAWIKI ) {
2115 # Show a warning if editing an interface message
2116 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2117 # If this is a default message (but not css or js),
2118 # show a hint that it is translatable on translatewiki.net
2119 if ( !$this->mTitle->hasContentModel( CONTENT_MODEL_CSS )
2120 && !$this->mTitle->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
2121 ) {
2122 $defaultMessageText = $this->mTitle->getDefaultMessageText();
2123 if ( $defaultMessageText !== false ) {
2124 $wgOut->wrapWikiMsg( "<div class='mw-translateinterface'>\n$1\n</div>",
2125 'translateinterface' );
2126 }
2127 }
2128 } elseif ( $namespace == NS_FILE ) {
2129 # Show a hint to shared repo
2130 $file = wfFindFile( $this->mTitle );
2131 if ( $file && !$file->isLocal() ) {
2132 $descUrl = $file->getDescriptionUrl();
2133 # there must be a description url to show a hint to shared repo
2134 if ( $descUrl ) {
2135 if ( !$this->mTitle->exists() ) {
2136 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2137 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2138 ) );
2139 } else {
2140 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2141 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2142 ) );
2143 }
2144 }
2145 }
2146 }
2147
2148 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2149 # Show log extract when the user is currently blocked
2150 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2151 $parts = explode( '/', $this->mTitle->getText(), 2 );
2152 $username = $parts[0];
2153 $user = User::newFromName( $username, false /* allow IP users*/ );
2154 $ip = User::isIP( $username );
2155 $block = Block::newFromTarget( $user, $user );
2156 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2157 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2158 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2159 } elseif ( !is_null( $block ) && $block->getType() != Block::TYPE_AUTO ) {
2160 # Show log extract if the user is currently blocked
2161 LogEventsList::showLogExtract(
2162 $wgOut,
2163 'block',
2164 MWNamespace::getCanonicalName( NS_USER ) . ':' . $block->getTarget(),
2165 '',
2166 array(
2167 'lim' => 1,
2168 'showIfEmpty' => false,
2169 'msgKey' => array(
2170 'blocked-notice-logextract',
2171 $user->getName() # Support GENDER in notice
2172 )
2173 )
2174 );
2175 }
2176 }
2177 # Try to add a custom edit intro, or use the standard one if this is not possible.
2178 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2179 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2180 wfMessage( 'helppage' )->inContentLanguage()->text()
2181 ) );
2182 if ( $wgUser->isLoggedIn() ) {
2183 $wgOut->wrapWikiMsg(
2184 // Suppress the external link icon, consider the help url an internal one
2185 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2186 array(
2187 'newarticletext',
2188 $helpLink
2189 )
2190 );
2191 } else {
2192 $wgOut->wrapWikiMsg(
2193 // Suppress the external link icon, consider the help url an internal one
2194 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2195 array(
2196 'newarticletextanon',
2197 $helpLink
2198 )
2199 );
2200 }
2201 }
2202 # Give a notice if the user is editing a deleted/moved page...
2203 if ( !$this->mTitle->exists() ) {
2204 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
2205 '',
2206 array(
2207 'lim' => 10,
2208 'conds' => array( "log_action != 'revision'" ),
2209 'showIfEmpty' => false,
2210 'msgKey' => array( 'recreate-moveddeleted-warn' )
2211 )
2212 );
2213 }
2214 }
2215
2216 /**
2217 * Attempt to show a custom editing introduction, if supplied
2218 *
2219 * @return bool
2220 */
2221 protected function showCustomIntro() {
2222 if ( $this->editintro ) {
2223 $title = Title::newFromText( $this->editintro );
2224 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2225 global $wgOut;
2226 // Added using template syntax, to take <noinclude>'s into account.
2227 $wgOut->addWikiTextTitleTidy(
2228 '<div class="mw-editintro">{{:' . $title->getFullText() . '}}</div>',
2229 $this->mTitle
2230 );
2231 return true;
2232 }
2233 }
2234 return false;
2235 }
2236
2237 /**
2238 * Gets an editable textual representation of $content.
2239 * The textual representation can be turned by into a Content object by the
2240 * toEditContent() method.
2241 *
2242 * If $content is null or false or a string, $content is returned unchanged.
2243 *
2244 * If the given Content object is not of a type that can be edited using
2245 * the text base EditPage, an exception will be raised. Set
2246 * $this->allowNonTextContent to true to allow editing of non-textual
2247 * content.
2248 *
2249 * @param Content|null|bool|string $content
2250 * @return string The editable text form of the content.
2251 *
2252 * @throws MWException If $content is not an instance of TextContent and
2253 * $this->allowNonTextContent is not true.
2254 */
2255 protected function toEditText( $content ) {
2256 if ( $content === null || $content === false || is_string( $content ) ) {
2257 return $content;
2258 }
2259
2260 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2261 throw new MWException( 'This content model is not supported: '
2262 . ContentHandler::getLocalizedName( $content->getModel() ) );
2263 }
2264
2265 return $content->serialize( $this->contentFormat );
2266 }
2267
2268 /**
2269 * Turns the given text into a Content object by unserializing it.
2270 *
2271 * If the resulting Content object is not of a type that can be edited using
2272 * the text base EditPage, an exception will be raised. Set
2273 * $this->allowNonTextContent to true to allow editing of non-textual
2274 * content.
2275 *
2276 * @param string|null|bool $text Text to unserialize
2277 * @return Content The content object created from $text. If $text was false
2278 * or null, false resp. null will be returned instead.
2279 *
2280 * @throws MWException If unserializing the text results in a Content
2281 * object that is not an instance of TextContent and
2282 * $this->allowNonTextContent is not true.
2283 */
2284 protected function toEditContent( $text ) {
2285 if ( $text === false || $text === null ) {
2286 return $text;
2287 }
2288
2289 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2290 $this->contentModel, $this->contentFormat );
2291
2292 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2293 throw new MWException( 'This content model is not supported: '
2294 . ContentHandler::getLocalizedName( $content->getModel() ) );
2295 }
2296
2297 return $content;
2298 }
2299
2300 /**
2301 * Send the edit form and related headers to $wgOut
2302 * @param callable|null $formCallback That takes an OutputPage parameter; will be called
2303 * during form output near the top, for captchas and the like.
2304 *
2305 * The $formCallback parameter is deprecated since MediaWiki 1.25. Please
2306 * use the EditPage::showEditForm:fields hook instead.
2307 */
2308 function showEditForm( $formCallback = null ) {
2309 global $wgOut, $wgUser;
2310
2311 # need to parse the preview early so that we know which templates are used,
2312 # otherwise users with "show preview after edit box" will get a blank list
2313 # we parse this near the beginning so that setHeaders can do the title
2314 # setting work instead of leaving it in getPreviewText
2315 $previewOutput = '';
2316 if ( $this->formtype == 'preview' ) {
2317 $previewOutput = $this->getPreviewText();
2318 }
2319
2320 Hooks::run( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2321
2322 $this->setHeaders();
2323
2324 if ( $this->showHeader() === false ) {
2325 return;
2326 }
2327
2328 $wgOut->addHTML( $this->editFormPageTop );
2329
2330 if ( $wgUser->getOption( 'previewontop' ) ) {
2331 $this->displayPreviewArea( $previewOutput, true );
2332 }
2333
2334 $wgOut->addHTML( $this->editFormTextTop );
2335
2336 $showToolbar = true;
2337 if ( $this->wasDeletedSinceLastEdit() ) {
2338 if ( $this->formtype == 'save' ) {
2339 // Hide the toolbar and edit area, user can click preview to get it back
2340 // Add an confirmation checkbox and explanation.
2341 $showToolbar = false;
2342 } else {
2343 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2344 'deletedwhileediting' );
2345 }
2346 }
2347
2348 // @todo add EditForm plugin interface and use it here!
2349 // search for textarea1 and textares2, and allow EditForm to override all uses.
2350 $wgOut->addHTML( Html::openElement(
2351 'form',
2352 array(
2353 'id' => self::EDITFORM_ID,
2354 'name' => self::EDITFORM_ID,
2355 'method' => 'post',
2356 'action' => $this->getActionURL( $this->getContextTitle() ),
2357 'enctype' => 'multipart/form-data'
2358 )
2359 ) );
2360
2361 if ( is_callable( $formCallback ) ) {
2362 wfWarn( 'The $formCallback parameter to ' . __METHOD__ . 'is deprecated' );
2363 call_user_func_array( $formCallback, array( &$wgOut ) );
2364 }
2365
2366 // Add an empty field to trip up spambots
2367 $wgOut->addHTML(
2368 Xml::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2369 . Html::rawElement(
2370 'label',
2371 array( 'for' => 'wpAntiSpam' ),
2372 wfMessage( 'simpleantispam-label' )->parse()
2373 )
2374 . Xml::element(
2375 'input',
2376 array(
2377 'type' => 'text',
2378 'name' => 'wpAntispam',
2379 'id' => 'wpAntispam',
2380 'value' => ''
2381 )
2382 )
2383 . Xml::closeElement( 'div' )
2384 );
2385
2386 Hooks::run( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2387
2388 // Put these up at the top to ensure they aren't lost on early form submission
2389 $this->showFormBeforeText();
2390
2391 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2392 $username = $this->lastDelete->user_name;
2393 $comment = $this->lastDelete->log_comment;
2394
2395 // It is better to not parse the comment at all than to have templates expanded in the middle
2396 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2397 $key = $comment === ''
2398 ? 'confirmrecreate-noreason'
2399 : 'confirmrecreate';
2400 $wgOut->addHTML(
2401 '<div class="mw-confirm-recreate">' .
2402 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2403 Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2404 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2405 ) .
2406 '</div>'
2407 );
2408 }
2409
2410 # When the summary is hidden, also hide them on preview/show changes
2411 if ( $this->nosummary ) {
2412 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2413 }
2414
2415 # If a blank edit summary was previously provided, and the appropriate
2416 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2417 # user being bounced back more than once in the event that a summary
2418 # is not required.
2419 #####
2420 # For a bit more sophisticated detection of blank summaries, hash the
2421 # automatic one and pass that in the hidden field wpAutoSummary.
2422 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2423 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2424 }
2425
2426 if ( $this->undidRev ) {
2427 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2428 }
2429
2430 if ( $this->selfRedirect ) {
2431 $wgOut->addHTML( Html::hidden( 'wpIgnoreSelfRedirect', true ) );
2432 }
2433
2434 if ( $this->hasPresetSummary ) {
2435 // If a summary has been preset using &summary= we don't want to prompt for
2436 // a different summary. Only prompt for a summary if the summary is blanked.
2437 // (Bug 17416)
2438 $this->autoSumm = md5( '' );
2439 }
2440
2441 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2442 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2443
2444 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2445 $wgOut->addHTML( Html::hidden( 'parentRevId',
2446 $this->parentRevId ?: $this->mArticle->getRevIdFetched() ) );
2447
2448 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2449 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2450
2451 if ( $this->section == 'new' ) {
2452 $this->showSummaryInput( true, $this->summary );
2453 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2454 }
2455
2456 $wgOut->addHTML( $this->editFormTextBeforeContent );
2457
2458 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2459 $wgOut->addHTML( EditPage::getEditToolbar() );
2460 }
2461
2462 if ( $this->blankArticle ) {
2463 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankArticle', true ) );
2464 }
2465
2466 if ( $this->isConflict ) {
2467 // In an edit conflict bypass the overridable content form method
2468 // and fallback to the raw wpTextbox1 since editconflicts can't be
2469 // resolved between page source edits and custom ui edits using the
2470 // custom edit ui.
2471 $this->textbox2 = $this->textbox1;
2472
2473 $content = $this->getCurrentContent();
2474 $this->textbox1 = $this->toEditText( $content );
2475
2476 $this->showTextbox1();
2477 } else {
2478 $this->showContentForm();
2479 }
2480
2481 $wgOut->addHTML( $this->editFormTextAfterContent );
2482
2483 $this->showStandardInputs();
2484
2485 $this->showFormAfterText();
2486
2487 $this->showTosSummary();
2488
2489 $this->showEditTools();
2490
2491 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2492
2493 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2494 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
2495
2496 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
2497 Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
2498
2499 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'limitreport' ),
2500 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2501
2502 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2503
2504 if ( $this->isConflict ) {
2505 try {
2506 $this->showConflict();
2507 } catch ( MWContentSerializationException $ex ) {
2508 // this can't really happen, but be nice if it does.
2509 $msg = wfMessage(
2510 'content-failed-to-parse',
2511 $this->contentModel,
2512 $this->contentFormat,
2513 $ex->getMessage()
2514 );
2515 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2516 }
2517 }
2518
2519 // Marker for detecting truncated form data. This must be the last
2520 // parameter sent in order to be of use, so do not move me.
2521 $wgOut->addHTML( Html::hidden( 'wpUltimateParam', true ) );
2522 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2523
2524 if ( !$wgUser->getOption( 'previewontop' ) ) {
2525 $this->displayPreviewArea( $previewOutput, false );
2526 }
2527
2528 }
2529
2530 /**
2531 * Extract the section title from current section text, if any.
2532 *
2533 * @param string $text
2534 * @return string|bool String or false
2535 */
2536 public static function extractSectionTitle( $text ) {
2537 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2538 if ( !empty( $matches[2] ) ) {
2539 global $wgParser;
2540 return $wgParser->stripSectionName( trim( $matches[2] ) );
2541 } else {
2542 return false;
2543 }
2544 }
2545
2546 /**
2547 * @return bool
2548 */
2549 protected function showHeader() {
2550 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2551 global $wgAllowUserCss, $wgAllowUserJs;
2552
2553 if ( $this->mTitle->isTalkPage() ) {
2554 $wgOut->addWikiMsg( 'talkpagetext' );
2555 }
2556
2557 // Add edit notices
2558 $editNotices = $this->mTitle->getEditNotices( $this->oldid );
2559 if ( count( $editNotices ) ) {
2560 $wgOut->addHTML( implode( "\n", $editNotices ) );
2561 } else {
2562 $msg = wfMessage( 'editnotice-notext' );
2563 if ( !$msg->isDisabled() ) {
2564 $wgOut->addHTML(
2565 '<div class="mw-editnotice-notext">'
2566 . $msg->parseAsBlock()
2567 . '</div>'
2568 );
2569 }
2570 }
2571
2572 if ( $this->isConflict ) {
2573 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2574 $this->edittime = $this->mArticle->getTimestamp();
2575 } else {
2576 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
2577 // We use $this->section to much before this and getVal('wgSection') directly in other places
2578 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2579 // Someone is welcome to try refactoring though
2580 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2581 return false;
2582 }
2583
2584 if ( $this->section != '' && $this->section != 'new' ) {
2585 if ( !$this->summary && !$this->preview && !$this->diff ) {
2586 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); //FIXME: use Content object
2587 if ( $sectionTitle !== false ) {
2588 $this->summary = "/* $sectionTitle */ ";
2589 }
2590 }
2591 }
2592
2593 if ( $this->missingComment ) {
2594 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2595 }
2596
2597 if ( $this->missingSummary && $this->section != 'new' ) {
2598 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2599 }
2600
2601 if ( $this->missingSummary && $this->section == 'new' ) {
2602 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2603 }
2604
2605 if ( $this->blankArticle ) {
2606 $wgOut->wrapWikiMsg( "<div id='mw-blankarticle'>\n$1\n</div>", 'blankarticle' );
2607 }
2608
2609 if ( $this->selfRedirect ) {
2610 $wgOut->wrapWikiMsg( "<div id='mw-selfredirect'>\n$1\n</div>", 'selfredirect' );
2611 }
2612
2613 if ( $this->hookError !== '' ) {
2614 $wgOut->addWikiText( $this->hookError );
2615 }
2616
2617 if ( !$this->checkUnicodeCompliantBrowser() ) {
2618 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2619 }
2620
2621 if ( $this->section != 'new' ) {
2622 $revision = $this->mArticle->getRevisionFetched();
2623 if ( $revision ) {
2624 // Let sysop know that this will make private content public if saved
2625
2626 if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2627 $wgOut->wrapWikiMsg(
2628 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2629 'rev-deleted-text-permission'
2630 );
2631 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2632 $wgOut->wrapWikiMsg(
2633 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
2634 'rev-deleted-text-view'
2635 );
2636 }
2637
2638 if ( !$revision->isCurrent() ) {
2639 $this->mArticle->setOldSubtitle( $revision->getId() );
2640 $wgOut->addWikiMsg( 'editingold' );
2641 }
2642 } elseif ( $this->mTitle->exists() ) {
2643 // Something went wrong
2644
2645 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2646 array( 'missing-revision', $this->oldid ) );
2647 }
2648 }
2649 }
2650
2651 if ( wfReadOnly() ) {
2652 $wgOut->wrapWikiMsg(
2653 "<div id=\"mw-read-only-warning\">\n$1\n</div>",
2654 array( 'readonlywarning', wfReadOnlyReason() )
2655 );
2656 } elseif ( $wgUser->isAnon() ) {
2657 if ( $this->formtype != 'preview' ) {
2658 $wgOut->wrapWikiMsg(
2659 "<div id='mw-anon-edit-warning'>\n$1\n</div>",
2660 array( 'anoneditwarning',
2661 // Log-in link
2662 '{{fullurl:Special:UserLogin|returnto={{FULLPAGENAMEE}}}}',
2663 // Sign-up link
2664 '{{fullurl:Special:UserLogin/signup|returnto={{FULLPAGENAMEE}}}}' )
2665 );
2666 } else {
2667 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>",
2668 'anonpreviewwarning'
2669 );
2670 }
2671 } else {
2672 if ( $this->isCssJsSubpage ) {
2673 # Check the skin exists
2674 if ( $this->isWrongCaseCssJsPage ) {
2675 $wgOut->wrapWikiMsg(
2676 "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>",
2677 array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() )
2678 );
2679 }
2680 if ( $this->formtype !== 'preview' ) {
2681 if ( $this->isCssSubpage && $wgAllowUserCss ) {
2682 $wgOut->wrapWikiMsg(
2683 "<div id='mw-usercssyoucanpreview'>\n$1\n</div>",
2684 array( 'usercssyoucanpreview' )
2685 );
2686 }
2687
2688 if ( $this->isJsSubpage && $wgAllowUserJs ) {
2689 $wgOut->wrapWikiMsg(
2690 "<div id='mw-userjsyoucanpreview'>\n$1\n</div>",
2691 array( 'userjsyoucanpreview' )
2692 );
2693 }
2694 }
2695 }
2696 }
2697
2698 if ( $this->mTitle->isProtected( 'edit' ) &&
2699 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2700 ) {
2701 # Is the title semi-protected?
2702 if ( $this->mTitle->isSemiProtected() ) {
2703 $noticeMsg = 'semiprotectedpagewarning';
2704 } else {
2705 # Then it must be protected based on static groups (regular)
2706 $noticeMsg = 'protectedpagewarning';
2707 }
2708 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2709 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2710 }
2711 if ( $this->mTitle->isCascadeProtected() ) {
2712 # Is this page under cascading protection from some source pages?
2713 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2714 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2715 $cascadeSourcesCount = count( $cascadeSources );
2716 if ( $cascadeSourcesCount > 0 ) {
2717 # Explain, and list the titles responsible
2718 foreach ( $cascadeSources as $page ) {
2719 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2720 }
2721 }
2722 $notice .= '</div>';
2723 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2724 }
2725 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2726 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2727 array( 'lim' => 1,
2728 'showIfEmpty' => false,
2729 'msgKey' => array( 'titleprotectedwarning' ),
2730 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2731 }
2732
2733 if ( $this->kblength === false ) {
2734 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2735 }
2736
2737 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2738 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2739 array(
2740 'longpageerror',
2741 $wgLang->formatNum( $this->kblength ),
2742 $wgLang->formatNum( $wgMaxArticleSize )
2743 )
2744 );
2745 } else {
2746 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2747 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2748 array(
2749 'longpage-hint',
2750 $wgLang->formatSize( strlen( $this->textbox1 ) ),
2751 strlen( $this->textbox1 )
2752 )
2753 );
2754 }
2755 }
2756 # Add header copyright warning
2757 $this->showHeaderCopyrightWarning();
2758
2759 return true;
2760 }
2761
2762 /**
2763 * Standard summary input and label (wgSummary), abstracted so EditPage
2764 * subclasses may reorganize the form.
2765 * Note that you do not need to worry about the label's for=, it will be
2766 * inferred by the id given to the input. You can remove them both by
2767 * passing array( 'id' => false ) to $userInputAttrs.
2768 *
2769 * @param string $summary The value of the summary input
2770 * @param string $labelText The html to place inside the label
2771 * @param array $inputAttrs Array of attrs to use on the input
2772 * @param array $spanLabelAttrs Array of attrs to use on the span inside the label
2773 *
2774 * @return array An array in the format array( $label, $input )
2775 */
2776 function getSummaryInput( $summary = "", $labelText = null,
2777 $inputAttrs = null, $spanLabelAttrs = null
2778 ) {
2779 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2780 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2781 'id' => 'wpSummary',
2782 'maxlength' => '200',
2783 'tabindex' => '1',
2784 'size' => 60,
2785 'spellcheck' => 'true',
2786 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2787
2788 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2789 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2790 'id' => "wpSummaryLabel"
2791 );
2792
2793 $label = null;
2794 if ( $labelText ) {
2795 $label = Xml::tags(
2796 'label',
2797 $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null,
2798 $labelText
2799 );
2800 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2801 }
2802
2803 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2804
2805 return array( $label, $input );
2806 }
2807
2808 /**
2809 * @param bool $isSubjectPreview True if this is the section subject/title
2810 * up top, or false if this is the comment summary
2811 * down below the textarea
2812 * @param string $summary The text of the summary to display
2813 */
2814 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2815 global $wgOut, $wgContLang;
2816 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2817 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2818 if ( $isSubjectPreview ) {
2819 if ( $this->nosummary ) {
2820 return;
2821 }
2822 } else {
2823 if ( !$this->mShowSummaryField ) {
2824 return;
2825 }
2826 }
2827 $summary = $wgContLang->recodeForEdit( $summary );
2828 $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
2829 list( $label, $input ) = $this->getSummaryInput(
2830 $summary,
2831 $labelText,
2832 array( 'class' => $summaryClass ),
2833 array()
2834 );
2835 $wgOut->addHTML( "{$label} {$input}" );
2836 }
2837
2838 /**
2839 * @param bool $isSubjectPreview True if this is the section subject/title
2840 * up top, or false if this is the comment summary
2841 * down below the textarea
2842 * @param string $summary The text of the summary to display
2843 * @return string
2844 */
2845 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2846 // avoid spaces in preview, gets always trimmed on save
2847 $summary = trim( $summary );
2848 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
2849 return "";
2850 }
2851
2852 global $wgParser;
2853
2854 if ( $isSubjectPreview ) {
2855 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2856 ->inContentLanguage()->text();
2857 }
2858
2859 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
2860
2861 $summary = wfMessage( $message )->parse()
2862 . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
2863 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2864 }
2865
2866 protected function showFormBeforeText() {
2867 global $wgOut;
2868 $section = htmlspecialchars( $this->section );
2869 $wgOut->addHTML( <<<HTML
2870 <input type='hidden' value="{$section}" name="wpSection"/>
2871 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2872 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2873 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2874
2875 HTML
2876 );
2877 if ( !$this->checkUnicodeCompliantBrowser() ) {
2878 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
2879 }
2880 }
2881
2882 protected function showFormAfterText() {
2883 global $wgOut, $wgUser;
2884 /**
2885 * To make it harder for someone to slip a user a page
2886 * which submits an edit form to the wiki without their
2887 * knowledge, a random token is associated with the login
2888 * session. If it's not passed back with the submission,
2889 * we won't save the page, or render user JavaScript and
2890 * CSS previews.
2891 *
2892 * For anon editors, who may not have a session, we just
2893 * include the constant suffix to prevent editing from
2894 * broken text-mangling proxies.
2895 */
2896 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2897 }
2898
2899 /**
2900 * Subpage overridable method for printing the form for page content editing
2901 * By default this simply outputs wpTextbox1
2902 * Subclasses can override this to provide a custom UI for editing;
2903 * be it a form, or simply wpTextbox1 with a modified content that will be
2904 * reverse modified when extracted from the post data.
2905 * Note that this is basically the inverse for importContentFormData
2906 */
2907 protected function showContentForm() {
2908 $this->showTextbox1();
2909 }
2910
2911 /**
2912 * Method to output wpTextbox1
2913 * The $textoverride method can be used by subclasses overriding showContentForm
2914 * to pass back to this method.
2915 *
2916 * @param array $customAttribs Array of html attributes to use in the textarea
2917 * @param string $textoverride Optional text to override $this->textarea1 with
2918 */
2919 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2920 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2921 $attribs = array( 'style' => 'display:none;' );
2922 } else {
2923 $classes = array(); // Textarea CSS
2924 if ( $this->mTitle->isProtected( 'edit' ) &&
2925 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2926 ) {
2927 # Is the title semi-protected?
2928 if ( $this->mTitle->isSemiProtected() ) {
2929 $classes[] = 'mw-textarea-sprotected';
2930 } else {
2931 # Then it must be protected based on static groups (regular)
2932 $classes[] = 'mw-textarea-protected';
2933 }
2934 # Is the title cascade-protected?
2935 if ( $this->mTitle->isCascadeProtected() ) {
2936 $classes[] = 'mw-textarea-cprotected';
2937 }
2938 }
2939
2940 $attribs = array( 'tabindex' => 1 );
2941
2942 if ( is_array( $customAttribs ) ) {
2943 $attribs += $customAttribs;
2944 }
2945
2946 if ( count( $classes ) ) {
2947 if ( isset( $attribs['class'] ) ) {
2948 $classes[] = $attribs['class'];
2949 }
2950 $attribs['class'] = implode( ' ', $classes );
2951 }
2952 }
2953
2954 $this->showTextbox(
2955 $textoverride !== null ? $textoverride : $this->textbox1,
2956 'wpTextbox1',
2957 $attribs
2958 );
2959 }
2960
2961 protected function showTextbox2() {
2962 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2963 }
2964
2965 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2966 global $wgOut, $wgUser;
2967
2968 $wikitext = $this->safeUnicodeOutput( $text );
2969 if ( strval( $wikitext ) !== '' ) {
2970 // Ensure there's a newline at the end, otherwise adding lines
2971 // is awkward.
2972 // But don't add a newline if the ext is empty, or Firefox in XHTML
2973 // mode will show an extra newline. A bit annoying.
2974 $wikitext .= "\n";
2975 }
2976
2977 $attribs = $customAttribs + array(
2978 'accesskey' => ',',
2979 'id' => $name,
2980 'cols' => $wgUser->getIntOption( 'cols' ),
2981 'rows' => $wgUser->getIntOption( 'rows' ),
2982 // Avoid PHP notices when appending preferences
2983 // (appending allows customAttribs['style'] to still work).
2984 'style' => ''
2985 );
2986
2987 $pageLang = $this->mTitle->getPageLanguage();
2988 $attribs['lang'] = $pageLang->getHtmlCode();
2989 $attribs['dir'] = $pageLang->getDir();
2990
2991 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
2992 }
2993
2994 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2995 global $wgOut;
2996 $classes = array();
2997 if ( $isOnTop ) {
2998 $classes[] = 'ontop';
2999 }
3000
3001 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
3002
3003 if ( $this->formtype != 'preview' ) {
3004 $attribs['style'] = 'display: none;';
3005 }
3006
3007 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
3008
3009 if ( $this->formtype == 'preview' ) {
3010 $this->showPreview( $previewOutput );
3011 } else {
3012 // Empty content container for LivePreview
3013 $pageViewLang = $this->mTitle->getPageViewLanguage();
3014 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3015 'class' => 'mw-content-' . $pageViewLang->getDir() );
3016 $wgOut->addHTML( Html::rawElement( 'div', $attribs ) );
3017 }
3018
3019 $wgOut->addHTML( '</div>' );
3020
3021 if ( $this->formtype == 'diff' ) {
3022 try {
3023 $this->showDiff();
3024 } catch ( MWContentSerializationException $ex ) {
3025 $msg = wfMessage(
3026 'content-failed-to-parse',
3027 $this->contentModel,
3028 $this->contentFormat,
3029 $ex->getMessage()
3030 );
3031 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
3032 }
3033 }
3034 }
3035
3036 /**
3037 * Append preview output to $wgOut.
3038 * Includes category rendering if this is a category page.
3039 *
3040 * @param string $text The HTML to be output for the preview.
3041 */
3042 protected function showPreview( $text ) {
3043 global $wgOut;
3044 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3045 $this->mArticle->openShowCategory();
3046 }
3047 # This hook seems slightly odd here, but makes things more
3048 # consistent for extensions.
3049 Hooks::run( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
3050 $wgOut->addHTML( $text );
3051 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
3052 $this->mArticle->closeShowCategory();
3053 }
3054 }
3055
3056 /**
3057 * Get a diff between the current contents of the edit box and the
3058 * version of the page we're editing from.
3059 *
3060 * If this is a section edit, we'll replace the section as for final
3061 * save and then make a comparison.
3062 */
3063 function showDiff() {
3064 global $wgUser, $wgContLang, $wgOut;
3065
3066 $oldtitlemsg = 'currentrev';
3067 # if message does not exist, show diff against the preloaded default
3068 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
3069 $oldtext = $this->mTitle->getDefaultMessageText();
3070 if ( $oldtext !== false ) {
3071 $oldtitlemsg = 'defaultmessagetext';
3072 $oldContent = $this->toEditContent( $oldtext );
3073 } else {
3074 $oldContent = null;
3075 }
3076 } else {
3077 $oldContent = $this->getCurrentContent();
3078 }
3079
3080 $textboxContent = $this->toEditContent( $this->textbox1 );
3081
3082 $newContent = $this->mArticle->replaceSectionContent(
3083 $this->section, $textboxContent,
3084 $this->summary, $this->edittime );
3085
3086 if ( $newContent ) {
3087 ContentHandler::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
3088 Hooks::run( 'EditPageGetDiffContent', array( $this, &$newContent ) );
3089
3090 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
3091 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
3092 }
3093
3094 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
3095 $oldtitle = wfMessage( $oldtitlemsg )->parse();
3096 $newtitle = wfMessage( 'yourtext' )->parse();
3097
3098 if ( !$oldContent ) {
3099 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
3100 }
3101
3102 if ( !$newContent ) {
3103 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
3104 }
3105
3106 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
3107 $de->setContent( $oldContent, $newContent );
3108
3109 $difftext = $de->getDiff( $oldtitle, $newtitle );
3110 $de->showDiffStyle();
3111 } else {
3112 $difftext = '';
3113 }
3114
3115 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
3116 }
3117
3118 /**
3119 * Show the header copyright warning.
3120 */
3121 protected function showHeaderCopyrightWarning() {
3122 $msg = 'editpage-head-copy-warn';
3123 if ( !wfMessage( $msg )->isDisabled() ) {
3124 global $wgOut;
3125 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
3126 'editpage-head-copy-warn' );
3127 }
3128 }
3129
3130 /**
3131 * Give a chance for site and per-namespace customizations of
3132 * terms of service summary link that might exist separately
3133 * from the copyright notice.
3134 *
3135 * This will display between the save button and the edit tools,
3136 * so should remain short!
3137 */
3138 protected function showTosSummary() {
3139 $msg = 'editpage-tos-summary';
3140 Hooks::run( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
3141 if ( !wfMessage( $msg )->isDisabled() ) {
3142 global $wgOut;
3143 $wgOut->addHTML( '<div class="mw-tos-summary">' );
3144 $wgOut->addWikiMsg( $msg );
3145 $wgOut->addHTML( '</div>' );
3146 }
3147 }
3148
3149 protected function showEditTools() {
3150 global $wgOut;
3151 $wgOut->addHTML( '<div class="mw-editTools">' .
3152 wfMessage( 'edittools' )->inContentLanguage()->parse() .
3153 '</div>' );
3154 }
3155
3156 /**
3157 * Get the copyright warning
3158 *
3159 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
3160 * @return string
3161 */
3162 protected function getCopywarn() {
3163 return self::getCopyrightWarning( $this->mTitle );
3164 }
3165
3166 /**
3167 * Get the copyright warning, by default returns wikitext
3168 *
3169 * @param Title $title
3170 * @param string $format Output format, valid values are any function of a Message object
3171 * @return string
3172 */
3173 public static function getCopyrightWarning( $title, $format = 'plain' ) {
3174 global $wgRightsText;
3175 if ( $wgRightsText ) {
3176 $copywarnMsg = array( 'copyrightwarning',
3177 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
3178 $wgRightsText );
3179 } else {
3180 $copywarnMsg = array( 'copyrightwarning2',
3181 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
3182 }
3183 // Allow for site and per-namespace customization of contribution/copyright notice.
3184 Hooks::run( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
3185
3186 return "<div id=\"editpage-copywarn\">\n" .
3187 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
3188 }
3189
3190 /**
3191 * Get the Limit report for page previews
3192 *
3193 * @since 1.22
3194 * @param ParserOutput $output ParserOutput object from the parse
3195 * @return string HTML
3196 */
3197 public static function getPreviewLimitReport( $output ) {
3198 if ( !$output || !$output->getLimitReportData() ) {
3199 return '';
3200 }
3201
3202 $limitReport = Html::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
3203 wfMessage( 'limitreport-title' )->parseAsBlock()
3204 );
3205
3206 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
3207 $limitReport .= Html::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
3208
3209 $limitReport .= Html::openElement( 'table', array(
3210 'class' => 'preview-limit-report wikitable'
3211 ) ) .
3212 Html::openElement( 'tbody' );
3213
3214 foreach ( $output->getLimitReportData() as $key => $value ) {
3215 if ( Hooks::run( 'ParserLimitReportFormat',
3216 array( $key, &$value, &$limitReport, true, true )
3217 ) ) {
3218 $keyMsg = wfMessage( $key );
3219 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
3220 if ( !$valueMsg->exists() ) {
3221 $valueMsg = new RawMessage( '$1' );
3222 }
3223 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3224 $limitReport .= Html::openElement( 'tr' ) .
3225 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3226 Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3227 Html::closeElement( 'tr' );
3228 }
3229 }
3230 }
3231
3232 $limitReport .= Html::closeElement( 'tbody' ) .
3233 Html::closeElement( 'table' ) .
3234 Html::closeElement( 'div' );
3235
3236 return $limitReport;
3237 }
3238
3239 protected function showStandardInputs( &$tabindex = 2 ) {
3240 global $wgOut;
3241 $wgOut->addHTML( "<div class='editOptions'>\n" );
3242
3243 if ( $this->section != 'new' ) {
3244 $this->showSummaryInput( false, $this->summary );
3245 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3246 }
3247
3248 $checkboxes = $this->getCheckboxes( $tabindex,
3249 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
3250 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3251
3252 // Show copyright warning.
3253 $wgOut->addWikiText( $this->getCopywarn() );
3254 $wgOut->addHTML( $this->editFormTextAfterWarn );
3255
3256 $wgOut->addHTML( "<div class='editButtons'>\n" );
3257 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3258
3259 $cancel = $this->getCancelLink();
3260 if ( $cancel !== '' ) {
3261 $cancel .= Html::element( 'span',
3262 array( 'class' => 'mw-editButtons-pipe-separator' ),
3263 wfMessage( 'pipe-separator' )->text() );
3264 }
3265
3266 $message = wfMessage( 'edithelppage' )->inContentLanguage()->text();
3267 $edithelpurl = Skin::makeInternalOrExternalUrl( $message );
3268 $attrs = array(
3269 'target' => 'helpwindow',
3270 'href' => $edithelpurl,
3271 );
3272 $edithelp = Html::linkButton( wfMessage( 'edithelp' )->text(),
3273 $attrs, array( 'mw-ui-quiet' ) ) .
3274 wfMessage( 'word-separator' )->escaped() .
3275 wfMessage( 'newwindow' )->parse();
3276
3277 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3278 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3279 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3280
3281 Hooks::run( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3282
3283 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3284 }
3285
3286 /**
3287 * Show an edit conflict. textbox1 is already shown in showEditForm().
3288 * If you want to use another entry point to this function, be careful.
3289 */
3290 protected function showConflict() {
3291 global $wgOut;
3292
3293 if ( Hooks::run( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3294 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3295
3296 $content1 = $this->toEditContent( $this->textbox1 );
3297 $content2 = $this->toEditContent( $this->textbox2 );
3298
3299 $handler = ContentHandler::getForModelID( $this->contentModel );
3300 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3301 $de->setContent( $content2, $content1 );
3302 $de->showDiff(
3303 wfMessage( 'yourtext' )->parse(),
3304 wfMessage( 'storedversion' )->text()
3305 );
3306
3307 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3308 $this->showTextbox2();
3309 }
3310 }
3311
3312 /**
3313 * @return string
3314 */
3315 public function getCancelLink() {
3316 $cancelParams = array();
3317 if ( !$this->isConflict && $this->oldid > 0 ) {
3318 $cancelParams['oldid'] = $this->oldid;
3319 }
3320 $attrs = array( 'id' => 'mw-editform-cancel' );
3321
3322 return Linker::linkKnown(
3323 $this->getContextTitle(),
3324 wfMessage( 'cancel' )->parse(),
3325 Html::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ),
3326 $cancelParams
3327 );
3328 }
3329
3330 /**
3331 * Returns the URL to use in the form's action attribute.
3332 * This is used by EditPage subclasses when simply customizing the action
3333 * variable in the constructor is not enough. This can be used when the
3334 * EditPage lives inside of a Special page rather than a custom page action.
3335 *
3336 * @param Title $title Title object for which is being edited (where we go to for &action= links)
3337 * @return string
3338 */
3339 protected function getActionURL( Title $title ) {
3340 return $title->getLocalURL( array( 'action' => $this->action ) );
3341 }
3342
3343 /**
3344 * Check if a page was deleted while the user was editing it, before submit.
3345 * Note that we rely on the logging table, which hasn't been always there,
3346 * but that doesn't matter, because this only applies to brand new
3347 * deletes.
3348 * @return bool
3349 */
3350 protected function wasDeletedSinceLastEdit() {
3351 if ( $this->deletedSinceEdit !== null ) {
3352 return $this->deletedSinceEdit;
3353 }
3354
3355 $this->deletedSinceEdit = false;
3356
3357 if ( $this->mTitle->isDeletedQuick() ) {
3358 $this->lastDelete = $this->getLastDelete();
3359 if ( $this->lastDelete ) {
3360 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3361 if ( $deleteTime > $this->starttime ) {
3362 $this->deletedSinceEdit = true;
3363 }
3364 }
3365 }
3366
3367 return $this->deletedSinceEdit;
3368 }
3369
3370 /**
3371 * @return bool|stdClass
3372 */
3373 protected function getLastDelete() {
3374 $dbr = wfGetDB( DB_SLAVE );
3375 $data = $dbr->selectRow(
3376 array( 'logging', 'user' ),
3377 array(
3378 'log_type',
3379 'log_action',
3380 'log_timestamp',
3381 'log_user',
3382 'log_namespace',
3383 'log_title',
3384 'log_comment',
3385 'log_params',
3386 'log_deleted',
3387 'user_name'
3388 ), array(
3389 'log_namespace' => $this->mTitle->getNamespace(),
3390 'log_title' => $this->mTitle->getDBkey(),
3391 'log_type' => 'delete',
3392 'log_action' => 'delete',
3393 'user_id=log_user'
3394 ),
3395 __METHOD__,
3396 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3397 );
3398 // Quick paranoid permission checks...
3399 if ( is_object( $data ) ) {
3400 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3401 $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
3402 }
3403
3404 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3405 $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
3406 }
3407 }
3408
3409 return $data;
3410 }
3411
3412 /**
3413 * Get the rendered text for previewing.
3414 * @throws MWException
3415 * @return string
3416 */
3417 function getPreviewText() {
3418 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3419 global $wgAllowUserCss, $wgAllowUserJs;
3420
3421 if ( $wgRawHtml && !$this->mTokenOk ) {
3422 // Could be an offsite preview attempt. This is very unsafe if
3423 // HTML is enabled, as it could be an attack.
3424 $parsedNote = '';
3425 if ( $this->textbox1 !== '' ) {
3426 // Do not put big scary notice, if previewing the empty
3427 // string, which happens when you initially edit
3428 // a category page, due to automatic preview-on-open.
3429 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3430 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3431 }
3432 return $parsedNote;
3433 }
3434
3435 $note = '';
3436
3437 try {
3438 $content = $this->toEditContent( $this->textbox1 );
3439
3440 $previewHTML = '';
3441 if ( !Hooks::run(
3442 'AlternateEditPreview',
3443 array( $this, &$content, &$previewHTML, &$this->mParserOutput ) )
3444 ) {
3445 return $previewHTML;
3446 }
3447
3448 # provide a anchor link to the editform
3449 $continueEditing = '<span class="mw-continue-editing">' .
3450 '[[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' .
3451 wfMessage( 'continue-editing' )->text() . ']]</span>';
3452 if ( $this->mTriedSave && !$this->mTokenOk ) {
3453 if ( $this->mTokenOkExceptSuffix ) {
3454 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3455 } else {
3456 $note = wfMessage( 'session_fail_preview' )->plain();
3457 }
3458 } elseif ( $this->incompleteForm ) {
3459 $note = wfMessage( 'edit_form_incomplete' )->plain();
3460 } else {
3461 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3462 }
3463
3464 $parserOptions = $this->mArticle->makeParserOptions( $this->mArticle->getContext() );
3465 $parserOptions->setIsPreview( true );
3466 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3467
3468 # don't parse non-wikitext pages, show message about preview
3469 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3470 if ( $this->mTitle->isCssJsSubpage() ) {
3471 $level = 'user';
3472 } elseif ( $this->mTitle->isCssOrJsPage() ) {
3473 $level = 'site';
3474 } else {
3475 $level = false;
3476 }
3477
3478 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3479 $format = 'css';
3480 if ( $level === 'user' && !$wgAllowUserCss ) {
3481 $format = false;
3482 }
3483 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3484 $format = 'js';
3485 if ( $level === 'user' && !$wgAllowUserJs ) {
3486 $format = false;
3487 }
3488 } else {
3489 $format = false;
3490 }
3491
3492 # Used messages to make sure grep find them:
3493 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3494 if ( $level && $format ) {
3495 $note = "<div id='mw-{$level}{$format}preview'>" .
3496 wfMessage( "{$level}{$format}preview" )->text() .
3497 ' ' . $continueEditing . "</div>";
3498 }
3499 }
3500
3501 # If we're adding a comment, we need to show the
3502 # summary as the headline
3503 if ( $this->section === "new" && $this->summary !== "" ) {
3504 $content = $content->addSectionHeader( $this->summary );
3505 }
3506
3507 $hook_args = array( $this, &$content );
3508 ContentHandler::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3509 Hooks::run( 'EditPageGetPreviewContent', $hook_args );
3510
3511 $parserOptions->enableLimitReport();
3512
3513 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3514 # But it's now deprecated, so never mind
3515
3516 $pstContent = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3517 $scopedCallback = $parserOptions->setupFakeRevision(
3518 $this->mTitle, $pstContent, $wgUser );
3519 $parserOutput = $pstContent->getParserOutput( $this->mTitle, null, $parserOptions );
3520
3521 # Try to stash the edit for the final submission step
3522 # @todo: different date format preferences cause cache misses
3523 ApiStashEdit::stashEditFromPreview(
3524 $this->getArticle(), $content, $pstContent,
3525 $parserOutput, $parserOptions, $parserOptions, wfTimestampNow()
3526 );
3527
3528 $parserOutput->setEditSectionTokens( false ); // no section edit links
3529 $previewHTML = $parserOutput->getText();
3530 $this->mParserOutput = $parserOutput;
3531 $wgOut->addParserOutputMetadata( $parserOutput );
3532
3533 if ( count( $parserOutput->getWarnings() ) ) {
3534 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3535 }
3536 } catch ( MWContentSerializationException $ex ) {
3537 $m = wfMessage(
3538 'content-failed-to-parse',
3539 $this->contentModel,
3540 $this->contentFormat,
3541 $ex->getMessage()
3542 );
3543 $note .= "\n\n" . $m->parse();
3544 $previewHTML = '';
3545 }
3546
3547 if ( $this->isConflict ) {
3548 $conflict = '<h2 id="mw-previewconflict">'
3549 . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3550 } else {
3551 $conflict = '<hr />';
3552 }
3553
3554 $previewhead = "<div class='previewnote'>\n" .
3555 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3556 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3557
3558 $pageViewLang = $this->mTitle->getPageViewLanguage();
3559 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3560 'class' => 'mw-content-' . $pageViewLang->getDir() );
3561 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3562
3563 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3564 }
3565
3566 /**
3567 * @return array
3568 */
3569 function getTemplates() {
3570 if ( $this->preview || $this->section != '' ) {
3571 $templates = array();
3572 if ( !isset( $this->mParserOutput ) ) {
3573 return $templates;
3574 }
3575 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3576 foreach ( array_keys( $template ) as $dbk ) {
3577 $templates[] = Title::makeTitle( $ns, $dbk );
3578 }
3579 }
3580 return $templates;
3581 } else {
3582 return $this->mTitle->getTemplateLinksFrom();
3583 }
3584 }
3585
3586 /**
3587 * Shows a bulletin board style toolbar for common editing functions.
3588 * It can be disabled in the user preferences.
3589 *
3590 * @return string
3591 */
3592 static function getEditToolbar() {
3593 global $wgContLang, $wgOut;
3594 global $wgEnableUploads, $wgForeignFileRepos;
3595
3596 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3597
3598 /**
3599 * $toolarray is an array of arrays each of which includes the
3600 * opening tag, the closing tag, optionally a sample text that is
3601 * inserted between the two when no selection is highlighted
3602 * and. The tip text is shown when the user moves the mouse
3603 * over the button.
3604 *
3605 * Images are defined in ResourceLoaderEditToolbarModule.
3606 */
3607 $toolarray = array(
3608 array(
3609 'id' => 'mw-editbutton-bold',
3610 'open' => '\'\'\'',
3611 'close' => '\'\'\'',
3612 'sample' => wfMessage( 'bold_sample' )->text(),
3613 'tip' => wfMessage( 'bold_tip' )->text(),
3614 ),
3615 array(
3616 'id' => 'mw-editbutton-italic',
3617 'open' => '\'\'',
3618 'close' => '\'\'',
3619 'sample' => wfMessage( 'italic_sample' )->text(),
3620 'tip' => wfMessage( 'italic_tip' )->text(),
3621 ),
3622 array(
3623 'id' => 'mw-editbutton-link',
3624 'open' => '[[',
3625 'close' => ']]',
3626 'sample' => wfMessage( 'link_sample' )->text(),
3627 'tip' => wfMessage( 'link_tip' )->text(),
3628 ),
3629 array(
3630 'id' => 'mw-editbutton-extlink',
3631 'open' => '[',
3632 'close' => ']',
3633 'sample' => wfMessage( 'extlink_sample' )->text(),
3634 'tip' => wfMessage( 'extlink_tip' )->text(),
3635 ),
3636 array(
3637 'id' => 'mw-editbutton-headline',
3638 'open' => "\n== ",
3639 'close' => " ==\n",
3640 'sample' => wfMessage( 'headline_sample' )->text(),
3641 'tip' => wfMessage( 'headline_tip' )->text(),
3642 ),
3643 $imagesAvailable ? array(
3644 'id' => 'mw-editbutton-image',
3645 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3646 'close' => ']]',
3647 'sample' => wfMessage( 'image_sample' )->text(),
3648 'tip' => wfMessage( 'image_tip' )->text(),
3649 ) : false,
3650 $imagesAvailable ? array(
3651 'id' => 'mw-editbutton-media',
3652 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3653 'close' => ']]',
3654 'sample' => wfMessage( 'media_sample' )->text(),
3655 'tip' => wfMessage( 'media_tip' )->text(),
3656 ) : false,
3657 array(
3658 'id' => 'mw-editbutton-nowiki',
3659 'open' => "<nowiki>",
3660 'close' => "</nowiki>",
3661 'sample' => wfMessage( 'nowiki_sample' )->text(),
3662 'tip' => wfMessage( 'nowiki_tip' )->text(),
3663 ),
3664 array(
3665 'id' => 'mw-editbutton-signature',
3666 'open' => '--~~~~',
3667 'close' => '',
3668 'sample' => '',
3669 'tip' => wfMessage( 'sig_tip' )->text(),
3670 ),
3671 array(
3672 'id' => 'mw-editbutton-hr',
3673 'open' => "\n----\n",
3674 'close' => '',
3675 'sample' => '',
3676 'tip' => wfMessage( 'hr_tip' )->text(),
3677 )
3678 );
3679
3680 $script = 'mw.loader.using("mediawiki.toolbar", function () {';
3681 foreach ( $toolarray as $tool ) {
3682 if ( !$tool ) {
3683 continue;
3684 }
3685
3686 $params = array(
3687 // Images are defined in ResourceLoaderEditToolbarModule
3688 false,
3689 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3690 // Older browsers show a "speedtip" type message only for ALT.
3691 // Ideally these should be different, realistically they
3692 // probably don't need to be.
3693 $tool['tip'],
3694 $tool['open'],
3695 $tool['close'],
3696 $tool['sample'],
3697 $tool['id'],
3698 );
3699
3700 $script .= Xml::encodeJsCall(
3701 'mw.toolbar.addButton',
3702 $params,
3703 ResourceLoader::inDebugMode()
3704 );
3705 }
3706
3707 $script .= '});';
3708 $wgOut->addScript( ResourceLoader::makeInlineScript( $script ) );
3709
3710 $toolbar = '<div id="toolbar"></div>';
3711
3712 Hooks::run( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3713
3714 return $toolbar;
3715 }
3716
3717 /**
3718 * Returns an array of html code of the following checkboxes:
3719 * minor and watch
3720 *
3721 * @param int $tabindex Current tabindex
3722 * @param array $checked Array of checkbox => bool, where bool indicates the checked
3723 * status of the checkbox
3724 *
3725 * @return array
3726 */
3727 public function getCheckboxes( &$tabindex, $checked ) {
3728 global $wgUser, $wgUseMediaWikiUIEverywhere;
3729
3730 $checkboxes = array();
3731
3732 // don't show the minor edit checkbox if it's a new page or section
3733 if ( !$this->isNew ) {
3734 $checkboxes['minor'] = '';
3735 $minorLabel = wfMessage( 'minoredit' )->parse();
3736 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3737 $attribs = array(
3738 'tabindex' => ++$tabindex,
3739 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3740 'id' => 'wpMinoredit',
3741 );
3742 $minorEditHtml =
3743 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3744 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
3745 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3746 ">{$minorLabel}</label>";
3747
3748 if ( $wgUseMediaWikiUIEverywhere ) {
3749 $checkboxes['minor'] = Html::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3750 $minorEditHtml .
3751 Html::closeElement( 'div' );
3752 } else {
3753 $checkboxes['minor'] = $minorEditHtml;
3754 }
3755 }
3756 }
3757
3758 $watchLabel = wfMessage( 'watchthis' )->parse();
3759 $checkboxes['watch'] = '';
3760 if ( $wgUser->isLoggedIn() ) {
3761 $attribs = array(
3762 'tabindex' => ++$tabindex,
3763 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3764 'id' => 'wpWatchthis',
3765 );
3766 $watchThisHtml =
3767 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3768 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
3769 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
3770 ">{$watchLabel}</label>";
3771 if ( $wgUseMediaWikiUIEverywhere ) {
3772 $checkboxes['watch'] = Html::openElement( 'div', array( 'class' => 'mw-ui-checkbox' ) ) .
3773 $watchThisHtml .
3774 Html::closeElement( 'div' );
3775 } else {
3776 $checkboxes['watch'] = $watchThisHtml;
3777 }
3778 }
3779 Hooks::run( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3780 return $checkboxes;
3781 }
3782
3783 /**
3784 * Returns an array of html code of the following buttons:
3785 * save, diff, preview and live
3786 *
3787 * @param int $tabindex Current tabindex
3788 *
3789 * @return array
3790 */
3791 public function getEditButtons( &$tabindex ) {
3792 $buttons = array();
3793
3794 $attribs = array(
3795 'id' => 'wpSave',
3796 'name' => 'wpSave',
3797 'tabindex' => ++$tabindex,
3798 ) + Linker::tooltipAndAccesskeyAttribs( 'save' );
3799 $buttons['save'] = Html::submitButton( wfMessage( 'savearticle' )->text(),
3800 $attribs, array( 'mw-ui-constructive' ) );
3801
3802 ++$tabindex; // use the same for preview and live preview
3803 $attribs = array(
3804 'id' => 'wpPreview',
3805 'name' => 'wpPreview',
3806 'tabindex' => $tabindex,
3807 ) + Linker::tooltipAndAccesskeyAttribs( 'preview' );
3808 $buttons['preview'] = Html::submitButton( wfMessage( 'showpreview' )->text(),
3809 $attribs );
3810 $buttons['live'] = '';
3811
3812 $attribs = array(
3813 'id' => 'wpDiff',
3814 'name' => 'wpDiff',
3815 'tabindex' => ++$tabindex,
3816 ) + Linker::tooltipAndAccesskeyAttribs( 'diff' );
3817 $buttons['diff'] = Html::submitButton( wfMessage( 'showdiff' )->text(),
3818 $attribs );
3819
3820 Hooks::run( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3821 return $buttons;
3822 }
3823
3824 /**
3825 * Output preview text only. This can be sucked into the edit page
3826 * via JavaScript, and saves the server time rendering the skin as
3827 * well as theoretically being more robust on the client (doesn't
3828 * disturb the edit box's undo history, won't eat your text on
3829 * failure, etc).
3830 *
3831 * @todo This doesn't include category or interlanguage links.
3832 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3833 * or something...</s>" that might also require more skin
3834 * initialization, so check whether that's a problem.
3835 */
3836 function livePreview() {
3837 global $wgOut;
3838 $wgOut->disable();
3839 header( 'Content-type: text/xml; charset=utf-8' );
3840 header( 'Cache-control: no-cache' );
3841
3842 $previewText = $this->getPreviewText();
3843 #$categories = $skin->getCategoryLinks();
3844
3845 $s =
3846 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3847 Xml::tags( 'livepreview', null,
3848 Xml::element( 'preview', null, $previewText )
3849 #. Xml::element( 'category', null, $categories )
3850 );
3851 echo $s;
3852 }
3853
3854 /**
3855 * Creates a basic error page which informs the user that
3856 * they have attempted to edit a nonexistent section.
3857 */
3858 function noSuchSectionPage() {
3859 global $wgOut;
3860
3861 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3862
3863 $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
3864 Hooks::run( 'EditPageNoSuchSection', array( &$this, &$res ) );
3865 $wgOut->addHTML( $res );
3866
3867 $wgOut->returnToMain( false, $this->mTitle );
3868 }
3869
3870 /**
3871 * Show "your edit contains spam" page with your diff and text
3872 *
3873 * @param string|array|bool $match Text (or array of texts) which triggered one or more filters
3874 */
3875 public function spamPageWithContent( $match = false ) {
3876 global $wgOut, $wgLang;
3877 $this->textbox2 = $this->textbox1;
3878
3879 if ( is_array( $match ) ) {
3880 $match = $wgLang->listToText( $match );
3881 }
3882 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3883
3884 $wgOut->addHTML( '<div id="spamprotected">' );
3885 $wgOut->addWikiMsg( 'spamprotectiontext' );
3886 if ( $match ) {
3887 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3888 }
3889 $wgOut->addHTML( '</div>' );
3890
3891 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3892 $this->showDiff();
3893
3894 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3895 $this->showTextbox2();
3896
3897 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3898 }
3899
3900 /**
3901 * Check if the browser is on a blacklist of user-agents known to
3902 * mangle UTF-8 data on form submission. Returns true if Unicode
3903 * should make it through, false if it's known to be a problem.
3904 * @return bool
3905 */
3906 private function checkUnicodeCompliantBrowser() {
3907 global $wgBrowserBlackList, $wgRequest;
3908
3909 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3910 if ( $currentbrowser === false ) {
3911 // No User-Agent header sent? Trust it by default...
3912 return true;
3913 }
3914
3915 foreach ( $wgBrowserBlackList as $browser ) {
3916 if ( preg_match( $browser, $currentbrowser ) ) {
3917 return false;
3918 }
3919 }
3920 return true;
3921 }
3922
3923 /**
3924 * Filter an input field through a Unicode de-armoring process if it
3925 * came from an old browser with known broken Unicode editing issues.
3926 *
3927 * @param WebRequest $request
3928 * @param string $field
3929 * @return string
3930 */
3931 protected function safeUnicodeInput( $request, $field ) {
3932 $text = rtrim( $request->getText( $field ) );
3933 return $request->getBool( 'safemode' )
3934 ? $this->unmakeSafe( $text )
3935 : $text;
3936 }
3937
3938 /**
3939 * Filter an output field through a Unicode armoring process if it is
3940 * going to an old browser with known broken Unicode editing issues.
3941 *
3942 * @param string $text
3943 * @return string
3944 */
3945 protected function safeUnicodeOutput( $text ) {
3946 global $wgContLang;
3947 $codedText = $wgContLang->recodeForEdit( $text );
3948 return $this->checkUnicodeCompliantBrowser()
3949 ? $codedText
3950 : $this->makeSafe( $codedText );
3951 }
3952
3953 /**
3954 * A number of web browsers are known to corrupt non-ASCII characters
3955 * in a UTF-8 text editing environment. To protect against this,
3956 * detected browsers will be served an armored version of the text,
3957 * with non-ASCII chars converted to numeric HTML character references.
3958 *
3959 * Preexisting such character references will have a 0 added to them
3960 * to ensure that round-trips do not alter the original data.
3961 *
3962 * @param string $invalue
3963 * @return string
3964 */
3965 private function makeSafe( $invalue ) {
3966 // Armor existing references for reversibility.
3967 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
3968
3969 $bytesleft = 0;
3970 $result = "";
3971 $working = 0;
3972 $valueLength = strlen( $invalue );
3973 for ( $i = 0; $i < $valueLength; $i++ ) {
3974 $bytevalue = ord( $invalue[$i] );
3975 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3976 $result .= chr( $bytevalue );
3977 $bytesleft = 0;
3978 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3979 $working = $working << 6;
3980 $working += ( $bytevalue & 0x3F );
3981 $bytesleft--;
3982 if ( $bytesleft <= 0 ) {
3983 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3984 }
3985 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3986 $working = $bytevalue & 0x1F;
3987 $bytesleft = 1;
3988 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3989 $working = $bytevalue & 0x0F;
3990 $bytesleft = 2;
3991 } else { // 1111 0xxx
3992 $working = $bytevalue & 0x07;
3993 $bytesleft = 3;
3994 }
3995 }
3996 return $result;
3997 }
3998
3999 /**
4000 * Reverse the previously applied transliteration of non-ASCII characters
4001 * back to UTF-8. Used to protect data from corruption by broken web browsers
4002 * as listed in $wgBrowserBlackList.
4003 *
4004 * @param string $invalue
4005 * @return string
4006 */
4007 private function unmakeSafe( $invalue ) {
4008 $result = "";
4009 $valueLength = strlen( $invalue );
4010 for ( $i = 0; $i < $valueLength; $i++ ) {
4011 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
4012 $i += 3;
4013 $hexstring = "";
4014 do {
4015 $hexstring .= $invalue[$i];
4016 $i++;
4017 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
4018
4019 // Do some sanity checks. These aren't needed for reversibility,
4020 // but should help keep the breakage down if the editor
4021 // breaks one of the entities whilst editing.
4022 if ( ( substr( $invalue, $i, 1 ) == ";" ) && ( strlen( $hexstring ) <= 6 ) ) {
4023 $codepoint = hexdec( $hexstring );
4024 $result .= codepointToUtf8( $codepoint );
4025 } else {
4026 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
4027 }
4028 } else {
4029 $result .= substr( $invalue, $i, 1 );
4030 }
4031 }
4032 // reverse the transform that we made for reversibility reasons.
4033 return strtr( $result, array( "&#x0" => "&#x" ) );
4034 }
4035 }