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