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