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