Whitespaces fixes
[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 $this->editFormPageTop .= $wgOut->parse( "<div class=\"error mw-undo-{$undoMsg}\">" .
841 wfMsgNoTrans( 'undo-' . $undoMsg ) . '</div>', true, /* interface */true );
842 }
843
844 if ( $text === false ) {
845 $text = $this->getOriginalContent();
846 }
847 }
848 }
849
850 wfProfileOut( __METHOD__ );
851 return $text;
852 }
853
854 /**
855 * Get the content of the wanted revision, without section extraction.
856 *
857 * The result of this function can be used to compare user's input with
858 * section replaced in its context (using WikiPage::replaceSection())
859 * to the original text of the edit.
860 *
861 * This difers from Article::getContent() that when a missing revision is
862 * encountered the result will be an empty string and not the
863 * 'missing-article' message.
864 *
865 * @since 1.19
866 * @return string
867 */
868 private function getOriginalContent() {
869 if ( $this->section == 'new' ) {
870 return $this->getCurrentText();
871 }
872 $revision = $this->mArticle->getRevisionFetched();
873 if ( $revision === null ) {
874 return '';
875 }
876 return $this->mArticle->getContent();
877 }
878
879 /**
880 * Get the actual text of the page. This is basically similar to
881 * WikiPage::getRawText() except that when the page doesn't exist an empty
882 * string is returned instead of false.
883 *
884 * @since 1.19
885 * @return string
886 */
887 private function getCurrentText() {
888 $text = $this->mArticle->getRawText();
889 if ( $text === false ) {
890 return '';
891 } else {
892 return $text;
893 }
894 }
895
896 /**
897 * Use this method before edit() to preload some text into the edit box
898 *
899 * @param $text string
900 */
901 public function setPreloadedText( $text ) {
902 $this->mPreloadText = $text;
903 }
904
905 /**
906 * Get the contents to be preloaded into the box, either set by
907 * an earlier setPreloadText() or by loading the given page.
908 *
909 * @param $preload String: representing the title to preload from.
910 * @return String
911 */
912 protected function getPreloadedText( $preload ) {
913 global $wgUser, $wgParser;
914
915 if ( !empty( $this->mPreloadText ) ) {
916 return $this->mPreloadText;
917 }
918
919 if ( $preload === '' ) {
920 return '';
921 }
922
923 $title = Title::newFromText( $preload );
924 # Check for existence to avoid getting MediaWiki:Noarticletext
925 if ( $title === null || !$title->exists() || !$title->userCan( 'read' ) ) {
926 return '';
927 }
928
929 $page = WikiPage::factory( $title );
930 if ( $page->isRedirect() ) {
931 $title = $page->getRedirectTarget();
932 # Same as before
933 if ( $title === null || !$title->exists() || !$title->userCan( 'read' ) ) {
934 return '';
935 }
936 $page = WikiPage::factory( $title );
937 }
938
939 $parserOptions = ParserOptions::newFromUser( $wgUser );
940 return $wgParser->getPreloadText( $page->getRawText(), $title, $parserOptions );
941 }
942
943 /**
944 * Make sure the form isn't faking a user's credentials.
945 *
946 * @param $request WebRequest
947 * @return bool
948 * @private
949 */
950 function tokenOk( &$request ) {
951 global $wgUser;
952 $token = $request->getVal( 'wpEditToken' );
953 $this->mTokenOk = $wgUser->matchEditToken( $token );
954 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
955 return $this->mTokenOk;
956 }
957
958 /**
959 * Attempt submission
960 * @return bool false if output is done, true if the rest of the form should be displayed
961 */
962 function attemptSave() {
963 global $wgUser, $wgOut;
964
965 $resultDetails = false;
966 # Allow bots to exempt some edits from bot flagging
967 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
968 $status = $this->internalAttemptSave( $resultDetails, $bot );
969 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
970
971 if ( $status->value == self::AS_SUCCESS_UPDATE || $status->value == self::AS_SUCCESS_NEW_ARTICLE ) {
972 $this->didSave = true;
973 }
974
975 switch ( $status->value ) {
976 case self::AS_HOOK_ERROR_EXPECTED:
977 case self::AS_CONTENT_TOO_BIG:
978 case self::AS_ARTICLE_WAS_DELETED:
979 case self::AS_CONFLICT_DETECTED:
980 case self::AS_SUMMARY_NEEDED:
981 case self::AS_TEXTBOX_EMPTY:
982 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
983 case self::AS_END:
984 return true;
985
986 case self::AS_HOOK_ERROR:
987 case self::AS_FILTERING:
988 return false;
989
990 case self::AS_SUCCESS_NEW_ARTICLE:
991 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
992 $anchor = isset ( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
993 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
994 return false;
995
996 case self::AS_SUCCESS_UPDATE:
997 $extraQuery = '';
998 $sectionanchor = $resultDetails['sectionanchor'];
999
1000 // Give extensions a chance to modify URL query on update
1001 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle, &$sectionanchor, &$extraQuery ) );
1002
1003 if ( $resultDetails['redirect'] ) {
1004 if ( $extraQuery == '' ) {
1005 $extraQuery = 'redirect=no';
1006 } else {
1007 $extraQuery = 'redirect=no&' . $extraQuery;
1008 }
1009 }
1010 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1011 return false;
1012
1013 case self::AS_BLANK_ARTICLE:
1014 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1015 return false;
1016
1017 case self::AS_SPAM_ERROR:
1018 $this->spamPageWithContent( $resultDetails['spam'] );
1019 return false;
1020
1021 case self::AS_BLOCKED_PAGE_FOR_USER:
1022 throw new UserBlockedError( $wgUser->getBlock() );
1023
1024 case self::AS_IMAGE_REDIRECT_ANON:
1025 case self::AS_IMAGE_REDIRECT_LOGGED:
1026 throw new PermissionsError( 'upload' );
1027
1028 case self::AS_READ_ONLY_PAGE_ANON:
1029 case self::AS_READ_ONLY_PAGE_LOGGED:
1030 throw new PermissionsError( 'edit' );
1031
1032 case self::AS_READ_ONLY_PAGE:
1033 throw new ReadOnlyError;
1034
1035 case self::AS_RATE_LIMITED:
1036 throw new ThrottledError();
1037
1038 case self::AS_NO_CREATE_PERMISSION:
1039 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1040 throw new PermissionsError( $permission );
1041
1042 }
1043 return false;
1044 }
1045
1046 /**
1047 * Attempt submission (no UI)
1048 *
1049 * @param $result
1050 * @param $bot bool
1051 *
1052 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1053 *
1054 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1055 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1056 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1057 */
1058 function internalAttemptSave( &$result, $bot = false ) {
1059 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
1060 global $wgMaxArticleSize;
1061
1062 $status = Status::newGood();
1063
1064 wfProfileIn( __METHOD__ );
1065 wfProfileIn( __METHOD__ . '-checks' );
1066
1067 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1068 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1069 $status->fatal( 'hookaborted' );
1070 $status->value = self::AS_HOOK_ERROR;
1071 wfProfileOut( __METHOD__ . '-checks' );
1072 wfProfileOut( __METHOD__ );
1073 return $status;
1074 }
1075
1076 # Check image redirect
1077 if ( $this->mTitle->getNamespace() == NS_FILE &&
1078 Title::newFromRedirect( $this->textbox1 ) instanceof Title &&
1079 !$wgUser->isAllowed( 'upload' ) ) {
1080 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1081 $status->setResult( false, $code );
1082
1083 wfProfileOut( __METHOD__ . '-checks' );
1084 wfProfileOut( __METHOD__ );
1085
1086 return $status;
1087 }
1088
1089 # Check for spam
1090 $match = self::matchSummarySpamRegex( $this->summary );
1091 if ( $match === false ) {
1092 $match = self::matchSpamRegex( $this->textbox1 );
1093 }
1094 if ( $match !== false ) {
1095 $result['spam'] = $match;
1096 $ip = $wgRequest->getIP();
1097 $pdbk = $this->mTitle->getPrefixedDBkey();
1098 $match = str_replace( "\n", '', $match );
1099 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1100 $status->fatal( 'spamprotectionmatch', $match );
1101 $status->value = self::AS_SPAM_ERROR;
1102 wfProfileOut( __METHOD__ . '-checks' );
1103 wfProfileOut( __METHOD__ );
1104 return $status;
1105 }
1106 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section, $this->hookError, $this->summary ) ) {
1107 # Error messages or other handling should be performed by the filter function
1108 $status->setResult( false, self::AS_FILTERING );
1109 wfProfileOut( __METHOD__ . '-checks' );
1110 wfProfileOut( __METHOD__ );
1111 return $status;
1112 }
1113 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) ) ) {
1114 # Error messages etc. could be handled within the hook...
1115 $status->fatal( 'hookaborted' );
1116 $status->value = self::AS_HOOK_ERROR;
1117 wfProfileOut( __METHOD__ . '-checks' );
1118 wfProfileOut( __METHOD__ );
1119 return $status;
1120 } elseif ( $this->hookError != '' ) {
1121 # ...or the hook could be expecting us to produce an error
1122 $status->fatal( 'hookaborted' );
1123 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1124 wfProfileOut( __METHOD__ . '-checks' );
1125 wfProfileOut( __METHOD__ );
1126 return $status;
1127 }
1128
1129 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1130 // Auto-block user's IP if the account was "hard" blocked
1131 $wgUser->spreadAnyEditBlock();
1132 # Check block state against master, thus 'false'.
1133 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1134 wfProfileOut( __METHOD__ . '-checks' );
1135 wfProfileOut( __METHOD__ );
1136 return $status;
1137 }
1138
1139 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1140 if ( $this->kblength > $wgMaxArticleSize ) {
1141 // Error will be displayed by showEditForm()
1142 $this->tooBig = true;
1143 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1144 wfProfileOut( __METHOD__ . '-checks' );
1145 wfProfileOut( __METHOD__ );
1146 return $status;
1147 }
1148
1149 if ( !$wgUser->isAllowed( 'edit' ) ) {
1150 if ( $wgUser->isAnon() ) {
1151 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1152 wfProfileOut( __METHOD__ . '-checks' );
1153 wfProfileOut( __METHOD__ );
1154 return $status;
1155 } else {
1156 $status->fatal( 'readonlytext' );
1157 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1158 wfProfileOut( __METHOD__ . '-checks' );
1159 wfProfileOut( __METHOD__ );
1160 return $status;
1161 }
1162 }
1163
1164 if ( wfReadOnly() ) {
1165 $status->fatal( 'readonlytext' );
1166 $status->value = self::AS_READ_ONLY_PAGE;
1167 wfProfileOut( __METHOD__ . '-checks' );
1168 wfProfileOut( __METHOD__ );
1169 return $status;
1170 }
1171 if ( $wgUser->pingLimiter() ) {
1172 $status->fatal( 'actionthrottledtext' );
1173 $status->value = self::AS_RATE_LIMITED;
1174 wfProfileOut( __METHOD__ . '-checks' );
1175 wfProfileOut( __METHOD__ );
1176 return $status;
1177 }
1178
1179 # If the article has been deleted while editing, don't save it without
1180 # confirmation
1181 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1182 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1183 wfProfileOut( __METHOD__ . '-checks' );
1184 wfProfileOut( __METHOD__ );
1185 return $status;
1186 }
1187
1188 wfProfileOut( __METHOD__ . '-checks' );
1189
1190 # If article is new, insert it.
1191 $aid = $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
1192 $new = ( $aid == 0 );
1193
1194 if ( $new ) {
1195 // Late check for create permission, just in case *PARANOIA*
1196 if ( !$this->mTitle->userCan( 'create' ) ) {
1197 $status->fatal( 'nocreatetext' );
1198 $status->value = self::AS_NO_CREATE_PERMISSION;
1199 wfDebug( __METHOD__ . ": no create permission\n" );
1200 wfProfileOut( __METHOD__ );
1201 return $status;
1202 }
1203
1204 # Don't save a new article if it's blank.
1205 if ( $this->textbox1 == '' ) {
1206 $status->setResult( false, self::AS_BLANK_ARTICLE );
1207 wfProfileOut( __METHOD__ );
1208 return $status;
1209 }
1210
1211 // Run post-section-merge edit filter
1212 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1, &$this->hookError, $this->summary ) ) ) {
1213 # Error messages etc. could be handled within the hook...
1214 $status->fatal( 'hookaborted' );
1215 $status->value = self::AS_HOOK_ERROR;
1216 wfProfileOut( __METHOD__ );
1217 return $status;
1218 } elseif ( $this->hookError != '' ) {
1219 # ...or the hook could be expecting us to produce an error
1220 $status->fatal( 'hookaborted' );
1221 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1222 wfProfileOut( __METHOD__ );
1223 return $status;
1224 }
1225
1226 $text = $this->textbox1;
1227 $result['sectionanchor'] = '';
1228 if ( $this->section == 'new' ) {
1229 if ( $this->sectiontitle !== '' ) {
1230 // Insert the section title above the content.
1231 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle ) . "\n\n" . $text;
1232
1233 // Jump to the new section
1234 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1235
1236 // If no edit summary was specified, create one automatically from the section
1237 // title and have it link to the new section. Otherwise, respect the summary as
1238 // passed.
1239 if ( $this->summary === '' ) {
1240 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1241 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1242 }
1243 } elseif ( $this->summary !== '' ) {
1244 // Insert the section title above the content.
1245 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary ) . "\n\n" . $text;
1246
1247 // Jump to the new section
1248 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1249
1250 // Create a link to the new section from the edit summary.
1251 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1252 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
1253 }
1254 }
1255
1256 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1257
1258 } else {
1259
1260 # Article exists. Check for edit conflict.
1261
1262 $this->mArticle->clear(); # Force reload of dates, etc.
1263 $timestamp = $this->mArticle->getTimestamp();
1264
1265 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1266
1267 if ( $timestamp != $this->edittime ) {
1268 $this->isConflict = true;
1269 if ( $this->section == 'new' ) {
1270 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
1271 $this->mArticle->getComment() == $this->summary ) {
1272 // Probably a duplicate submission of a new comment.
1273 // This can happen when squid resends a request after
1274 // a timeout but the first one actually went through.
1275 wfDebug( __METHOD__ . ": duplicate new section submission; trigger edit conflict!\n" );
1276 } else {
1277 // New comment; suppress conflict.
1278 $this->isConflict = false;
1279 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1280 }
1281 } elseif ( $this->section == '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime ) ) {
1282 # Suppress edit conflict with self, except for section edits where merging is required.
1283 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1284 $this->isConflict = false;
1285 }
1286 }
1287
1288 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1289 // backwards compatibility with old forms/bots).
1290 if ( $this->sectiontitle !== '' ) {
1291 $sectionTitle = $this->sectiontitle;
1292 } else {
1293 $sectionTitle = $this->summary;
1294 }
1295
1296 if ( $this->isConflict ) {
1297 wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1298 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $sectionTitle, $this->edittime );
1299 } else {
1300 wfDebug( __METHOD__ . ": getting section '$this->section'\n" );
1301 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $sectionTitle );
1302 }
1303 if ( is_null( $text ) ) {
1304 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1305 $this->isConflict = true;
1306 $text = $this->textbox1; // do not try to merge here!
1307 } elseif ( $this->isConflict ) {
1308 # Attempt merge
1309 if ( $this->mergeChangesInto( $text ) ) {
1310 // Successful merge! Maybe we should tell the user the good news?
1311 $this->isConflict = false;
1312 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1313 } else {
1314 $this->section = '';
1315 $this->textbox1 = $text;
1316 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1317 }
1318 }
1319
1320 if ( $this->isConflict ) {
1321 $status->setResult( false, self::AS_CONFLICT_DETECTED );
1322 wfProfileOut( __METHOD__ );
1323 return $status;
1324 }
1325
1326 // Run post-section-merge edit filter
1327 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError, $this->summary ) ) ) {
1328 # Error messages etc. could be handled within the hook...
1329 $status->fatal( 'hookaborted' );
1330 $status->value = self::AS_HOOK_ERROR;
1331 wfProfileOut( __METHOD__ );
1332 return $status;
1333 } elseif ( $this->hookError != '' ) {
1334 # ...or the hook could be expecting us to produce an error
1335 $status->fatal( 'hookaborted' );
1336 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1337 wfProfileOut( __METHOD__ );
1338 return $status;
1339 }
1340
1341 # Handle the user preference to force summaries here, but not for null edits
1342 if ( $this->section != 'new' && !$this->allowBlankSummary
1343 && $this->getOriginalContent() != $text
1344 && !Title::newFromRedirect( $text ) ) # check if it's not a redirect
1345 {
1346 if ( md5( $this->summary ) == $this->autoSumm ) {
1347 $this->missingSummary = true;
1348 $status->fatal( 'missingsummary' );
1349 $status->value = self::AS_SUMMARY_NEEDED;
1350 wfProfileOut( __METHOD__ );
1351 return $status;
1352 }
1353 }
1354
1355 # And a similar thing for new sections
1356 if ( $this->section == 'new' && !$this->allowBlankSummary ) {
1357 if ( trim( $this->summary ) == '' ) {
1358 $this->missingSummary = true;
1359 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1360 $status->value = self::AS_SUMMARY_NEEDED;
1361 wfProfileOut( __METHOD__ );
1362 return $status;
1363 }
1364 }
1365
1366 # All's well
1367 wfProfileIn( __METHOD__ . '-sectionanchor' );
1368 $sectionanchor = '';
1369 if ( $this->section == 'new' ) {
1370 if ( $this->textbox1 == '' ) {
1371 $this->missingComment = true;
1372 $status->fatal( 'missingcommenttext' );
1373 $status->value = self::AS_TEXTBOX_EMPTY;
1374 wfProfileOut( __METHOD__ . '-sectionanchor' );
1375 wfProfileOut( __METHOD__ );
1376 return $status;
1377 }
1378 if ( $this->sectiontitle !== '' ) {
1379 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1380 // If no edit summary was specified, create one automatically from the section
1381 // title and have it link to the new section. Otherwise, respect the summary as
1382 // passed.
1383 if ( $this->summary === '' ) {
1384 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1385 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1386 }
1387 } elseif ( $this->summary !== '' ) {
1388 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1389 # This is a new section, so create a link to the new section
1390 # in the revision summary.
1391 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1392 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
1393 }
1394 } elseif ( $this->section != '' ) {
1395 # Try to get a section anchor from the section source, redirect to edited section if header found
1396 # XXX: might be better to integrate this into Article::replaceSection
1397 # for duplicate heading checking and maybe parsing
1398 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1399 # we can't deal with anchors, includes, html etc in the header for now,
1400 # headline would need to be parsed to improve this
1401 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1402 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1403 }
1404 }
1405 $result['sectionanchor'] = $sectionanchor;
1406 wfProfileOut( __METHOD__ . '-sectionanchor' );
1407
1408 // Save errors may fall down to the edit form, but we've now
1409 // merged the section into full text. Clear the section field
1410 // so that later submission of conflict forms won't try to
1411 // replace that into a duplicated mess.
1412 $this->textbox1 = $text;
1413 $this->section = '';
1414
1415 $status->value = self::AS_SUCCESS_UPDATE;
1416 }
1417
1418 // Check for length errors again now that the section is merged in
1419 $this->kblength = (int)( strlen( $text ) / 1024 );
1420 if ( $this->kblength > $wgMaxArticleSize ) {
1421 $this->tooBig = true;
1422 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
1423 wfProfileOut( __METHOD__ );
1424 return $status;
1425 }
1426
1427 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1428 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
1429 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
1430 ( $bot ? EDIT_FORCE_BOT : 0 );
1431
1432 $doEditStatus = $this->mArticle->doEdit( $text, $this->summary, $flags );
1433
1434 if ( $doEditStatus->isOK() ) {
1435 $result['redirect'] = Title::newFromRedirect( $text ) !== null;
1436 $this->commitWatch();
1437 wfProfileOut( __METHOD__ );
1438 return $status;
1439 } else {
1440 $this->isConflict = true;
1441 $doEditStatus->value = self::AS_END; // Destroys data doEdit() put in $status->value but who cares
1442 wfProfileOut( __METHOD__ );
1443 return $doEditStatus;
1444 }
1445 }
1446
1447 /**
1448 * Commit the change of watch status
1449 */
1450 protected function commitWatch() {
1451 global $wgUser;
1452 if ( $this->watchthis xor $this->mTitle->userIsWatching() ) {
1453 $dbw = wfGetDB( DB_MASTER );
1454 $dbw->begin();
1455 if ( $this->watchthis ) {
1456 WatchAction::doWatch( $this->mTitle, $wgUser );
1457 } else {
1458 WatchAction::doUnwatch( $this->mTitle, $wgUser );
1459 }
1460 $dbw->commit();
1461 }
1462 }
1463
1464 /**
1465 * Check if no edits were made by other users since
1466 * the time a user started editing the page. Limit to
1467 * 50 revisions for the sake of performance.
1468 *
1469 * @param $id int
1470 * @param $edittime string
1471 *
1472 * @return bool
1473 */
1474 protected function userWasLastToEdit( $id, $edittime ) {
1475 if ( !$id ) return false;
1476 $dbw = wfGetDB( DB_MASTER );
1477 $res = $dbw->select( 'revision',
1478 'rev_user',
1479 array(
1480 'rev_page' => $this->mTitle->getArticleId(),
1481 'rev_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $edittime ) )
1482 ),
1483 __METHOD__,
1484 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1485 foreach ( $res as $row ) {
1486 if ( $row->rev_user != $id ) {
1487 return false;
1488 }
1489 }
1490 return true;
1491 }
1492
1493 /**
1494 * @private
1495 * @todo document
1496 *
1497 * @parma $editText string
1498 *
1499 * @return bool
1500 */
1501 function mergeChangesInto( &$editText ) {
1502 wfProfileIn( __METHOD__ );
1503
1504 $db = wfGetDB( DB_MASTER );
1505
1506 // This is the revision the editor started from
1507 $baseRevision = $this->getBaseRevision();
1508 if ( is_null( $baseRevision ) ) {
1509 wfProfileOut( __METHOD__ );
1510 return false;
1511 }
1512 $baseText = $baseRevision->getText();
1513
1514 // The current state, we want to merge updates into it
1515 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
1516 if ( is_null( $currentRevision ) ) {
1517 wfProfileOut( __METHOD__ );
1518 return false;
1519 }
1520 $currentText = $currentRevision->getText();
1521
1522 $result = '';
1523 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1524 $editText = $result;
1525 wfProfileOut( __METHOD__ );
1526 return true;
1527 } else {
1528 wfProfileOut( __METHOD__ );
1529 return false;
1530 }
1531 }
1532
1533 /**
1534 * @return Revision
1535 */
1536 function getBaseRevision() {
1537 if ( !$this->mBaseRevision ) {
1538 $db = wfGetDB( DB_MASTER );
1539 $baseRevision = Revision::loadFromTimestamp(
1540 $db, $this->mTitle, $this->edittime );
1541 return $this->mBaseRevision = $baseRevision;
1542 } else {
1543 return $this->mBaseRevision;
1544 }
1545 }
1546
1547 /**
1548 * Check given input text against $wgSpamRegex, and return the text of the first match.
1549 *
1550 * @param $text string
1551 *
1552 * @return string|bool matching string or false
1553 */
1554 public static function matchSpamRegex( $text ) {
1555 global $wgSpamRegex;
1556 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1557 $regexes = (array)$wgSpamRegex;
1558 return self::matchSpamRegexInternal( $text, $regexes );
1559 }
1560
1561 /**
1562 * Check given input text against $wgSpamRegex, and return the text of the first match.
1563 *
1564 * @parma $text string
1565 *
1566 * @return string|bool matching string or false
1567 */
1568 public static function matchSummarySpamRegex( $text ) {
1569 global $wgSummarySpamRegex;
1570 $regexes = (array)$wgSummarySpamRegex;
1571 return self::matchSpamRegexInternal( $text, $regexes );
1572 }
1573
1574 /**
1575 * @param $text string
1576 * @param $regexes array
1577 * @return bool|string
1578 */
1579 protected static function matchSpamRegexInternal( $text, $regexes ) {
1580 foreach ( $regexes as $regex ) {
1581 $matches = array();
1582 if ( preg_match( $regex, $text, $matches ) ) {
1583 return $matches[0];
1584 }
1585 }
1586 return false;
1587 }
1588
1589 function setHeaders() {
1590 global $wgOut, $wgUser;
1591
1592 $wgOut->addModules( 'mediawiki.action.edit' );
1593
1594 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1595 $wgOut->addModules( 'mediawiki.legacy.preview' );
1596 }
1597 // Bug #19334: textarea jumps when editing articles in IE8
1598 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1599
1600 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1601
1602 # Enabled article-related sidebar, toplinks, etc.
1603 $wgOut->setArticleRelated( true );
1604
1605 if ( $this->isConflict ) {
1606 $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1607 } elseif ( $this->section != '' ) {
1608 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
1609 $wgOut->setPageTitle( wfMessage( $msg, $this->getContextTitle()->getPrefixedText() ) );
1610 } else {
1611 # Use the title defined by DISPLAYTITLE magic word when present
1612 if ( isset( $this->mParserOutput )
1613 && ( $dt = $this->mParserOutput->getDisplayTitle() ) !== false ) {
1614 $title = $dt;
1615 } else {
1616 $title = $this->getContextTitle()->getPrefixedText();
1617 }
1618 $wgOut->setPageTitle( wfMessage( 'editing', $title ) );
1619 }
1620 }
1621
1622 /**
1623 * Show all applicable editing introductions
1624 */
1625 protected function showIntro() {
1626 global $wgOut, $wgUser;
1627 if ( $this->suppressIntro ) {
1628 return;
1629 }
1630
1631 $namespace = $this->mTitle->getNamespace();
1632
1633 if ( $namespace == NS_MEDIAWIKI ) {
1634 # Show a warning if editing an interface message
1635 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1636 }
1637
1638 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1639 # Show log extract when the user is currently blocked
1640 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
1641 $parts = explode( '/', $this->mTitle->getText(), 2 );
1642 $username = $parts[0];
1643 $user = User::newFromName( $username, false /* allow IP users*/ );
1644 $ip = User::isIP( $username );
1645 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1646 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1647 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1648 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1649 LogEventsList::showLogExtract(
1650 $wgOut,
1651 'block',
1652 $user->getUserPage(),
1653 '',
1654 array(
1655 'lim' => 1,
1656 'showIfEmpty' => false,
1657 'msgKey' => array(
1658 'blocked-notice-logextract',
1659 $user->getName() # Support GENDER in notice
1660 )
1661 )
1662 );
1663 }
1664 }
1665 # Try to add a custom edit intro, or use the standard one if this is not possible.
1666 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
1667 if ( $wgUser->isLoggedIn() ) {
1668 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1669 } else {
1670 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1671 }
1672 }
1673 # Give a notice if the user is editing a deleted/moved page...
1674 if ( !$this->mTitle->exists() ) {
1675 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
1676 '', array( 'lim' => 10,
1677 'conds' => array( "log_action != 'revision'" ),
1678 'showIfEmpty' => false,
1679 'msgKey' => array( 'recreate-moveddeleted-warn' ) )
1680 );
1681 }
1682 }
1683
1684 /**
1685 * Attempt to show a custom editing introduction, if supplied
1686 *
1687 * @return bool
1688 */
1689 protected function showCustomIntro() {
1690 if ( $this->editintro ) {
1691 $title = Title::newFromText( $this->editintro );
1692 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
1693 global $wgOut;
1694 // Added using template syntax, to take <noinclude>'s into account.
1695 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle );
1696 return true;
1697 } else {
1698 return false;
1699 }
1700 } else {
1701 return false;
1702 }
1703 }
1704
1705 /**
1706 * Send the edit form and related headers to $wgOut
1707 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1708 * during form output near the top, for captchas and the like.
1709 */
1710 function showEditForm( $formCallback = null ) {
1711 global $wgOut, $wgUser;
1712
1713 wfProfileIn( __METHOD__ );
1714
1715 # need to parse the preview early so that we know which templates are used,
1716 # otherwise users with "show preview after edit box" will get a blank list
1717 # we parse this near the beginning so that setHeaders can do the title
1718 # setting work instead of leaving it in getPreviewText
1719 $previewOutput = '';
1720 if ( $this->formtype == 'preview' ) {
1721 $previewOutput = $this->getPreviewText();
1722 }
1723
1724 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
1725
1726 $this->setHeaders();
1727
1728 if ( $this->showHeader() === false ) {
1729 wfProfileOut( __METHOD__ );
1730 return;
1731 }
1732
1733 $wgOut->addHTML( $this->editFormPageTop );
1734
1735 if ( $wgUser->getOption( 'previewontop' ) ) {
1736 $this->displayPreviewArea( $previewOutput, true );
1737 }
1738
1739 $wgOut->addHTML( $this->editFormTextTop );
1740
1741 $showToolbar = true;
1742 if ( $this->wasDeletedSinceLastEdit() ) {
1743 if ( $this->formtype == 'save' ) {
1744 // Hide the toolbar and edit area, user can click preview to get it back
1745 // Add an confirmation checkbox and explanation.
1746 $showToolbar = false;
1747 } else {
1748 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1749 'deletedwhileediting' );
1750 }
1751 }
1752
1753 $wgOut->addHTML( Html::openElement( 'form', array( 'id' => 'editform', 'name' => 'editform',
1754 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1755 'enctype' => 'multipart/form-data' ) ) );
1756
1757 if ( is_callable( $formCallback ) ) {
1758 call_user_func_array( $formCallback, array( &$wgOut ) );
1759 }
1760
1761 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1762
1763 // Put these up at the top to ensure they aren't lost on early form submission
1764 $this->showFormBeforeText();
1765
1766 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
1767 $username = $this->lastDelete->user_name;
1768 $comment = $this->lastDelete->log_comment;
1769
1770 // It is better to not parse the comment at all than to have templates expanded in the middle
1771 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1772 $key = $comment === ''
1773 ? 'confirmrecreate-noreason'
1774 : 'confirmrecreate';
1775 $wgOut->addHTML(
1776 '<div class="mw-confirm-recreate">' .
1777 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1778 Xml::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1779 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1780 ) .
1781 '</div>'
1782 );
1783 }
1784
1785 # If a blank edit summary was previously provided, and the appropriate
1786 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1787 # user being bounced back more than once in the event that a summary
1788 # is not required.
1789 #####
1790 # For a bit more sophisticated detection of blank summaries, hash the
1791 # automatic one and pass that in the hidden field wpAutoSummary.
1792 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
1793 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
1794 }
1795
1796 if ( $this->hasPresetSummary ) {
1797 // If a summary has been preset using &summary= we dont want to prompt for
1798 // a different summary. Only prompt for a summary if the summary is blanked.
1799 // (Bug 17416)
1800 $this->autoSumm = md5( '' );
1801 }
1802
1803 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1804 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
1805
1806 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
1807
1808 if ( $this->section == 'new' ) {
1809 $this->showSummaryInput( true, $this->summary );
1810 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
1811 }
1812
1813 $wgOut->addHTML( $this->editFormTextBeforeContent );
1814
1815 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
1816 $wgOut->addHTML( EditPage::getEditToolbar() );
1817 }
1818
1819 if ( $this->isConflict ) {
1820 // In an edit conflict bypass the overrideable content form method
1821 // and fallback to the raw wpTextbox1 since editconflicts can't be
1822 // resolved between page source edits and custom ui edits using the
1823 // custom edit ui.
1824 $this->textbox2 = $this->textbox1;
1825 $this->textbox1 = $this->getCurrentText();
1826
1827 $this->showTextbox1();
1828 } else {
1829 $this->showContentForm();
1830 }
1831
1832 $wgOut->addHTML( $this->editFormTextAfterContent );
1833
1834 $wgOut->addWikiText( $this->getCopywarn() );
1835
1836 $wgOut->addHTML( $this->editFormTextAfterWarn );
1837
1838 $this->showStandardInputs();
1839
1840 $this->showFormAfterText();
1841
1842 $this->showTosSummary();
1843
1844 $this->showEditTools();
1845
1846 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
1847
1848 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
1849 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
1850
1851 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
1852 Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
1853
1854 if ( $this->isConflict ) {
1855 $this->showConflict();
1856 }
1857
1858 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
1859
1860 if ( !$wgUser->getOption( 'previewontop' ) ) {
1861 $this->displayPreviewArea( $previewOutput, false );
1862 }
1863
1864 wfProfileOut( __METHOD__ );
1865 }
1866
1867 /**
1868 * Extract the section title from current section text, if any.
1869 *
1870 * @param string $text
1871 * @return Mixed|string or false
1872 */
1873 public static function extractSectionTitle( $text ) {
1874 preg_match( "/^(=+)(.+)\\1(\n|$)/i", $text, $matches );
1875 if ( !empty( $matches[2] ) ) {
1876 global $wgParser;
1877 return $wgParser->stripSectionName( trim( $matches[2] ) );
1878 } else {
1879 return false;
1880 }
1881 }
1882
1883 protected function showHeader() {
1884 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1885
1886 if ( $this->mTitle->isTalkPage() ) {
1887 $wgOut->addWikiMsg( 'talkpagetext' );
1888 }
1889
1890 # Optional notices on a per-namespace and per-page basis
1891 $editnotice_ns = 'editnotice-' . $this->mTitle->getNamespace();
1892 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
1893 if ( $editnotice_ns_message->exists() ) {
1894 $wgOut->addWikiText( $editnotice_ns_message->plain() );
1895 }
1896 if ( MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
1897 $parts = explode( '/', $this->mTitle->getDBkey() );
1898 $editnotice_base = $editnotice_ns;
1899 while ( count( $parts ) > 0 ) {
1900 $editnotice_base .= '-' . array_shift( $parts );
1901 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
1902 if ( $editnotice_base_msg->exists() ) {
1903 $wgOut->addWikiText( $editnotice_base_msg->plain() );
1904 }
1905 }
1906 } else {
1907 # Even if there are no subpages in namespace, we still don't want / in MW ns.
1908 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle->getDBkey() );
1909 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
1910 if ( $editnoticeMsg->exists() ) {
1911 $wgOut->addWikiText( $editnoticeMsg->plain() );
1912 }
1913 }
1914
1915 if ( $this->isConflict ) {
1916 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1917 $this->edittime = $this->mArticle->getTimestamp();
1918 } else {
1919 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
1920 // We use $this->section to much before this and getVal('wgSection') directly in other places
1921 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1922 // Someone is welcome to try refactoring though
1923 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1924 return false;
1925 }
1926
1927 if ( $this->section != '' && $this->section != 'new' ) {
1928 if ( !$this->summary && !$this->preview && !$this->diff ) {
1929 $sectionTitle = self::extractSectionTitle( $this->textbox1 );
1930 if ( $sectionTitle !== false ) {
1931 $this->summary = "/* $sectionTitle */ ";
1932 }
1933 }
1934 }
1935
1936 if ( $this->missingComment ) {
1937 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1938 }
1939
1940 if ( $this->missingSummary && $this->section != 'new' ) {
1941 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1942 }
1943
1944 if ( $this->missingSummary && $this->section == 'new' ) {
1945 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1946 }
1947
1948 if ( $this->hookError !== '' ) {
1949 $wgOut->addWikiText( $this->hookError );
1950 }
1951
1952 if ( !$this->checkUnicodeCompliantBrowser() ) {
1953 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1954 }
1955
1956 if ( $this->section != 'new' ) {
1957 $revision = $this->mArticle->getRevisionFetched();
1958 if ( $revision ) {
1959 // Let sysop know that this will make private content public if saved
1960
1961 if ( !$revision->userCan( Revision::DELETED_TEXT ) ) {
1962 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1963 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
1964 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1965 }
1966
1967 if ( !$revision->isCurrent() ) {
1968 $this->mArticle->setOldSubtitle( $revision->getId() );
1969 $wgOut->addWikiMsg( 'editingold' );
1970 }
1971 } elseif ( $this->mTitle->exists() ) {
1972 // Something went wrong
1973
1974 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
1975 array( 'missing-article', $this->mTitle->getPrefixedText(),
1976 wfMsgNoTrans( 'missingarticle-rev', $this->oldid ) ) );
1977 }
1978 }
1979 }
1980
1981 if ( wfReadOnly() ) {
1982 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1983 } elseif ( $wgUser->isAnon() ) {
1984 if ( $this->formtype != 'preview' ) {
1985 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
1986 } else {
1987 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
1988 }
1989 } else {
1990 if ( $this->isCssJsSubpage ) {
1991 # Check the skin exists
1992 if ( $this->isWrongCaseCssJsPage ) {
1993 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
1994 }
1995 if ( $this->formtype !== 'preview' ) {
1996 if ( $this->isCssSubpage )
1997 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
1998 if ( $this->isJsSubpage )
1999 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2000 }
2001 }
2002 }
2003
2004 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
2005 # Is the title semi-protected?
2006 if ( $this->mTitle->isSemiProtected() ) {
2007 $noticeMsg = 'semiprotectedpagewarning';
2008 } else {
2009 # Then it must be protected based on static groups (regular)
2010 $noticeMsg = 'protectedpagewarning';
2011 }
2012 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2013 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2014 }
2015 if ( $this->mTitle->isCascadeProtected() ) {
2016 # Is this page under cascading protection from some source pages?
2017 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2018 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2019 $cascadeSourcesCount = count( $cascadeSources );
2020 if ( $cascadeSourcesCount > 0 ) {
2021 # Explain, and list the titles responsible
2022 foreach ( $cascadeSources as $page ) {
2023 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2024 }
2025 }
2026 $notice .= '</div>';
2027 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2028 }
2029 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2030 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2031 array( 'lim' => 1,
2032 'showIfEmpty' => false,
2033 'msgKey' => array( 'titleprotectedwarning' ),
2034 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2035 }
2036
2037 if ( $this->kblength === false ) {
2038 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2039 }
2040
2041 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2042 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2043 array( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2044 } else {
2045 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2046 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2047 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 ) )
2048 );
2049 }
2050 }
2051 }
2052
2053 /**
2054 * Standard summary input and label (wgSummary), abstracted so EditPage
2055 * subclasses may reorganize the form.
2056 * Note that you do not need to worry about the label's for=, it will be
2057 * inferred by the id given to the input. You can remove them both by
2058 * passing array( 'id' => false ) to $userInputAttrs.
2059 *
2060 * @param $summary string The value of the summary input
2061 * @param $labelText string The html to place inside the label
2062 * @param $inputAttrs array of attrs to use on the input
2063 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2064 *
2065 * @return array An array in the format array( $label, $input )
2066 */
2067 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2068 // Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
2069 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2070 'id' => 'wpSummary',
2071 'maxlength' => '200',
2072 'tabindex' => '1',
2073 'size' => 60,
2074 'spellcheck' => 'true',
2075 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2076
2077 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2078 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2079 'id' => "wpSummaryLabel"
2080 );
2081
2082 $label = null;
2083 if ( $labelText ) {
2084 $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2085 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2086 }
2087
2088 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2089
2090 return array( $label, $input );
2091 }
2092
2093 /**
2094 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2095 * up top, or false if this is the comment summary
2096 * down below the textarea
2097 * @param $summary String: The text of the summary to display
2098 * @return String
2099 */
2100 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2101 global $wgOut, $wgContLang;
2102 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2103 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2104 if ( $isSubjectPreview ) {
2105 if ( $this->nosummary ) {
2106 return;
2107 }
2108 } else {
2109 if ( !$this->mShowSummaryField ) {
2110 return;
2111 }
2112 }
2113 $summary = $wgContLang->recodeForEdit( $summary );
2114 $labelText = wfMsgExt( $isSubjectPreview ? 'subject' : 'summary', 'parseinline' );
2115 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2116 $wgOut->addHTML( "{$label} {$input}" );
2117 }
2118
2119 /**
2120 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2121 * up top, or false if this is the comment summary
2122 * down below the textarea
2123 * @param $summary String: the text of the summary to display
2124 * @return String
2125 */
2126 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2127 if ( !$summary || ( !$this->preview && !$this->diff ) )
2128 return "";
2129
2130 global $wgParser;
2131
2132 if ( $isSubjectPreview )
2133 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
2134
2135 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
2136
2137 $summary = wfMsgExt( $message, 'parseinline' ) . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
2138 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2139 }
2140
2141 protected function showFormBeforeText() {
2142 global $wgOut;
2143 $section = htmlspecialchars( $this->section );
2144 $wgOut->addHTML( <<<HTML
2145 <input type='hidden' value="{$section}" name="wpSection" />
2146 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2147 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2148 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2149
2150 HTML
2151 );
2152 if ( !$this->checkUnicodeCompliantBrowser() )
2153 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
2154 }
2155
2156 protected function showFormAfterText() {
2157 global $wgOut, $wgUser;
2158 /**
2159 * To make it harder for someone to slip a user a page
2160 * which submits an edit form to the wiki without their
2161 * knowledge, a random token is associated with the login
2162 * session. If it's not passed back with the submission,
2163 * we won't save the page, or render user JavaScript and
2164 * CSS previews.
2165 *
2166 * For anon editors, who may not have a session, we just
2167 * include the constant suffix to prevent editing from
2168 * broken text-mangling proxies.
2169 */
2170 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2171 }
2172
2173 /**
2174 * Subpage overridable method for printing the form for page content editing
2175 * By default this simply outputs wpTextbox1
2176 * Subclasses can override this to provide a custom UI for editing;
2177 * be it a form, or simply wpTextbox1 with a modified content that will be
2178 * reverse modified when extracted from the post data.
2179 * Note that this is basically the inverse for importContentFormData
2180 */
2181 protected function showContentForm() {
2182 $this->showTextbox1();
2183 }
2184
2185 /**
2186 * Method to output wpTextbox1
2187 * The $textoverride method can be used by subclasses overriding showContentForm
2188 * to pass back to this method.
2189 *
2190 * @param $customAttribs array of html attributes to use in the textarea
2191 * @param $textoverride String: optional text to override $this->textarea1 with
2192 */
2193 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2194 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2195 $attribs = array( 'style' => 'display:none;' );
2196 } else {
2197 $classes = array(); // Textarea CSS
2198 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
2199 # Is the title semi-protected?
2200 if ( $this->mTitle->isSemiProtected() ) {
2201 $classes[] = 'mw-textarea-sprotected';
2202 } else {
2203 # Then it must be protected based on static groups (regular)
2204 $classes[] = 'mw-textarea-protected';
2205 }
2206 # Is the title cascade-protected?
2207 if ( $this->mTitle->isCascadeProtected() ) {
2208 $classes[] = 'mw-textarea-cprotected';
2209 }
2210 }
2211
2212 $attribs = array( 'tabindex' => 1 );
2213
2214 if ( is_array( $customAttribs ) ) {
2215 $attribs += $customAttribs;
2216 }
2217
2218 if ( count( $classes ) ) {
2219 if ( isset( $attribs['class'] ) ) {
2220 $classes[] = $attribs['class'];
2221 }
2222 $attribs['class'] = implode( ' ', $classes );
2223 }
2224 }
2225
2226 $this->showTextbox( $textoverride !== null ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
2227 }
2228
2229 protected function showTextbox2() {
2230 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2231 }
2232
2233 protected function showTextbox( $content, $name, $customAttribs = array() ) {
2234 global $wgOut, $wgUser;
2235
2236 $wikitext = $this->safeUnicodeOutput( $content );
2237 if ( strval( $wikitext ) !== '' ) {
2238 // Ensure there's a newline at the end, otherwise adding lines
2239 // is awkward.
2240 // But don't add a newline if the ext is empty, or Firefox in XHTML
2241 // mode will show an extra newline. A bit annoying.
2242 $wikitext .= "\n";
2243 }
2244
2245 $attribs = $customAttribs + array(
2246 'accesskey' => ',',
2247 'id' => $name,
2248 'cols' => $wgUser->getIntOption( 'cols' ),
2249 'rows' => $wgUser->getIntOption( 'rows' ),
2250 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2251 );
2252
2253 $pageLang = $this->mTitle->getPageLanguage();
2254 $attribs['lang'] = $pageLang->getCode();
2255 $attribs['dir'] = $pageLang->getDir();
2256
2257 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
2258 }
2259
2260 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2261 global $wgOut;
2262 $classes = array();
2263 if ( $isOnTop )
2264 $classes[] = 'ontop';
2265
2266 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2267
2268 if ( $this->formtype != 'preview' )
2269 $attribs['style'] = 'display: none;';
2270
2271 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
2272
2273 if ( $this->formtype == 'preview' ) {
2274 $this->showPreview( $previewOutput );
2275 }
2276
2277 $wgOut->addHTML( '</div>' );
2278
2279 if ( $this->formtype == 'diff' ) {
2280 $this->showDiff();
2281 }
2282 }
2283
2284 /**
2285 * Append preview output to $wgOut.
2286 * Includes category rendering if this is a category page.
2287 *
2288 * @param $text String: the HTML to be output for the preview.
2289 */
2290 protected function showPreview( $text ) {
2291 global $wgOut;
2292 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2293 $this->mArticle->openShowCategory();
2294 }
2295 # This hook seems slightly odd here, but makes things more
2296 # consistent for extensions.
2297 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2298 $wgOut->addHTML( $text );
2299 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2300 $this->mArticle->closeShowCategory();
2301 }
2302 }
2303
2304 /**
2305 * Get a diff between the current contents of the edit box and the
2306 * version of the page we're editing from.
2307 *
2308 * If this is a section edit, we'll replace the section as for final
2309 * save and then make a comparison.
2310 */
2311 function showDiff() {
2312 global $wgUser, $wgContLang, $wgParser, $wgOut;
2313
2314 $oldtext = $this->getOriginalContent();
2315 $newtext = $this->mArticle->replaceSection(
2316 $this->section, $this->textbox1, $this->summary, $this->edittime );
2317
2318 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2319
2320 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
2321 $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle, $wgUser, $popts );
2322
2323 if ( $oldtext !== false || $newtext != '' ) {
2324 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2325 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2326
2327 $de = new DifferenceEngine( $this->mArticle->getContext() );
2328 $de->setText( $oldtext, $newtext );
2329 $difftext = $de->getDiff( $oldtitle, $newtitle );
2330 $de->showDiffStyle();
2331 } else {
2332 $difftext = '';
2333 }
2334
2335 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2336 }
2337
2338 /**
2339 * Give a chance for site and per-namespace customizations of
2340 * terms of service summary link that might exist separately
2341 * from the copyright notice.
2342 *
2343 * This will display between the save button and the edit tools,
2344 * so should remain short!
2345 */
2346 protected function showTosSummary() {
2347 $msg = 'editpage-tos-summary';
2348 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
2349 if ( !wfMessage( $msg )->isDisabled() ) {
2350 global $wgOut;
2351 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2352 $wgOut->addWikiMsg( $msg );
2353 $wgOut->addHTML( '</div>' );
2354 }
2355 }
2356
2357 protected function showEditTools() {
2358 global $wgOut;
2359 $wgOut->addHTML( '<div class="mw-editTools">' .
2360 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2361 '</div>' );
2362 }
2363
2364 protected function getCopywarn() {
2365 global $wgRightsText;
2366 if ( $wgRightsText ) {
2367 $copywarnMsg = array( 'copyrightwarning',
2368 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2369 $wgRightsText );
2370 } else {
2371 $copywarnMsg = array( 'copyrightwarning2',
2372 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2373 }
2374 // Allow for site and per-namespace customization of contribution/copyright notice.
2375 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle, &$copywarnMsg ) );
2376
2377 return "<div id=\"editpage-copywarn\">\n" .
2378 call_user_func_array( "wfMsgNoTrans", $copywarnMsg ) . "\n</div>";
2379 }
2380
2381 protected function showStandardInputs( &$tabindex = 2 ) {
2382 global $wgOut;
2383 $wgOut->addHTML( "<div class='editOptions'>\n" );
2384
2385 if ( $this->section != 'new' ) {
2386 $this->showSummaryInput( false, $this->summary );
2387 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
2388 }
2389
2390 $checkboxes = $this->getCheckboxes( $tabindex,
2391 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
2392 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2393 $wgOut->addHTML( "<div class='editButtons'>\n" );
2394 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2395
2396 $cancel = $this->getCancelLink();
2397 if ( $cancel !== '' ) {
2398 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2399 }
2400 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2401 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2402 htmlspecialchars( wfMsg( 'edithelp' ) ) . '</a> ' .
2403 htmlspecialchars( wfMsg( 'newwindow' ) );
2404 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2405 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2406 }
2407
2408 /**
2409 * Show an edit conflict. textbox1 is already shown in showEditForm().
2410 * If you want to use another entry point to this function, be careful.
2411 */
2412 protected function showConflict() {
2413 global $wgOut;
2414
2415 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2416 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2417
2418 $de = new DifferenceEngine( $this->mArticle->getContext() );
2419 $de->setText( $this->textbox2, $this->textbox1 );
2420 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2421
2422 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2423 $this->showTextbox2();
2424 }
2425 }
2426
2427 /**
2428 * @return string
2429 */
2430 public function getCancelLink() {
2431 $cancelParams = array();
2432 if ( !$this->isConflict && $this->oldid > 0 ) {
2433 $cancelParams['oldid'] = $this->oldid;
2434 }
2435
2436 return Linker::linkKnown(
2437 $this->getContextTitle(),
2438 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2439 array( 'id' => 'mw-editform-cancel' ),
2440 $cancelParams
2441 );
2442 }
2443
2444 /**
2445 * Returns the URL to use in the form's action attribute.
2446 * This is used by EditPage subclasses when simply customizing the action
2447 * variable in the constructor is not enough. This can be used when the
2448 * EditPage lives inside of a Special page rather than a custom page action.
2449 *
2450 * @param $title Title object for which is being edited (where we go to for &action= links)
2451 * @return string
2452 */
2453 protected function getActionURL( Title $title ) {
2454 return $title->getLocalURL( array( 'action' => $this->action ) );
2455 }
2456
2457 /**
2458 * Check if a page was deleted while the user was editing it, before submit.
2459 * Note that we rely on the logging table, which hasn't been always there,
2460 * but that doesn't matter, because this only applies to brand new
2461 * deletes.
2462 */
2463 protected function wasDeletedSinceLastEdit() {
2464 if ( $this->deletedSinceEdit !== null ) {
2465 return $this->deletedSinceEdit;
2466 }
2467
2468 $this->deletedSinceEdit = false;
2469
2470 if ( $this->mTitle->isDeletedQuick() ) {
2471 $this->lastDelete = $this->getLastDelete();
2472 if ( $this->lastDelete ) {
2473 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
2474 if ( $deleteTime > $this->starttime ) {
2475 $this->deletedSinceEdit = true;
2476 }
2477 }
2478 }
2479
2480 return $this->deletedSinceEdit;
2481 }
2482
2483 protected function getLastDelete() {
2484 $dbr = wfGetDB( DB_SLAVE );
2485 $data = $dbr->selectRow(
2486 array( 'logging', 'user' ),
2487 array( 'log_type',
2488 'log_action',
2489 'log_timestamp',
2490 'log_user',
2491 'log_namespace',
2492 'log_title',
2493 'log_comment',
2494 'log_params',
2495 'log_deleted',
2496 'user_name' ),
2497 array( 'log_namespace' => $this->mTitle->getNamespace(),
2498 'log_title' => $this->mTitle->getDBkey(),
2499 'log_type' => 'delete',
2500 'log_action' => 'delete',
2501 'user_id=log_user' ),
2502 __METHOD__,
2503 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2504 );
2505 // Quick paranoid permission checks...
2506 if ( is_object( $data ) ) {
2507 if ( $data->log_deleted & LogPage::DELETED_USER )
2508 $data->user_name = wfMsgHtml( 'rev-deleted-user' );
2509 if ( $data->log_deleted & LogPage::DELETED_COMMENT )
2510 $data->log_comment = wfMsgHtml( 'rev-deleted-comment' );
2511 }
2512 return $data;
2513 }
2514
2515 /**
2516 * Get the rendered text for previewing.
2517 * @return string
2518 */
2519 function getPreviewText() {
2520 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2521
2522 wfProfileIn( __METHOD__ );
2523
2524 if ( $wgRawHtml && !$this->mTokenOk ) {
2525 // Could be an offsite preview attempt. This is very unsafe if
2526 // HTML is enabled, as it could be an attack.
2527 $parsedNote = '';
2528 if ( $this->textbox1 !== '' ) {
2529 // Do not put big scary notice, if previewing the empty
2530 // string, which happens when you initially edit
2531 // a category page, due to automatic preview-on-open.
2532 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2533 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2534 }
2535 wfProfileOut( __METHOD__ );
2536 return $parsedNote;
2537 }
2538
2539 if ( $this->mTriedSave && !$this->mTokenOk ) {
2540 if ( $this->mTokenOkExceptSuffix ) {
2541 $note = wfMsg( 'token_suffix_mismatch' );
2542 } else {
2543 $note = wfMsg( 'session_fail_preview' );
2544 }
2545 } elseif ( $this->incompleteForm ) {
2546 $note = wfMsg( 'edit_form_incomplete' );
2547 } else {
2548 $note = wfMsg( 'previewnote' );
2549 }
2550
2551 $parserOptions = ParserOptions::newFromUser( $wgUser );
2552 $parserOptions->setEditSection( false );
2553 $parserOptions->setTidy( true );
2554 $parserOptions->setIsPreview( true );
2555 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
2556
2557 # don't parse non-wikitext pages, show message about preview
2558 # 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?
2559
2560 if ( $this->isCssJsSubpage || !$this->mTitle->isWikitextPage() ) {
2561 if ( $this->mTitle->isCssJsSubpage() ) {
2562 $level = 'user';
2563 } elseif ( $this->mTitle->isCssOrJsPage() ) {
2564 $level = 'site';
2565 } else {
2566 $level = false;
2567 }
2568
2569 # Used messages to make sure grep find them:
2570 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2571 if ( $level ) {
2572 if ( preg_match( "/\\.css$/", $this->mTitle->getText() ) ) {
2573 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2574 $class = "mw-code mw-css";
2575 } elseif ( preg_match( "/\\.js$/", $this->mTitle->getText() ) ) {
2576 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2577 $class = "mw-code mw-js";
2578 } else {
2579 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2580 }
2581 }
2582
2583 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
2584 $previewHTML = $parserOutput->mText;
2585 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1 ) . "\n</pre>\n";
2586 } else {
2587 $toparse = $this->textbox1;
2588
2589 # If we're adding a comment, we need to show the
2590 # summary as the headline
2591 if ( $this->section == "new" && $this->summary != "" ) {
2592 $toparse = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary ) . "\n\n" . $toparse;
2593 }
2594
2595 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2596
2597 $parserOptions->enableLimitReport();
2598
2599 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle, $wgUser, $parserOptions );
2600 $parserOutput = $wgParser->parse( $toparse, $this->mTitle, $parserOptions );
2601
2602 $rt = Title::newFromRedirectArray( $this->textbox1 );
2603 if ( $rt ) {
2604 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
2605 } else {
2606 $previewHTML = $parserOutput->getText();
2607 }
2608
2609 $this->mParserOutput = $parserOutput;
2610 $wgOut->addParserOutputNoText( $parserOutput );
2611
2612 if ( count( $parserOutput->getWarnings() ) ) {
2613 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2614 }
2615 }
2616
2617 if ( $this->isConflict ) {
2618 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2619 } else {
2620 $conflict = '<hr />';
2621 }
2622
2623 $previewhead = "<div class='previewnote'>\n" .
2624 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2625 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2626
2627 $pageLang = $this->mTitle->getPageLanguage();
2628 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2629 'class' => 'mw-content-' . $pageLang->getDir() );
2630 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
2631
2632 wfProfileOut( __METHOD__ );
2633 return $previewhead . $previewHTML . $this->previewTextAfterContent;
2634 }
2635
2636 /**
2637 * @return Array
2638 */
2639 function getTemplates() {
2640 if ( $this->preview || $this->section != '' ) {
2641 $templates = array();
2642 if ( !isset( $this->mParserOutput ) ) {
2643 return $templates;
2644 }
2645 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
2646 foreach ( array_keys( $template ) as $dbk ) {
2647 $templates[] = Title::makeTitle( $ns, $dbk );
2648 }
2649 }
2650 return $templates;
2651 } else {
2652 return $this->mTitle->getTemplateLinksFrom();
2653 }
2654 }
2655
2656 /**
2657 * Shows a bulletin board style toolbar for common editing functions.
2658 * It can be disabled in the user preferences.
2659 * The necessary JavaScript code can be found in skins/common/edit.js.
2660 *
2661 * @return string
2662 */
2663 static function getEditToolbar() {
2664 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2665 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2666
2667 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
2668
2669 /**
2670 * $toolarray is an array of arrays each of which includes the
2671 * filename of the button image (without path), the opening
2672 * tag, the closing tag, optionally a sample text that is
2673 * inserted between the two when no selection is highlighted
2674 * and. The tip text is shown when the user moves the mouse
2675 * over the button.
2676 *
2677 * Also here: accesskeys (key), which are not used yet until
2678 * someone can figure out a way to make them work in
2679 * IE. However, we should make sure these keys are not defined
2680 * on the edit page.
2681 */
2682 $toolarray = array(
2683 array(
2684 'image' => $wgLang->getImageFile( 'button-bold' ),
2685 'id' => 'mw-editbutton-bold',
2686 'open' => '\'\'\'',
2687 'close' => '\'\'\'',
2688 'sample' => wfMsg( 'bold_sample' ),
2689 'tip' => wfMsg( 'bold_tip' ),
2690 'key' => 'B'
2691 ),
2692 array(
2693 'image' => $wgLang->getImageFile( 'button-italic' ),
2694 'id' => 'mw-editbutton-italic',
2695 'open' => '\'\'',
2696 'close' => '\'\'',
2697 'sample' => wfMsg( 'italic_sample' ),
2698 'tip' => wfMsg( 'italic_tip' ),
2699 'key' => 'I'
2700 ),
2701 array(
2702 'image' => $wgLang->getImageFile( 'button-link' ),
2703 'id' => 'mw-editbutton-link',
2704 'open' => '[[',
2705 'close' => ']]',
2706 'sample' => wfMsg( 'link_sample' ),
2707 'tip' => wfMsg( 'link_tip' ),
2708 'key' => 'L'
2709 ),
2710 array(
2711 'image' => $wgLang->getImageFile( 'button-extlink' ),
2712 'id' => 'mw-editbutton-extlink',
2713 'open' => '[',
2714 'close' => ']',
2715 'sample' => wfMsg( 'extlink_sample' ),
2716 'tip' => wfMsg( 'extlink_tip' ),
2717 'key' => 'X'
2718 ),
2719 array(
2720 'image' => $wgLang->getImageFile( 'button-headline' ),
2721 'id' => 'mw-editbutton-headline',
2722 'open' => "\n== ",
2723 'close' => " ==\n",
2724 'sample' => wfMsg( 'headline_sample' ),
2725 'tip' => wfMsg( 'headline_tip' ),
2726 'key' => 'H'
2727 ),
2728 $imagesAvailable ? array(
2729 'image' => $wgLang->getImageFile( 'button-image' ),
2730 'id' => 'mw-editbutton-image',
2731 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
2732 'close' => ']]',
2733 'sample' => wfMsg( 'image_sample' ),
2734 'tip' => wfMsg( 'image_tip' ),
2735 'key' => 'D',
2736 ) : false,
2737 $imagesAvailable ? array(
2738 'image' => $wgLang->getImageFile( 'button-media' ),
2739 'id' => 'mw-editbutton-media',
2740 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
2741 'close' => ']]',
2742 'sample' => wfMsg( 'media_sample' ),
2743 'tip' => wfMsg( 'media_tip' ),
2744 'key' => 'M'
2745 ) : false,
2746 $wgUseTeX ? array(
2747 'image' => $wgLang->getImageFile( 'button-math' ),
2748 'id' => 'mw-editbutton-math',
2749 'open' => "<math>",
2750 'close' => "</math>",
2751 'sample' => wfMsg( 'math_sample' ),
2752 'tip' => wfMsg( 'math_tip' ),
2753 'key' => 'C'
2754 ) : false,
2755 array(
2756 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2757 'id' => 'mw-editbutton-nowiki',
2758 'open' => "<nowiki>",
2759 'close' => "</nowiki>",
2760 'sample' => wfMsg( 'nowiki_sample' ),
2761 'tip' => wfMsg( 'nowiki_tip' ),
2762 'key' => 'N'
2763 ),
2764 array(
2765 'image' => $wgLang->getImageFile( 'button-sig' ),
2766 'id' => 'mw-editbutton-signature',
2767 'open' => '--~~~~',
2768 'close' => '',
2769 'sample' => '',
2770 'tip' => wfMsg( 'sig_tip' ),
2771 'key' => 'Y'
2772 ),
2773 array(
2774 'image' => $wgLang->getImageFile( 'button-hr' ),
2775 'id' => 'mw-editbutton-hr',
2776 'open' => "\n----\n",
2777 'close' => '',
2778 'sample' => '',
2779 'tip' => wfMsg( 'hr_tip' ),
2780 'key' => 'R'
2781 )
2782 );
2783
2784 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
2785 foreach ( $toolarray as $tool ) {
2786 if ( !$tool ) {
2787 continue;
2788 }
2789
2790 $params = array(
2791 $image = $wgStylePath . '/common/images/' . $tool['image'],
2792 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2793 // Older browsers show a "speedtip" type message only for ALT.
2794 // Ideally these should be different, realistically they
2795 // probably don't need to be.
2796 $tip = $tool['tip'],
2797 $open = $tool['open'],
2798 $close = $tool['close'],
2799 $sample = $tool['sample'],
2800 $cssId = $tool['id'],
2801 );
2802
2803 $script .= Xml::encodeJsCall( 'mw.toolbar.addButton', $params );
2804 }
2805
2806 // This used to be called on DOMReady from mediawiki.action.edit, which
2807 // ended up causing race conditions with the setup code above.
2808 $script .= "\n" .
2809 "// Create button bar\n" .
2810 "$(function() { mw.toolbar.init(); } );\n";
2811
2812 $script .= '});';
2813 $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
2814
2815 $toolbar = '<div id="toolbar"></div>';
2816
2817 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2818
2819 return $toolbar;
2820 }
2821
2822 /**
2823 * Returns an array of html code of the following checkboxes:
2824 * minor and watch
2825 *
2826 * @param $tabindex int Current tabindex
2827 * @param $checked Array of checkbox => bool, where bool indicates the checked
2828 * status of the checkbox
2829 *
2830 * @return array
2831 */
2832 public function getCheckboxes( &$tabindex, $checked ) {
2833 global $wgUser;
2834
2835 $checkboxes = array();
2836
2837 // don't show the minor edit checkbox if it's a new page or section
2838 if ( !$this->isNew ) {
2839 $checkboxes['minor'] = '';
2840 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2841 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2842 $attribs = array(
2843 'tabindex' => ++$tabindex,
2844 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2845 'id' => 'wpMinoredit',
2846 );
2847 $checkboxes['minor'] =
2848 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2849 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
2850 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2851 ">{$minorLabel}</label>";
2852 }
2853 }
2854
2855 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2856 $checkboxes['watch'] = '';
2857 if ( $wgUser->isLoggedIn() ) {
2858 $attribs = array(
2859 'tabindex' => ++$tabindex,
2860 'accesskey' => wfMsg( 'accesskey-watch' ),
2861 'id' => 'wpWatchthis',
2862 );
2863 $checkboxes['watch'] =
2864 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2865 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
2866 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
2867 ">{$watchLabel}</label>";
2868 }
2869 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2870 return $checkboxes;
2871 }
2872
2873 /**
2874 * Returns an array of html code of the following buttons:
2875 * save, diff, preview and live
2876 *
2877 * @param $tabindex int Current tabindex
2878 *
2879 * @return array
2880 */
2881 public function getEditButtons( &$tabindex ) {
2882 $buttons = array();
2883
2884 $temp = array(
2885 'id' => 'wpSave',
2886 'name' => 'wpSave',
2887 'type' => 'submit',
2888 'tabindex' => ++$tabindex,
2889 'value' => wfMsg( 'savearticle' ),
2890 'accesskey' => wfMsg( 'accesskey-save' ),
2891 'title' => wfMsg( 'tooltip-save' ) . ' [' . wfMsg( 'accesskey-save' ) . ']',
2892 );
2893 $buttons['save'] = Xml::element( 'input', $temp, '' );
2894
2895 ++$tabindex; // use the same for preview and live preview
2896 $temp = array(
2897 'id' => 'wpPreview',
2898 'name' => 'wpPreview',
2899 'type' => 'submit',
2900 'tabindex' => $tabindex,
2901 'value' => wfMsg( 'showpreview' ),
2902 'accesskey' => wfMsg( 'accesskey-preview' ),
2903 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2904 );
2905 $buttons['preview'] = Xml::element( 'input', $temp, '' );
2906 $buttons['live'] = '';
2907
2908 $temp = array(
2909 'id' => 'wpDiff',
2910 'name' => 'wpDiff',
2911 'type' => 'submit',
2912 'tabindex' => ++$tabindex,
2913 'value' => wfMsg( 'showdiff' ),
2914 'accesskey' => wfMsg( 'accesskey-diff' ),
2915 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2916 );
2917 $buttons['diff'] = Xml::element( 'input', $temp, '' );
2918
2919 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2920 return $buttons;
2921 }
2922
2923 /**
2924 * Output preview text only. This can be sucked into the edit page
2925 * via JavaScript, and saves the server time rendering the skin as
2926 * well as theoretically being more robust on the client (doesn't
2927 * disturb the edit box's undo history, won't eat your text on
2928 * failure, etc).
2929 *
2930 * @todo This doesn't include category or interlanguage links.
2931 * Would need to enhance it a bit, <s>maybe wrap them in XML
2932 * or something...</s> that might also require more skin
2933 * initialization, so check whether that's a problem.
2934 */
2935 function livePreview() {
2936 global $wgOut;
2937 $wgOut->disable();
2938 header( 'Content-type: text/xml; charset=utf-8' );
2939 header( 'Cache-control: no-cache' );
2940
2941 $previewText = $this->getPreviewText();
2942 #$categories = $skin->getCategoryLinks();
2943
2944 $s =
2945 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2946 Xml::tags( 'livepreview', null,
2947 Xml::element( 'preview', null, $previewText )
2948 #. Xml::element( 'category', null, $categories )
2949 );
2950 echo $s;
2951 }
2952
2953 /**
2954 * Call the stock "user is blocked" page
2955 *
2956 * @deprecated in 1.19; throw an exception directly instead
2957 */
2958 function blockedPage() {
2959 wfDeprecated( __METHOD__, '1.19' );
2960 global $wgUser;
2961
2962 throw new UserBlockedError( $wgUser->getBlock() );
2963 }
2964
2965 /**
2966 * Produce the stock "please login to edit pages" page
2967 *
2968 * @deprecated in 1.19; throw an exception directly instead
2969 */
2970 function userNotLoggedInPage() {
2971 wfDeprecated( __METHOD__, '1.19' );
2972 throw new PermissionsError( 'edit' );
2973 }
2974
2975 /**
2976 * Show an error page saying to the user that he has insufficient permissions
2977 * to create a new page
2978 *
2979 * @deprecated in 1.19; throw an exception directly instead
2980 */
2981 function noCreatePermission() {
2982 wfDeprecated( __METHOD__, '1.19' );
2983 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
2984 throw new PermissionsError( $permission );
2985 }
2986
2987 /**
2988 * Creates a basic error page which informs the user that
2989 * they have attempted to edit a nonexistent section.
2990 */
2991 function noSuchSectionPage() {
2992 global $wgOut;
2993
2994 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
2995
2996 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section );
2997 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
2998 $wgOut->addHTML( $res );
2999
3000 $wgOut->returnToMain( false, $this->mTitle );
3001 }
3002
3003 /**
3004 * Produce the stock "your edit contains spam" page
3005 *
3006 * @param $match string Text which triggered one or more filters
3007 * @deprecated since 1.17 Use method spamPageWithContent() instead
3008 */
3009 static function spamPage( $match = false ) {
3010 wfDeprecated( __METHOD__, '1.17' );
3011
3012 global $wgOut, $wgTitle;
3013
3014 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3015
3016 $wgOut->addHTML( '<div id="spamprotected">' );
3017 $wgOut->addWikiMsg( 'spamprotectiontext' );
3018 if ( $match ) {
3019 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3020 }
3021 $wgOut->addHTML( '</div>' );
3022
3023 $wgOut->returnToMain( false, $wgTitle );
3024 }
3025
3026 /**
3027 * Show "your edit contains spam" page with your diff and text
3028 *
3029 * @param $match string|bool Text which triggered one or more filters
3030 */
3031 public function spamPageWithContent( $match = false ) {
3032 global $wgOut;
3033 $this->textbox2 = $this->textbox1;
3034
3035 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3036
3037 $wgOut->addHTML( '<div id="spamprotected">' );
3038 $wgOut->addWikiMsg( 'spamprotectiontext' );
3039 if ( $match ) {
3040 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3041 }
3042 $wgOut->addHTML( '</div>' );
3043
3044 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3045 $de = new DifferenceEngine( $this->mArticle->getContext() );
3046 $de->setText( $this->getCurrentText(), $this->textbox2 );
3047 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
3048
3049 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3050 $this->showTextbox2();
3051
3052 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3053 }
3054
3055 /**
3056 * Format an anchor fragment as it would appear for a given section name
3057 * @param $text String
3058 * @return String
3059 * @private
3060 */
3061 function sectionAnchor( $text ) {
3062 global $wgParser;
3063 return $wgParser->guessSectionNameFromWikiText( $text );
3064 }
3065
3066 /**
3067 * Check if the browser is on a blacklist of user-agents known to
3068 * mangle UTF-8 data on form submission. Returns true if Unicode
3069 * should make it through, false if it's known to be a problem.
3070 * @return bool
3071 * @private
3072 */
3073 function checkUnicodeCompliantBrowser() {
3074 global $wgBrowserBlackList;
3075 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
3076 // No User-Agent header sent? Trust it by default...
3077 return true;
3078 }
3079 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
3080 foreach ( $wgBrowserBlackList as $browser ) {
3081 if ( preg_match( $browser, $currentbrowser ) ) {
3082 return false;
3083 }
3084 }
3085 return true;
3086 }
3087
3088 /**
3089 * Filter an input field through a Unicode de-armoring process if it
3090 * came from an old browser with known broken Unicode editing issues.
3091 *
3092 * @param $request WebRequest
3093 * @param $field String
3094 * @return String
3095 * @private
3096 */
3097 function safeUnicodeInput( $request, $field ) {
3098 $text = rtrim( $request->getText( $field ) );
3099 return $request->getBool( 'safemode' )
3100 ? $this->unmakesafe( $text )
3101 : $text;
3102 }
3103
3104 /**
3105 * @param $request WebRequest
3106 * @param $text string
3107 * @return string
3108 */
3109 function safeUnicodeText( $request, $text ) {
3110 $text = rtrim( $text );
3111 return $request->getBool( 'safemode' )
3112 ? $this->unmakesafe( $text )
3113 : $text;
3114 }
3115
3116 /**
3117 * Filter an output field through a Unicode armoring process if it is
3118 * going to an old browser with known broken Unicode editing issues.
3119 *
3120 * @param $text String
3121 * @return String
3122 * @private
3123 */
3124 function safeUnicodeOutput( $text ) {
3125 global $wgContLang;
3126 $codedText = $wgContLang->recodeForEdit( $text );
3127 return $this->checkUnicodeCompliantBrowser()
3128 ? $codedText
3129 : $this->makesafe( $codedText );
3130 }
3131
3132 /**
3133 * A number of web browsers are known to corrupt non-ASCII characters
3134 * in a UTF-8 text editing environment. To protect against this,
3135 * detected browsers will be served an armored version of the text,
3136 * with non-ASCII chars converted to numeric HTML character references.
3137 *
3138 * Preexisting such character references will have a 0 added to them
3139 * to ensure that round-trips do not alter the original data.
3140 *
3141 * @param $invalue String
3142 * @return String
3143 * @private
3144 */
3145 function makesafe( $invalue ) {
3146 // Armor existing references for reversability.
3147 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
3148
3149 $bytesleft = 0;
3150 $result = "";
3151 $working = 0;
3152 for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
3153 $bytevalue = ord( $invalue[$i] );
3154 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3155 $result .= chr( $bytevalue );
3156 $bytesleft = 0;
3157 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3158 $working = $working << 6;
3159 $working += ( $bytevalue & 0x3F );
3160 $bytesleft--;
3161 if ( $bytesleft <= 0 ) {
3162 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3163 }
3164 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3165 $working = $bytevalue & 0x1F;
3166 $bytesleft = 1;
3167 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3168 $working = $bytevalue & 0x0F;
3169 $bytesleft = 2;
3170 } else { // 1111 0xxx
3171 $working = $bytevalue & 0x07;
3172 $bytesleft = 3;
3173 }
3174 }
3175 return $result;
3176 }
3177
3178 /**
3179 * Reverse the previously applied transliteration of non-ASCII characters
3180 * back to UTF-8. Used to protect data from corruption by broken web browsers
3181 * as listed in $wgBrowserBlackList.
3182 *
3183 * @param $invalue String
3184 * @return String
3185 * @private
3186 */
3187 function unmakesafe( $invalue ) {
3188 $result = "";
3189 for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
3190 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
3191 $i += 3;
3192 $hexstring = "";
3193 do {
3194 $hexstring .= $invalue[$i];
3195 $i++;
3196 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3197
3198 // Do some sanity checks. These aren't needed for reversability,
3199 // but should help keep the breakage down if the editor
3200 // breaks one of the entities whilst editing.
3201 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3202 $codepoint = hexdec( $hexstring );
3203 $result .= codepointToUtf8( $codepoint );
3204 } else {
3205 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3206 }
3207 } else {
3208 $result .= substr( $invalue, $i, 1 );
3209 }
3210 }
3211 // reverse the transform that we made for reversability reasons.
3212 return strtr( $result, array( "&#x0" => "&#x" ) );
3213 }
3214 }