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