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