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