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