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