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