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