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