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