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