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