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