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