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