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