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