Merge branch 'master' into Wikidata
[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 ); #FIXME: what should this return??
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() { #FIXME: use Content! set content_model and content_format!
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->emptyContent();
921 }
922
923 $content = $this->mArticle->getContentObject();
924 return $content;
925 }
926
927 /**
928 * Get the current content of the page. This is basically similar to
929 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
930 * content object is returned instead of null.
931 *
932 * @since 1.20
933 * @return string
934 */
935 private function getCurrentContent() {
936 $rev = $this->mArticle->getRevision();
937 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
938
939 if ( $content === false || $content === null ) {
940 if ( !$this->content_model ) $this->content_model = $this->getTitle()->getContentModelName();
941 $handler = ContentHandler::getForModelName( $this->content_model );
942
943 return $handler->emptyContent();
944 } else {
945 #FIXME: nasty side-effect!
946 $this->content_model = $rev->getContentModelName();
947 $this->content_format = $rev->getContentFormat();
948
949 return $content;
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->emptyContent();
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->emptyContent();
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->emptyContent();
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 <<<<<<< HEAD
1303 // Run post-section-merge edit filter
1304 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1, &$this->hookError, $this->summary ) ) ) {
1305 # Error messages etc. could be handled within the hook...
1306 $status->fatal( 'hookaborted' );
1307 $status->value = self::AS_HOOK_ERROR;
1308 wfProfileOut( __METHOD__ );
1309 return $status;
1310 } elseif ( $this->hookError != '' ) {
1311 # ...or the hook could be expecting us to produce an error
1312 $status->fatal( 'hookaborted' );
1313 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1314 wfProfileOut( __METHOD__ );
1315 return $status;
1316 }
1317
1318 $content = ContentHandler::makeContent( $this->textbox1, $this->getTitle(), $this->content_model, $this->content_format );
1319
1320 # Handle the user preference to force summaries here. Check if it's not a redirect.
1321 if ( !$this->allowBlankSummary && !$content->isRedirect() ) {
1322 if ( md5( $this->summary ) == $this->autoSumm ) {
1323 $this->missingSummary = true;
1324 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1325 $status->value = self::AS_SUMMARY_NEEDED;
1326 wfProfileOut( __METHOD__ );
1327 return $status;
1328 }
1329 =======
1330 $text = $this->textbox1;
1331 $result['sectionanchor'] = '';
1332 if ( $this->section == 'new' ) {
1333 if ( $this->sectiontitle !== '' ) {
1334 // Insert the section title above the content.
1335 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->sectiontitle ) . "\n\n" . $text;
1336
1337 // Jump to the new section
1338 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1339
1340 // If no edit summary was specified, create one automatically from the section
1341 // title and have it link to the new section. Otherwise, respect the summary as
1342 // passed.
1343 if ( $this->summary === '' ) {
1344 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1345 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1346 }
1347 } elseif ( $this->summary !== '' ) {
1348 // Insert the section title above the content.
1349 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary ) . "\n\n" . $text;
1350
1351 // Jump to the new section
1352 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1353
1354 // Create a link to the new section from the edit summary.
1355 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1356 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
1357 >>>>>>> master
1358 }
1359
1360 $result['sectionanchor'] = '';
1361 if ( $this->section == 'new' ) {
1362 if ( $this->sectiontitle !== '' ) {
1363 // Insert the section title above the content.
1364 $content = $content->addSectionHeader( $this->sectiontitle );
1365
1366 // Jump to the new section
1367 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1368
1369 // If no edit summary was specified, create one automatically from the section
1370 // title and have it link to the new section. Otherwise, respect the summary as
1371 // passed.
1372 if ( $this->summary === '' ) {
1373 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1374 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1375 }
1376 } elseif ( $this->summary !== '' ) {
1377 // Insert the section title above the content.
1378 $content = $content->addSectionHeader( $this->sectiontitle );
1379
1380 // Jump to the new section
1381 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1382
1383 // Create a link to the new section from the edit summary.
1384 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1385 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
1386 }
1387 }
1388
1389 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1390
1391 } else {
1392
1393 # Article exists. Check for edit conflict.
1394
1395 $this->mArticle->clear(); # Force reload of dates, etc.
1396 $timestamp = $this->mArticle->getTimestamp();
1397
1398 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1399
1400 if ( $timestamp != $this->edittime ) {
1401 $this->isConflict = true;
1402 if ( $this->section == 'new' ) {
1403 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
1404 $this->mArticle->getComment() == $this->summary ) {
1405 // Probably a duplicate submission of a new comment.
1406 // This can happen when squid resends a request after
1407 // a timeout but the first one actually went through.
1408 wfDebug( __METHOD__ . ": duplicate new section submission; trigger edit conflict!\n" );
1409 } else {
1410 // New comment; suppress conflict.
1411 $this->isConflict = false;
1412 wfDebug( __METHOD__ .": conflict suppressed; new section\n" );
1413 }
1414 } elseif ( $this->section == '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime ) ) {
1415 # Suppress edit conflict with self, except for section edits where merging is required.
1416 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1417 $this->isConflict = false;
1418 <<<<<<< HEAD
1419 =======
1420 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1421 >>>>>>> master
1422 }
1423 }
1424 <<<<<<< HEAD
1425
1426 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1427 // backwards compatibility with old forms/bots).
1428 if ( $this->sectiontitle !== '' ) {
1429 $sectionTitle = $this->sectiontitle;
1430 =======
1431 }
1432
1433 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
1434 // backwards compatibility with old forms/bots).
1435 if ( $this->sectiontitle !== '' ) {
1436 $sectionTitle = $this->sectiontitle;
1437 } else {
1438 $sectionTitle = $this->summary;
1439 }
1440
1441 if ( $this->isConflict ) {
1442 wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1443 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $sectionTitle, $this->edittime );
1444 } else {
1445 wfDebug( __METHOD__ . ": getting section '$this->section'\n" );
1446 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $sectionTitle );
1447 }
1448 if ( is_null( $text ) ) {
1449 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1450 $this->isConflict = true;
1451 $text = $this->textbox1; // do not try to merge here!
1452 } elseif ( $this->isConflict ) {
1453 # Attempt merge
1454 if ( $this->mergeChangesInto( $text ) ) {
1455 // Successful merge! Maybe we should tell the user the good news?
1456 $this->isConflict = false;
1457 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1458 >>>>>>> master
1459 } else {
1460 $sectionTitle = $this->summary;
1461 }
1462
1463 $textbox_content = ContentHandler::makeContent( $this->textbox1, $this->getTitle(), $this->content_model, $this->content_format );
1464 $content = false;
1465
1466 if ( $this->isConflict ) {
1467 wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '{$timestamp}')\n" );
1468
1469 $content = $this->mArticle->replaceSectionContent( $this->section, $textbox_content, $sectionTitle, $this->edittime );
1470 } else {
1471 wfDebug( __METHOD__ . ": getting section '$this->section'\n" );
1472
1473 $content = $this->mArticle->replaceSectionContent( $this->section, $textbox_content, $sectionTitle );
1474 }
1475
1476 if ( is_null( $content ) ) {
1477 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1478 $this->isConflict = true;
1479 $content = $textbox_content; // do not try to merge here!
1480 } elseif ( $this->isConflict ) {
1481 # Attempt merge
1482 if ( $this->mergeChangesIntoContent( $textbox_content ) ) {
1483 // Successful merge! Maybe we should tell the user the good news?
1484 $content = $textbox_content;
1485 $this->isConflict = false;
1486 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1487 } else {
1488 $this->section = '';
1489 #$this->textbox1 = $text; #redundant, nothing to do here?
1490 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1491 }
1492 }
1493
1494 if ( $this->isConflict ) {
1495 $status->setResult( false, self::AS_CONFLICT_DETECTED );
1496 wfProfileOut( __METHOD__ );
1497 return $status;
1498 }
1499
1500 // Run post-section-merge edit filter
1501 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $content->serialize( $this->content_format ), &$this->hookError, $this->summary ) )
1502 || !wfRunHooks( 'EditFilterMergedContent', array( $this, $content, &$this->hookError, $this->summary ) ) ) { #FIXME: document new hook
1503 # Error messages etc. could be handled within the hook...
1504 $status->fatal( 'hookaborted' );
1505 $status->value = self::AS_HOOK_ERROR;
1506 wfProfileOut( __METHOD__ );
1507 return $status;
1508 } elseif ( $this->hookError != '' ) {
1509 # ...or the hook could be expecting us to produce an error
1510 $status->fatal( 'hookaborted' );
1511 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1512 wfProfileOut( __METHOD__ );
1513 return $status;
1514 }
1515
1516 # Handle the user preference to force summaries here, but not for null edits
1517 if ( $this->section != 'new' && !$this->allowBlankSummary
1518 && !$content->equals( $this->getOriginalContent() )
1519 && !$content->isRedirect() ) # check if it's not a redirect
1520 {
1521 if ( md5( $this->summary ) == $this->autoSumm ) {
1522 $this->missingSummary = true;
1523 $status->fatal( 'missingsummary' );
1524 $status->value = self::AS_SUMMARY_NEEDED;
1525 wfProfileOut( __METHOD__ );
1526 return $status;
1527 }
1528 }
1529
1530 # And a similar thing for new sections
1531 if ( $this->section == 'new' && !$this->allowBlankSummary ) {
1532 if ( trim( $this->summary ) == '' ) {
1533 $this->missingSummary = true;
1534 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1535 $status->value = self::AS_SUMMARY_NEEDED;
1536 wfProfileOut( __METHOD__ );
1537 return $status;
1538 }
1539 }
1540
1541 # All's well
1542 wfProfileIn( __METHOD__ . '-sectionanchor' );
1543 $sectionanchor = '';
1544 if ( $this->section == 'new' ) {
1545 if ( $this->textbox1 == '' ) {
1546 $this->missingComment = true;
1547 $status->fatal( 'missingcommenttext' );
1548 $status->value = self::AS_TEXTBOX_EMPTY;
1549 wfProfileOut( __METHOD__ . '-sectionanchor' );
1550 wfProfileOut( __METHOD__ );
1551 return $status;
1552 }
1553 if ( $this->sectiontitle !== '' ) {
1554 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1555 // If no edit summary was specified, create one automatically from the section
1556 // title and have it link to the new section. Otherwise, respect the summary as
1557 // passed.
1558 if ( $this->summary === '' ) {
1559 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1560 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSectionTitle );
1561 }
1562 } elseif ( $this->summary !== '' ) {
1563 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1564 # This is a new section, so create a link to the new section
1565 # in the revision summary.
1566 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1567 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
1568 }
1569 } elseif ( $this->section != '' ) {
1570 # Try to get a section anchor from the section source, redirect to edited section if header found
1571 # XXX: might be better to integrate this into Article::replaceSection
1572 # for duplicate heading checking and maybe parsing
1573 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1574 # we can't deal with anchors, includes, html etc in the header for now,
1575 # headline would need to be parsed to improve this
1576 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1577 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1578 }
1579 }
1580 $result['sectionanchor'] = $sectionanchor;
1581 wfProfileOut( __METHOD__ . '-sectionanchor' );
1582
1583 // Save errors may fall down to the edit form, but we've now
1584 // merged the section into full text. Clear the section field
1585 // so that later submission of conflict forms won't try to
1586 // replace that into a duplicated mess.
1587 $this->textbox1 = $content->serialize( $this->content_format );
1588 $this->section = '';
1589
1590 $status->value = self::AS_SUCCESS_UPDATE;
1591 }
1592
1593 // Check for length errors again now that the section is merged in
1594 $this->kblength = (int)( strlen( $content->serialize( $this->content_format ) ) / 1024 );
1595 if ( $this->kblength > $wgMaxArticleSize ) {
1596 $this->tooBig = true;
1597 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
1598 wfProfileOut( __METHOD__ );
1599 return $status;
1600 }
1601
1602 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1603 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
1604 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
1605 ( $bot ? EDIT_FORCE_BOT : 0 );
1606
1607 $doEditStatus = $this->mArticle->doEditContent( $content, $this->summary, $flags, false, null, $this->content_format );
1608
1609 if ( $doEditStatus->isOK() ) {
1610 $result['redirect'] = $content->isRedirect();
1611 $this->commitWatch();
1612 wfProfileOut( __METHOD__ );
1613 return $status;
1614 } else {
1615 $this->isConflict = true;
1616 $doEditStatus->value = self::AS_END; // Destroys data doEdit() put in $status->value but who cares
1617 wfProfileOut( __METHOD__ );
1618 return $doEditStatus;
1619 }
1620 } catch (MWContentSerializationException $ex) {
1621 $status->fatal( 'content-failed-to-parse', $this->content_model, $this->content_format, $ex->getMessage() );
1622 $status->value = self::AS_PARSE_ERROR;
1623 wfProfileOut( __METHOD__ );
1624 return $status;
1625 }
1626 }
1627
1628 /**
1629 * Commit the change of watch status
1630 */
1631 protected function commitWatch() {
1632 global $wgUser;
1633 if ( $this->watchthis xor $this->mTitle->userIsWatching() ) {
1634 $dbw = wfGetDB( DB_MASTER );
1635 $dbw->begin( __METHOD__ );
1636 if ( $this->watchthis ) {
1637 WatchAction::doWatch( $this->mTitle, $wgUser );
1638 } else {
1639 WatchAction::doUnwatch( $this->mTitle, $wgUser );
1640 }
1641 $dbw->commit( __METHOD__ );
1642 }
1643 }
1644
1645 /**
1646 * Check if no edits were made by other users since
1647 * the time a user started editing the page. Limit to
1648 * 50 revisions for the sake of performance.
1649 *
1650 * @param $id int
1651 * @param $edittime string
1652 *
1653 * @return bool
1654 */
1655 protected function userWasLastToEdit( $id, $edittime ) {
1656 if ( !$id ) return false;
1657 $dbw = wfGetDB( DB_MASTER );
1658 $res = $dbw->select( 'revision',
1659 'rev_user',
1660 array(
1661 'rev_page' => $this->mTitle->getArticleID(),
1662 'rev_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $edittime ) )
1663 ),
1664 __METHOD__,
1665 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1666 foreach ( $res as $row ) {
1667 if ( $row->rev_user != $id ) {
1668 return false;
1669 }
1670 }
1671 return true;
1672 }
1673
1674 /**
1675 * @private
1676 * @todo document
1677 *
1678 * @parma $editText string
1679 *
1680 * @return bool
1681 * @deprecated since 1.20
1682 */
1683 function mergeChangesInto( &$editText ){
1684 wfDebug( __METHOD__, "1.20" );
1685
1686 $editContent = ContentHandler::makeContent( $editText, $this->getTitle(), $this->content_model, $this->content_format );
1687
1688 $ok = $this->mergeChangesIntoContent( $editContent );
1689
1690 if ( $ok ) {
1691 $editText = $editContent->serialize( $this->content_format ); #XXX: really serialize?!
1692 return true;
1693 } else {
1694 return false;
1695 }
1696 }
1697
1698 /**
1699 * @private
1700 * @todo document
1701 *
1702 * @parma $editText string
1703 *
1704 * @return bool
1705 * @since since 1.20
1706 */
1707 private function mergeChangesIntoContent( &$editContent ){
1708 wfProfileIn( __METHOD__ );
1709
1710 $db = wfGetDB( DB_MASTER );
1711
1712 // This is the revision the editor started from
1713 $baseRevision = $this->getBaseRevision();
1714 if ( is_null( $baseRevision ) ) {
1715 wfProfileOut( __METHOD__ );
1716 return false;
1717 }
1718 $baseContent = $baseRevision->getContent();
1719
1720 // The current state, we want to merge updates into it
1721 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
1722 if ( is_null( $currentRevision ) ) {
1723 wfProfileOut( __METHOD__ );
1724 return false;
1725 }
1726 $currentContent = $currentRevision->getContent();
1727
1728 $handler = ContentHandler::getForModelName( $baseContent->getModelName() );
1729
1730 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1731
1732 if ( $result ) {
1733 $editContent = $result;
1734 wfProfileOut( __METHOD__ );
1735 return true;
1736 } else {
1737 wfProfileOut( __METHOD__ );
1738 return false;
1739 }
1740 }
1741
1742 /**
1743 * @return Revision
1744 */
1745 function getBaseRevision() {
1746 if ( !$this->mBaseRevision ) {
1747 $db = wfGetDB( DB_MASTER );
1748 $baseRevision = Revision::loadFromTimestamp(
1749 $db, $this->mTitle, $this->edittime );
1750 return $this->mBaseRevision = $baseRevision;
1751 } else {
1752 return $this->mBaseRevision;
1753 }
1754 }
1755
1756 /**
1757 * Check given input text against $wgSpamRegex, and return the text of the first match.
1758 *
1759 * @param $text string
1760 *
1761 * @return string|bool matching string or false
1762 */
1763 public static function matchSpamRegex( $text ) {
1764 global $wgSpamRegex;
1765 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1766 $regexes = (array)$wgSpamRegex;
1767 return self::matchSpamRegexInternal( $text, $regexes );
1768 }
1769
1770 /**
1771 * Check given input text against $wgSpamRegex, and return the text of the first match.
1772 *
1773 * @parma $text string
1774 *
1775 * @return string|bool matching string or false
1776 */
1777 public static function matchSummarySpamRegex( $text ) {
1778 global $wgSummarySpamRegex;
1779 $regexes = (array)$wgSummarySpamRegex;
1780 return self::matchSpamRegexInternal( $text, $regexes );
1781 }
1782
1783 /**
1784 * @param $text string
1785 * @param $regexes array
1786 * @return bool|string
1787 */
1788 protected static function matchSpamRegexInternal( $text, $regexes ) {
1789 foreach ( $regexes as $regex ) {
1790 $matches = array();
1791 if ( preg_match( $regex, $text, $matches ) ) {
1792 return $matches[0];
1793 }
1794 }
1795 return false;
1796 }
1797
1798 function setHeaders() {
1799 global $wgOut, $wgUser;
1800
1801 $wgOut->addModules( 'mediawiki.action.edit' );
1802
1803 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1804 $wgOut->addModules( 'mediawiki.legacy.preview' );
1805 }
1806 // Bug #19334: textarea jumps when editing articles in IE8
1807 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1808
1809 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1810
1811 # Enabled article-related sidebar, toplinks, etc.
1812 $wgOut->setArticleRelated( true );
1813
1814 $contextTitle = $this->getContextTitle();
1815 if ( $this->isConflict ) {
1816 $msg = 'editconflict';
1817 } elseif ( $contextTitle->exists() && $this->section != '' ) {
1818 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
1819 } else {
1820 $msg = $contextTitle->exists() || ( $contextTitle->getNamespace() == NS_MEDIAWIKI && $contextTitle->getDefaultMessageText() !== false ) ?
1821 'editing' : 'creating';
1822 }
1823 # Use the title defined by DISPLAYTITLE magic word when present
1824 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
1825 if ( $displayTitle === false ) {
1826 $displayTitle = $contextTitle->getPrefixedText();
1827 }
1828 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1829 }
1830
1831 /**
1832 * Show all applicable editing introductions
1833 */
1834 protected function showIntro() {
1835 global $wgOut, $wgUser;
1836 if ( $this->suppressIntro ) {
1837 return;
1838 }
1839
1840 $namespace = $this->mTitle->getNamespace();
1841
1842 if ( $namespace == NS_MEDIAWIKI ) {
1843 # Show a warning if editing an interface message
1844 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1845 } else if( $namespace == NS_FILE ) {
1846 # Show a hint to shared repo
1847 $file = wfFindFile( $this->mTitle );
1848 if( $file && !$file->isLocal() ) {
1849 $descUrl = $file->getDescriptionUrl();
1850 # there must be a description url to show a hint to shared repo
1851 if( $descUrl ) {
1852 if( !$this->mTitle->exists() ) {
1853 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1854 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1855 ) );
1856 } else {
1857 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1858 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1859 ) );
1860 }
1861 }
1862 }
1863 }
1864
1865 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1866 # Show log extract when the user is currently blocked
1867 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
1868 $parts = explode( '/', $this->mTitle->getText(), 2 );
1869 $username = $parts[0];
1870 $user = User::newFromName( $username, false /* allow IP users*/ );
1871 $ip = User::isIP( $username );
1872 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1873 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1874 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1875 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1876 LogEventsList::showLogExtract(
1877 $wgOut,
1878 'block',
1879 $user->getUserPage(),
1880 '',
1881 array(
1882 'lim' => 1,
1883 'showIfEmpty' => false,
1884 'msgKey' => array(
1885 'blocked-notice-logextract',
1886 $user->getName() # Support GENDER in notice
1887 )
1888 )
1889 );
1890 }
1891 }
1892 # Try to add a custom edit intro, or use the standard one if this is not possible.
1893 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
1894 if ( $wgUser->isLoggedIn() ) {
1895 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1896 } else {
1897 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1898 }
1899 }
1900 # Give a notice if the user is editing a deleted/moved page...
1901 if ( !$this->mTitle->exists() ) {
1902 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
1903 '', array( 'lim' => 10,
1904 'conds' => array( "log_action != 'revision'" ),
1905 'showIfEmpty' => false,
1906 'msgKey' => array( 'recreate-moveddeleted-warn' ) )
1907 );
1908 }
1909 }
1910
1911 /**
1912 * Attempt to show a custom editing introduction, if supplied
1913 *
1914 * @return bool
1915 */
1916 protected function showCustomIntro() {
1917 if ( $this->editintro ) {
1918 $title = Title::newFromText( $this->editintro );
1919 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
1920 global $wgOut;
1921 // Added using template syntax, to take <noinclude>'s into account.
1922 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle );
1923 return true;
1924 } else {
1925 return false;
1926 }
1927 } else {
1928 return false;
1929 }
1930 }
1931
1932 /**
1933 * Send the edit form and related headers to $wgOut
1934 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1935 * during form output near the top, for captchas and the like.
1936 */
1937 function showEditForm( $formCallback = null ) {
1938 global $wgOut, $wgUser;
1939
1940 wfProfileIn( __METHOD__ );
1941
1942 # need to parse the preview early so that we know which templates are used,
1943 # otherwise users with "show preview after edit box" will get a blank list
1944 # we parse this near the beginning so that setHeaders can do the title
1945 # setting work instead of leaving it in getPreviewText
1946 $previewOutput = '';
1947 if ( $this->formtype == 'preview' ) {
1948 $previewOutput = $this->getPreviewText();
1949 }
1950
1951 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
1952
1953 $this->setHeaders();
1954
1955 if ( $this->showHeader() === false ) {
1956 wfProfileOut( __METHOD__ );
1957 return;
1958 }
1959
1960 $wgOut->addHTML( $this->editFormPageTop );
1961
1962 if ( $wgUser->getOption( 'previewontop' ) ) {
1963 $this->displayPreviewArea( $previewOutput, true );
1964 }
1965
1966 $wgOut->addHTML( $this->editFormTextTop );
1967
1968 $showToolbar = true;
1969 if ( $this->wasDeletedSinceLastEdit() ) {
1970 if ( $this->formtype == 'save' ) {
1971 // Hide the toolbar and edit area, user can click preview to get it back
1972 // Add an confirmation checkbox and explanation.
1973 $showToolbar = false;
1974 } else {
1975 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1976 'deletedwhileediting' );
1977 }
1978 }
1979
1980 #FIXME: add EditForm plugin interface and use it here! #FIXME: search for textarea1 and textares2, and allow EditForm to override all uses.
1981 $wgOut->addHTML( Html::openElement( 'form', array( 'id' => 'editform', 'name' => 'editform',
1982 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1983 'enctype' => 'multipart/form-data' ) ) );
1984
1985 if ( is_callable( $formCallback ) ) {
1986 call_user_func_array( $formCallback, array( &$wgOut ) );
1987 }
1988
1989 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1990
1991 // Put these up at the top to ensure they aren't lost on early form submission
1992 $this->showFormBeforeText();
1993
1994 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
1995 $username = $this->lastDelete->user_name;
1996 $comment = $this->lastDelete->log_comment;
1997
1998 // It is better to not parse the comment at all than to have templates expanded in the middle
1999 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2000 $key = $comment === ''
2001 ? 'confirmrecreate-noreason'
2002 : 'confirmrecreate';
2003 $wgOut->addHTML(
2004 '<div class="mw-confirm-recreate">' .
2005 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
2006 Xml::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
2007 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2008 ) .
2009 '</div>'
2010 );
2011 }
2012
2013 # When the summary is hidden, also hide them on preview/show changes
2014 if( $this->nosummary ) {
2015 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2016 }
2017
2018 # If a blank edit summary was previously provided, and the appropriate
2019 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2020 # user being bounced back more than once in the event that a summary
2021 # is not required.
2022 #####
2023 # For a bit more sophisticated detection of blank summaries, hash the
2024 # automatic one and pass that in the hidden field wpAutoSummary.
2025 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2026 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2027 }
2028
2029 if ( $this->hasPresetSummary ) {
2030 // If a summary has been preset using &summary= we dont want to prompt for
2031 // a different summary. Only prompt for a summary if the summary is blanked.
2032 // (Bug 17416)
2033 $this->autoSumm = md5( '' );
2034 }
2035
2036 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2037 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2038
2039 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2040
2041 $wgOut->addHTML( Html::hidden( 'format', $this->content_format ) );
2042 $wgOut->addHTML( Html::hidden( 'model', $this->content_model ) );
2043
2044 if ( $this->section == 'new' ) {
2045 $this->showSummaryInput( true, $this->summary );
2046 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2047 }
2048
2049 $wgOut->addHTML( $this->editFormTextBeforeContent );
2050
2051 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2052 $wgOut->addHTML( EditPage::getEditToolbar() );
2053 }
2054
2055 if ( $this->isConflict ) {
2056 // In an edit conflict bypass the overrideable content form method
2057 // and fallback to the raw wpTextbox1 since editconflicts can't be
2058 // resolved between page source edits and custom ui edits using the
2059 // custom edit ui.
2060 $this->textbox2 = $this->textbox1;
2061
2062 $content = $this->getCurrentContent();
2063 $this->textbox1 = $content->serialize( $this->content_format );
2064
2065 $this->showTextbox1();
2066 } else {
2067 $this->showContentForm();
2068 }
2069
2070 $wgOut->addHTML( $this->editFormTextAfterContent );
2071
2072 $wgOut->addWikiText( $this->getCopywarn() );
2073
2074 $wgOut->addHTML( $this->editFormTextAfterWarn );
2075
2076 $this->showStandardInputs();
2077
2078 $this->showFormAfterText();
2079
2080 $this->showTosSummary();
2081
2082 $this->showEditTools();
2083
2084 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2085
2086 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2087 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
2088
2089 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
2090 Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
2091
2092 if ( $this->isConflict ) {
2093 $this->showConflict();
2094 }
2095
2096 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2097
2098 if ( !$wgUser->getOption( 'previewontop' ) ) {
2099 $this->displayPreviewArea( $previewOutput, false );
2100 }
2101
2102 wfProfileOut( __METHOD__ );
2103 }
2104
2105 /**
2106 * Extract the section title from current section text, if any.
2107 *
2108 * @param string $text
2109 * @return Mixed|string or false
2110 */
2111 public static function extractSectionTitle( $text ) {
2112 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2113 if ( !empty( $matches[2] ) ) {
2114 global $wgParser;
2115 return $wgParser->stripSectionName( trim( $matches[2] ) );
2116 } else {
2117 return false;
2118 }
2119 }
2120
2121 protected function showHeader() {
2122 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2123
2124 if ( $this->mTitle->isTalkPage() ) {
2125 $wgOut->addWikiMsg( 'talkpagetext' );
2126 }
2127
2128 # Optional notices on a per-namespace and per-page basis
2129 $editnotice_ns = 'editnotice-' . $this->mTitle->getNamespace();
2130 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
2131 if ( $editnotice_ns_message->exists() ) {
2132 $wgOut->addWikiText( $editnotice_ns_message->plain() );
2133 }
2134 if ( MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
2135 $parts = explode( '/', $this->mTitle->getDBkey() );
2136 $editnotice_base = $editnotice_ns;
2137 while ( count( $parts ) > 0 ) {
2138 $editnotice_base .= '-' . array_shift( $parts );
2139 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
2140 if ( $editnotice_base_msg->exists() ) {
2141 $wgOut->addWikiText( $editnotice_base_msg->plain() );
2142 }
2143 }
2144 } else {
2145 # Even if there are no subpages in namespace, we still don't want / in MW ns.
2146 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle->getDBkey() );
2147 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
2148 if ( $editnoticeMsg->exists() ) {
2149 $wgOut->addWikiText( $editnoticeMsg->plain() );
2150 }
2151 }
2152
2153 if ( $this->isConflict ) {
2154 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2155 $this->edittime = $this->mArticle->getTimestamp();
2156 } else {
2157 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
2158 // We use $this->section to much before this and getVal('wgSection') directly in other places
2159 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2160 // Someone is welcome to try refactoring though
2161 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2162 return false;
2163 }
2164
2165 if ( $this->section != '' && $this->section != 'new' ) {
2166 if ( !$this->summary && !$this->preview && !$this->diff ) {
2167 $sectionTitle = self::extractSectionTitle( $this->textbox1 );
2168 if ( $sectionTitle !== false ) {
2169 $this->summary = "/* $sectionTitle */ ";
2170 }
2171 }
2172 }
2173
2174 if ( $this->missingComment ) {
2175 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2176 }
2177
2178 if ( $this->missingSummary && $this->section != 'new' ) {
2179 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2180 }
2181
2182 if ( $this->missingSummary && $this->section == 'new' ) {
2183 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2184 }
2185
2186 if ( $this->hookError !== '' ) {
2187 $wgOut->addWikiText( $this->hookError );
2188 }
2189
2190 if ( !$this->checkUnicodeCompliantBrowser() ) {
2191 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2192 }
2193
2194 if ( $this->section != 'new' ) {
2195 $revision = $this->mArticle->getRevisionFetched();
2196 if ( $revision ) {
2197 // Let sysop know that this will make private content public if saved
2198
2199 if ( !$revision->userCan( Revision::DELETED_TEXT ) ) {
2200 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2201 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2202 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2203 }
2204
2205 if ( !$revision->isCurrent() ) {
2206 $this->mArticle->setOldSubtitle( $revision->getId() );
2207 $wgOut->addWikiMsg( 'editingold' );
2208 }
2209 } elseif ( $this->mTitle->exists() ) {
2210 // Something went wrong
2211
2212 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2213 array( 'missing-article', $this->mTitle->getPrefixedText(),
2214 wfMsgNoTrans( 'missingarticle-rev', $this->oldid ) ) );
2215 }
2216 }
2217 }
2218
2219 if ( wfReadOnly() ) {
2220 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2221 } elseif ( $wgUser->isAnon() ) {
2222 if ( $this->formtype != 'preview' ) {
2223 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2224 } else {
2225 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2226 }
2227 } else {
2228 if ( $this->isCssJsSubpage ) {
2229 # Check the skin exists
2230 if ( $this->isWrongCaseCssJsPage ) {
2231 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
2232 }
2233 if ( $this->formtype !== 'preview' ) {
2234 if ( $this->isCssSubpage )
2235 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2236 if ( $this->isJsSubpage )
2237 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2238 }
2239 }
2240 }
2241
2242 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
2243 # Is the title semi-protected?
2244 if ( $this->mTitle->isSemiProtected() ) {
2245 $noticeMsg = 'semiprotectedpagewarning';
2246 } else {
2247 # Then it must be protected based on static groups (regular)
2248 $noticeMsg = 'protectedpagewarning';
2249 }
2250 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2251 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2252 }
2253 if ( $this->mTitle->isCascadeProtected() ) {
2254 # Is this page under cascading protection from some source pages?
2255 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2256 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2257 $cascadeSourcesCount = count( $cascadeSources );
2258 if ( $cascadeSourcesCount > 0 ) {
2259 # Explain, and list the titles responsible
2260 foreach ( $cascadeSources as $page ) {
2261 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2262 }
2263 }
2264 $notice .= '</div>';
2265 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2266 }
2267 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2268 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2269 array( 'lim' => 1,
2270 'showIfEmpty' => false,
2271 'msgKey' => array( 'titleprotectedwarning' ),
2272 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2273 }
2274
2275 if ( $this->kblength === false ) {
2276 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2277 }
2278
2279 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2280 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2281 array( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2282 } else {
2283 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2284 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2285 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 ) )
2286 );
2287 }
2288 }
2289 }
2290
2291 /**
2292 * Standard summary input and label (wgSummary), abstracted so EditPage
2293 * subclasses may reorganize the form.
2294 * Note that you do not need to worry about the label's for=, it will be
2295 * inferred by the id given to the input. You can remove them both by
2296 * passing array( 'id' => false ) to $userInputAttrs.
2297 *
2298 * @param $summary string The value of the summary input
2299 * @param $labelText string The html to place inside the label
2300 * @param $inputAttrs array of attrs to use on the input
2301 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2302 *
2303 * @return array An array in the format array( $label, $input )
2304 */
2305 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2306 // Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
2307 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2308 'id' => 'wpSummary',
2309 'maxlength' => '200',
2310 'tabindex' => '1',
2311 'size' => 60,
2312 'spellcheck' => 'true',
2313 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2314
2315 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2316 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2317 'id' => "wpSummaryLabel"
2318 );
2319
2320 $label = null;
2321 if ( $labelText ) {
2322 $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2323 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2324 }
2325
2326 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2327
2328 return array( $label, $input );
2329 }
2330
2331 /**
2332 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2333 * up top, or false if this is the comment summary
2334 * down below the textarea
2335 * @param $summary String: The text of the summary to display
2336 * @return String
2337 */
2338 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2339 global $wgOut, $wgContLang;
2340 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2341 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2342 if ( $isSubjectPreview ) {
2343 if ( $this->nosummary ) {
2344 return;
2345 }
2346 } else {
2347 if ( !$this->mShowSummaryField ) {
2348 return;
2349 }
2350 }
2351 $summary = $wgContLang->recodeForEdit( $summary );
2352 $labelText = wfMsgExt( $isSubjectPreview ? 'subject' : 'summary', 'parseinline' );
2353 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2354 $wgOut->addHTML( "{$label} {$input}" );
2355 }
2356
2357 /**
2358 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2359 * up top, or false if this is the comment summary
2360 * down below the textarea
2361 * @param $summary String: the text of the summary to display
2362 * @return String
2363 */
2364 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2365 if ( !$summary || ( !$this->preview && !$this->diff ) )
2366 return "";
2367
2368 global $wgParser;
2369
2370 if ( $isSubjectPreview )
2371 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
2372
2373 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
2374
2375 $summary = wfMsgExt( $message, 'parseinline' ) . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
2376 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2377 }
2378
2379 protected function showFormBeforeText() {
2380 global $wgOut;
2381 $section = htmlspecialchars( $this->section );
2382 $wgOut->addHTML( <<<HTML
2383 <input type='hidden' value="{$section}" name="wpSection" />
2384 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2385 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2386 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2387
2388 HTML
2389 );
2390 if ( !$this->checkUnicodeCompliantBrowser() )
2391 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
2392 }
2393
2394 protected function showFormAfterText() {
2395 global $wgOut, $wgUser;
2396 /**
2397 * To make it harder for someone to slip a user a page
2398 * which submits an edit form to the wiki without their
2399 * knowledge, a random token is associated with the login
2400 * session. If it's not passed back with the submission,
2401 * we won't save the page, or render user JavaScript and
2402 * CSS previews.
2403 *
2404 * For anon editors, who may not have a session, we just
2405 * include the constant suffix to prevent editing from
2406 * broken text-mangling proxies.
2407 */
2408 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2409 }
2410
2411 /**
2412 * Subpage overridable method for printing the form for page content editing
2413 * By default this simply outputs wpTextbox1
2414 * Subclasses can override this to provide a custom UI for editing;
2415 * be it a form, or simply wpTextbox1 with a modified content that will be
2416 * reverse modified when extracted from the post data.
2417 * Note that this is basically the inverse for importContentFormData
2418 */
2419 protected function showContentForm() {
2420 $this->showTextbox1();
2421 }
2422
2423 /**
2424 * Method to output wpTextbox1
2425 * The $textoverride method can be used by subclasses overriding showContentForm
2426 * to pass back to this method.
2427 *
2428 * @param $customAttribs array of html attributes to use in the textarea
2429 * @param $textoverride String: optional text to override $this->textarea1 with
2430 */
2431 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2432 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2433 $attribs = array( 'style' => 'display:none;' );
2434 } else {
2435 $classes = array(); // Textarea CSS
2436 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
2437 # Is the title semi-protected?
2438 if ( $this->mTitle->isSemiProtected() ) {
2439 $classes[] = 'mw-textarea-sprotected';
2440 } else {
2441 # Then it must be protected based on static groups (regular)
2442 $classes[] = 'mw-textarea-protected';
2443 }
2444 # Is the title cascade-protected?
2445 if ( $this->mTitle->isCascadeProtected() ) {
2446 $classes[] = 'mw-textarea-cprotected';
2447 }
2448 }
2449
2450 $attribs = array( 'tabindex' => 1 );
2451
2452 if ( is_array( $customAttribs ) ) {
2453 $attribs += $customAttribs;
2454 }
2455
2456 if ( count( $classes ) ) {
2457 if ( isset( $attribs['class'] ) ) {
2458 $classes[] = $attribs['class'];
2459 }
2460 $attribs['class'] = implode( ' ', $classes );
2461 }
2462 }
2463
2464 $this->showTextbox( $textoverride !== null ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
2465 }
2466
2467 protected function showTextbox2() {
2468 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2469 }
2470
2471 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2472 global $wgOut, $wgUser;
2473
2474 $wikitext = $this->safeUnicodeOutput( $content );
2475 if ( strval( $wikitext ) !== '' ) {
2476 // Ensure there's a newline at the end, otherwise adding lines
2477 // is awkward.
2478 // But don't add a newline if the ext is empty, or Firefox in XHTML
2479 // mode will show an extra newline. A bit annoying.
2480 $wikitext .= "\n";
2481 }
2482
2483 $attribs = $customAttribs + array(
2484 'accesskey' => ',',
2485 'id' => $name,
2486 'cols' => $wgUser->getIntOption( 'cols' ),
2487 'rows' => $wgUser->getIntOption( 'rows' ),
2488 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2489 );
2490
2491 $pageLang = $this->mTitle->getPageLanguage();
2492 $attribs['lang'] = $pageLang->getCode();
2493 $attribs['dir'] = $pageLang->getDir();
2494
2495 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
2496 }
2497
2498 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2499 global $wgOut;
2500 $classes = array();
2501 if ( $isOnTop )
2502 $classes[] = 'ontop';
2503
2504 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2505
2506 if ( $this->formtype != 'preview' )
2507 $attribs['style'] = 'display: none;';
2508
2509 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
2510
2511 if ( $this->formtype == 'preview' ) {
2512 $this->showPreview( $previewOutput );
2513 }
2514
2515 $wgOut->addHTML( '</div>' );
2516
2517 if ( $this->formtype == 'diff' ) {
2518 $this->showDiff();
2519 }
2520 }
2521
2522 /**
2523 * Append preview output to $wgOut.
2524 * Includes category rendering if this is a category page.
2525 *
2526 * @param $text String: the HTML to be output for the preview.
2527 */
2528 protected function showPreview( $text ) {
2529 global $wgOut;
2530 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2531 $this->mArticle->openShowCategory();
2532 }
2533 # This hook seems slightly odd here, but makes things more
2534 # consistent for extensions.
2535 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2536 $wgOut->addHTML( $text );
2537 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2538 $this->mArticle->closeShowCategory();
2539 }
2540 }
2541
2542 /**
2543 * Get a diff between the current contents of the edit box and the
2544 * version of the page we're editing from.
2545 *
2546 * If this is a section edit, we'll replace the section as for final
2547 * save and then make a comparison.
2548 */
2549 function showDiff() {
2550 global $wgUser, $wgContLang, $wgOut;
2551
2552 $oldContent = $this->getOriginalContent();
2553
2554 $textboxContent = ContentHandler::makeContent( $this->textbox1, $this->getTitle(),
2555 $this->content_model, $this->content_format ); #XXX: handle parse errors ?
2556
2557 $newContent = $this->mArticle->replaceSectionContent(
2558 $this->section, $textboxContent,
2559 $this->summary, $this->edittime );
2560 $oldtitlemsg = 'currentrev';
2561 # if message does not exist, show diff against the preloaded default
2562 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
2563 $oldtext = $this->mTitle->getDefaultMessageText();
2564 if( $oldtext !== false ) {
2565 $oldtitlemsg = 'defaultmessagetext';
2566 }
2567 } else {
2568 $oldtext = $this->mArticle->getRawText();
2569 }
2570 $newtext = $this->mArticle->replaceSection(
2571 $this->section, $this->textbox1, $this->summary, $this->edittime );
2572
2573 # hanlde legacy text-based hook
2574 $newtext_orig = $newContent->serialize( $this->content_format );
2575 $newtext = $newtext_orig; #clone
2576 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2577
2578 if ( $newtext != $newtext_orig ) {
2579 #if the hook changed the text, create a new Content object accordingly.
2580 $newContent = ContentHandler::makeContent( $newtext, $this->getTitle(), $newContent->getModelName() ); #XXX: handle parse errors ?
2581 }
2582
2583 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) ); #FIXME: document new hook
2584
2585 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
2586 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
2587
2588 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
2589 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2590 if ( $oldtext !== false || $newtext != '' ) {
2591 $oldtitle = wfMsgExt( $oldtitlemsg, array( 'parseinline' ) );
2592 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2593
2594 $de = $oldContent->getContentHandler()->getDifferenceEngine( $this->mArticle->getContext() );
2595 $de->setContent( $oldContent, $newContent );
2596
2597 $difftext = $de->getDiff( $oldtitle, $newtitle );
2598 $de->showDiffStyle();
2599 } else {
2600 $difftext = '';
2601 }
2602
2603 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2604 }
2605
2606 /**
2607 * Give a chance for site and per-namespace customizations of
2608 * terms of service summary link that might exist separately
2609 * from the copyright notice.
2610 *
2611 * This will display between the save button and the edit tools,
2612 * so should remain short!
2613 */
2614 protected function showTosSummary() {
2615 $msg = 'editpage-tos-summary';
2616 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
2617 if ( !wfMessage( $msg )->isDisabled() ) {
2618 global $wgOut;
2619 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2620 $wgOut->addWikiMsg( $msg );
2621 $wgOut->addHTML( '</div>' );
2622 }
2623 }
2624
2625 protected function showEditTools() {
2626 global $wgOut;
2627 $wgOut->addHTML( '<div class="mw-editTools">' .
2628 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2629 '</div>' );
2630 }
2631
2632 protected function getCopywarn() {
2633 global $wgRightsText;
2634 if ( $wgRightsText ) {
2635 $copywarnMsg = array( 'copyrightwarning',
2636 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2637 $wgRightsText );
2638 } else {
2639 $copywarnMsg = array( 'copyrightwarning2',
2640 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2641 }
2642 // Allow for site and per-namespace customization of contribution/copyright notice.
2643 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle, &$copywarnMsg ) );
2644
2645 return "<div id=\"editpage-copywarn\">\n" .
2646 call_user_func_array( "wfMsgNoTrans", $copywarnMsg ) . "\n</div>";
2647 }
2648
2649 protected function showStandardInputs( &$tabindex = 2 ) {
2650 global $wgOut;
2651 $wgOut->addHTML( "<div class='editOptions'>\n" );
2652
2653 if ( $this->section != 'new' ) {
2654 $this->showSummaryInput( false, $this->summary );
2655 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
2656 }
2657
2658 $checkboxes = $this->getCheckboxes( $tabindex,
2659 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
2660 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2661 $wgOut->addHTML( "<div class='editButtons'>\n" );
2662 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2663
2664 $cancel = $this->getCancelLink();
2665 if ( $cancel !== '' ) {
2666 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2667 }
2668 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2669 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2670 htmlspecialchars( wfMsg( 'edithelp' ) ) . '</a> ' .
2671 htmlspecialchars( wfMsg( 'newwindow' ) );
2672 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2673 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2674 }
2675
2676 /**
2677 * Show an edit conflict. textbox1 is already shown in showEditForm().
2678 * If you want to use another entry point to this function, be careful.
2679 */
2680 protected function showConflict() {
2681 global $wgOut;
2682
2683 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2684 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2685
2686 $content1 = ContentHandler::makeContent( $this->textbox1, $this->getTitle(), $this->content_model, $this->content_format ); #XXX: handle parse errors?
2687 $content2 = ContentHandler::makeContent( $this->textbox2, $this->getTitle(), $this->content_model, $this->content_format ); #XXX: handle parse errors?
2688
2689 $handler = ContentHandler::getForModelName( $this->content_model );
2690 $de = $handler->getDifferenceEngine( $this->mArticle->getContext() );
2691 $de->setContent( $content2, $content1 );
2692 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2693
2694 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2695 $this->showTextbox2();
2696 }
2697 }
2698
2699 /**
2700 * @return string
2701 */
2702 public function getCancelLink() {
2703 $cancelParams = array();
2704 if ( !$this->isConflict && $this->oldid > 0 ) {
2705 $cancelParams['oldid'] = $this->oldid;
2706 }
2707
2708 return Linker::linkKnown(
2709 $this->getContextTitle(),
2710 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2711 array( 'id' => 'mw-editform-cancel' ),
2712 $cancelParams
2713 );
2714 }
2715
2716 /**
2717 * Returns the URL to use in the form's action attribute.
2718 * This is used by EditPage subclasses when simply customizing the action
2719 * variable in the constructor is not enough. This can be used when the
2720 * EditPage lives inside of a Special page rather than a custom page action.
2721 *
2722 * @param $title Title object for which is being edited (where we go to for &action= links)
2723 * @return string
2724 */
2725 protected function getActionURL( Title $title ) {
2726 return $title->getLocalURL( array( 'action' => $this->action ) );
2727 }
2728
2729 /**
2730 * Check if a page was deleted while the user was editing it, before submit.
2731 * Note that we rely on the logging table, which hasn't been always there,
2732 * but that doesn't matter, because this only applies to brand new
2733 * deletes.
2734 */
2735 protected function wasDeletedSinceLastEdit() {
2736 if ( $this->deletedSinceEdit !== null ) {
2737 return $this->deletedSinceEdit;
2738 }
2739
2740 $this->deletedSinceEdit = false;
2741
2742 if ( $this->mTitle->isDeletedQuick() ) {
2743 $this->lastDelete = $this->getLastDelete();
2744 if ( $this->lastDelete ) {
2745 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
2746 if ( $deleteTime > $this->starttime ) {
2747 $this->deletedSinceEdit = true;
2748 }
2749 }
2750 }
2751
2752 return $this->deletedSinceEdit;
2753 }
2754
2755 protected function getLastDelete() {
2756 $dbr = wfGetDB( DB_SLAVE );
2757 $data = $dbr->selectRow(
2758 array( 'logging', 'user' ),
2759 array( 'log_type',
2760 'log_action',
2761 'log_timestamp',
2762 'log_user',
2763 'log_namespace',
2764 'log_title',
2765 'log_comment',
2766 'log_params',
2767 'log_deleted',
2768 'user_name' ),
2769 array( 'log_namespace' => $this->mTitle->getNamespace(),
2770 'log_title' => $this->mTitle->getDBkey(),
2771 'log_type' => 'delete',
2772 'log_action' => 'delete',
2773 'user_id=log_user' ),
2774 __METHOD__,
2775 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2776 );
2777 // Quick paranoid permission checks...
2778 if ( is_object( $data ) ) {
2779 if ( $data->log_deleted & LogPage::DELETED_USER )
2780 $data->user_name = wfMsgHtml( 'rev-deleted-user' );
2781 if ( $data->log_deleted & LogPage::DELETED_COMMENT )
2782 $data->log_comment = wfMsgHtml( 'rev-deleted-comment' );
2783 }
2784 return $data;
2785 }
2786
2787 /**
2788 * Get the rendered text for previewing.
2789 * @return string
2790 */
2791 function getPreviewText() {
2792 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2793
2794 wfProfileIn( __METHOD__ );
2795
2796 if ( $wgRawHtml && !$this->mTokenOk ) {
2797 // Could be an offsite preview attempt. This is very unsafe if
2798 // HTML is enabled, as it could be an attack.
2799 $parsedNote = '';
2800 if ( $this->textbox1 !== '' ) {
2801 // Do not put big scary notice, if previewing the empty
2802 // string, which happens when you initially edit
2803 // a category page, due to automatic preview-on-open.
2804 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2805 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2806 }
2807 wfProfileOut( __METHOD__ );
2808 return $parsedNote;
2809 }
2810
2811 try {
2812 $content = ContentHandler::makeContent( $this->textbox1, $this->getTitle(), $this->content_model, $this->content_format );
2813
2814 if ( $this->mTriedSave && !$this->mTokenOk ) {
2815 if ( $this->mTokenOkExceptSuffix ) {
2816 $note = wfMsg( 'token_suffix_mismatch' );
2817 } else {
2818 $note = wfMsg( 'session_fail_preview' );
2819 }
2820 } elseif ( $this->incompleteForm ) {
2821 $note = wfMsg( 'edit_form_incomplete' );
2822 } elseif ( $this->isCssJsSubpage || $this->mTitle->isCssOrJsPage() ) {
2823 # if this is a CSS or JS page used in the UI, show a special notice
2824 # 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?
2825
2826 if( $this->mTitle->isCssJsSubpage() ) {
2827 $level = 'user';
2828 } elseif( $this->mTitle->isCssOrJsPage() ) {
2829 $level = 'site';
2830 } else {
2831 $level = false;
2832 }
2833
2834 if ( $content->getModelName() == CONTENT_MODEL_CSS ) {
2835 $format = 'css';
2836 } elseif ( $content->getModelName() == CONTENT_MODEL_JAVASCRIPT ) {
2837 $format = 'js';
2838 } else {
2839 $format = false;
2840 }
2841
2842 # Used messages to make sure grep find them:
2843 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2844 if( $level && $format ) {
2845 $note = "<div id='mw-{$level}{$format}preview'>" . wfMsg( "{$level}{$format}preview" ) . "</div>";
2846 } else {
2847 $note = wfMsg( 'previewnote' );
2848 }
2849 } else {
2850 $note = wfMsg( 'previewnote' );
2851 }
2852
2853 $parserOptions = ParserOptions::newFromUser( $wgUser );
2854 $parserOptions->setEditSection( false );
2855 $parserOptions->setTidy( true );
2856 $parserOptions->setIsPreview( true );
2857 $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' );
2858
2859 $rt = $content->getRedirectChain();
2860
2861 if ( $rt ) {
2862 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
2863 } else {
2864
2865 # If we're adding a comment, we need to show the
2866 # summary as the headline
2867 if ( $this->section == "new" && $this->summary != "" ) {
2868 $content = $content->addSectionHeader( $this->summary );
2869 }
2870
2871 $toparse_orig = $content->serialize( $this->content_format );
2872 $toparse = $toparse_orig;
2873 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2874
2875 if ( $toparse !== $toparse_orig ) {
2876 #hook changed the text, create new Content object
2877 $content = ContentHandler::makeContent( $toparse, $this->getTitle(), $this->content_model, $this->content_format );
2878 }
2879
2880 wfRunHooks( 'EditPageGetPreviewContent', array( $this, &$content ) ); # FIXME: document new hook
2881
2882 $parserOptions->enableLimitReport();
2883
2884 #XXX: For CSS/JS pages, we should have called the ShowRawCssJs hook here. But it's now deprecated, so never mind
2885 $content = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
2886 $parserOutput = $content->getParserOutput( $this->mTitle, null, $parserOptions );
2887
2888 $previewHTML = $parserOutput->getText();
2889 $this->mParserOutput = $parserOutput;
2890 $wgOut->addParserOutputNoText( $parserOutput );
2891
2892 if ( count( $parserOutput->getWarnings() ) ) {
2893 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2894 }
2895 }
2896 } catch (MWContentSerializationException $ex) {
2897 $note .= "\n\n" . wfMsg('content-failed-to-parse', $this->content_model, $this->content_format, $ex->getMessage() );
2898 $previewHTML = '';
2899 }
2900 if ( $this->mTriedSave && !$this->mTokenOk ) {
2901 if ( $this->mTokenOkExceptSuffix ) {
2902 $note = wfMsg( 'token_suffix_mismatch' );
2903 } else {
2904 $note = wfMsg( 'session_fail_preview' );
2905 }
2906 } elseif ( $this->incompleteForm ) {
2907 $note = wfMsg( 'edit_form_incomplete' );
2908 } else {
2909 $note = wfMsg( 'previewnote' );
2910 }
2911
2912 $parserOptions = ParserOptions::newFromUser( $wgUser );
2913 $parserOptions->setEditSection( false );
2914 $parserOptions->setTidy( true );
2915 $parserOptions->setIsPreview( true );
2916 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
2917
2918 # don't parse non-wikitext pages, show message about preview
2919 # 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?
2920
2921 if ( $this->isCssJsSubpage || !$this->mTitle->isWikitextPage() ) {
2922 if ( $this->mTitle->isCssJsSubpage() ) {
2923 $level = 'user';
2924 } elseif ( $this->mTitle->isCssOrJsPage() ) {
2925 $level = 'site';
2926 } else {
2927 $level = false;
2928 }
2929
2930 # Used messages to make sure grep find them:
2931 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2932 if ( $level ) {
2933 if ( preg_match( "/\\.css$/", $this->mTitle->getText() ) ) {
2934 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2935 $class = "mw-code mw-css";
2936 } elseif ( preg_match( "/\\.js$/", $this->mTitle->getText() ) ) {
2937 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2938 $class = "mw-code mw-js";
2939 } else {
2940 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2941 }
2942 }
2943
2944 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
2945 $previewHTML = $parserOutput->mText;
2946 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1 ) . "\n</pre>\n";
2947 } else {
2948 $toparse = $this->textbox1;
2949
2950 # If we're adding a comment, we need to show the
2951 # summary as the headline
2952 if ( $this->section == "new" && $this->summary != "" ) {
2953 $toparse = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary ) . "\n\n" . $toparse;
2954 }
2955
2956 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2957
2958 $parserOptions->enableLimitReport();
2959
2960 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle, $wgUser, $parserOptions );
2961 $parserOutput = $wgParser->parse( $toparse, $this->mTitle, $parserOptions );
2962
2963 $rt = Title::newFromRedirectArray( $this->textbox1 );
2964 if ( $rt ) {
2965 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
2966 } else {
2967 $previewHTML = $parserOutput->getText();
2968 }
2969
2970 $this->mParserOutput = $parserOutput;
2971 $wgOut->addParserOutputNoText( $parserOutput );
2972
2973 if ( count( $parserOutput->getWarnings() ) ) {
2974 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2975 }
2976 }
2977
2978 if ( $this->isConflict ) {
2979 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2980 } else {
2981 $conflict = '<hr />';
2982 }
2983
2984 $previewhead = "<div class='previewnote'>\n" .
2985 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2986 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2987
2988 $pageLang = $this->mTitle->getPageLanguage();
2989 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2990 'class' => 'mw-content-' . $pageLang->getDir() );
2991 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
2992
2993 wfProfileOut( __METHOD__ );
2994 return $previewhead . $previewHTML . $this->previewTextAfterContent;
2995 }
2996
2997 /**
2998 * @return Array
2999 */
3000 function getTemplates() {
3001 if ( $this->preview || $this->section != '' ) {
3002 $templates = array();
3003 if ( !isset( $this->mParserOutput ) ) {
3004 return $templates;
3005 }
3006 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3007 foreach ( array_keys( $template ) as $dbk ) {
3008 $templates[] = Title::makeTitle( $ns, $dbk );
3009 }
3010 }
3011 return $templates;
3012 } else {
3013 return $this->mTitle->getTemplateLinksFrom();
3014 }
3015 }
3016
3017 /**
3018 * Shows a bulletin board style toolbar for common editing functions.
3019 * It can be disabled in the user preferences.
3020 * The necessary JavaScript code can be found in skins/common/edit.js.
3021 *
3022 * @return string
3023 */
3024 static function getEditToolbar() {
3025 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3026 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
3027
3028 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3029
3030 /**
3031 * $toolarray is an array of arrays each of which includes the
3032 * filename of the button image (without path), the opening
3033 * tag, the closing tag, optionally a sample text that is
3034 * inserted between the two when no selection is highlighted
3035 * and. The tip text is shown when the user moves the mouse
3036 * over the button.
3037 *
3038 * Also here: accesskeys (key), which are not used yet until
3039 * someone can figure out a way to make them work in
3040 * IE. However, we should make sure these keys are not defined
3041 * on the edit page.
3042 */
3043 $toolarray = array(
3044 array(
3045 'image' => $wgLang->getImageFile( 'button-bold' ),
3046 'id' => 'mw-editbutton-bold',
3047 'open' => '\'\'\'',
3048 'close' => '\'\'\'',
3049 'sample' => wfMsg( 'bold_sample' ),
3050 'tip' => wfMsg( 'bold_tip' ),
3051 'key' => 'B'
3052 ),
3053 array(
3054 'image' => $wgLang->getImageFile( 'button-italic' ),
3055 'id' => 'mw-editbutton-italic',
3056 'open' => '\'\'',
3057 'close' => '\'\'',
3058 'sample' => wfMsg( 'italic_sample' ),
3059 'tip' => wfMsg( 'italic_tip' ),
3060 'key' => 'I'
3061 ),
3062 array(
3063 'image' => $wgLang->getImageFile( 'button-link' ),
3064 'id' => 'mw-editbutton-link',
3065 'open' => '[[',
3066 'close' => ']]',
3067 'sample' => wfMsg( 'link_sample' ),
3068 'tip' => wfMsg( 'link_tip' ),
3069 'key' => 'L'
3070 ),
3071 array(
3072 'image' => $wgLang->getImageFile( 'button-extlink' ),
3073 'id' => 'mw-editbutton-extlink',
3074 'open' => '[',
3075 'close' => ']',
3076 'sample' => wfMsg( 'extlink_sample' ),
3077 'tip' => wfMsg( 'extlink_tip' ),
3078 'key' => 'X'
3079 ),
3080 array(
3081 'image' => $wgLang->getImageFile( 'button-headline' ),
3082 'id' => 'mw-editbutton-headline',
3083 'open' => "\n== ",
3084 'close' => " ==\n",
3085 'sample' => wfMsg( 'headline_sample' ),
3086 'tip' => wfMsg( 'headline_tip' ),
3087 'key' => 'H'
3088 ),
3089 $imagesAvailable ? array(
3090 'image' => $wgLang->getImageFile( 'button-image' ),
3091 'id' => 'mw-editbutton-image',
3092 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3093 'close' => ']]',
3094 'sample' => wfMsg( 'image_sample' ),
3095 'tip' => wfMsg( 'image_tip' ),
3096 'key' => 'D',
3097 ) : false,
3098 $imagesAvailable ? array(
3099 'image' => $wgLang->getImageFile( 'button-media' ),
3100 'id' => 'mw-editbutton-media',
3101 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3102 'close' => ']]',
3103 'sample' => wfMsg( 'media_sample' ),
3104 'tip' => wfMsg( 'media_tip' ),
3105 'key' => 'M'
3106 ) : false,
3107 $wgUseTeX ? array(
3108 'image' => $wgLang->getImageFile( 'button-math' ),
3109 'id' => 'mw-editbutton-math',
3110 'open' => "<math>",
3111 'close' => "</math>",
3112 'sample' => wfMsg( 'math_sample' ),
3113 'tip' => wfMsg( 'math_tip' ),
3114 'key' => 'C'
3115 ) : false,
3116 array(
3117 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3118 'id' => 'mw-editbutton-nowiki',
3119 'open' => "<nowiki>",
3120 'close' => "</nowiki>",
3121 'sample' => wfMsg( 'nowiki_sample' ),
3122 'tip' => wfMsg( 'nowiki_tip' ),
3123 'key' => 'N'
3124 ),
3125 array(
3126 'image' => $wgLang->getImageFile( 'button-sig' ),
3127 'id' => 'mw-editbutton-signature',
3128 'open' => '--~~~~',
3129 'close' => '',
3130 'sample' => '',
3131 'tip' => wfMsg( 'sig_tip' ),
3132 'key' => 'Y'
3133 ),
3134 array(
3135 'image' => $wgLang->getImageFile( 'button-hr' ),
3136 'id' => 'mw-editbutton-hr',
3137 'open' => "\n----\n",
3138 'close' => '',
3139 'sample' => '',
3140 'tip' => wfMsg( 'hr_tip' ),
3141 'key' => 'R'
3142 )
3143 );
3144
3145 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3146 foreach ( $toolarray as $tool ) {
3147 if ( !$tool ) {
3148 continue;
3149 }
3150
3151 $params = array(
3152 $image = $wgStylePath . '/common/images/' . $tool['image'],
3153 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3154 // Older browsers show a "speedtip" type message only for ALT.
3155 // Ideally these should be different, realistically they
3156 // probably don't need to be.
3157 $tip = $tool['tip'],
3158 $open = $tool['open'],
3159 $close = $tool['close'],
3160 $sample = $tool['sample'],
3161 $cssId = $tool['id'],
3162 );
3163
3164 $script .= Xml::encodeJsCall( 'mw.toolbar.addButton', $params );
3165 }
3166
3167 // This used to be called on DOMReady from mediawiki.action.edit, which
3168 // ended up causing race conditions with the setup code above.
3169 $script .= "\n" .
3170 "// Create button bar\n" .
3171 "$(function() { mw.toolbar.init(); } );\n";
3172
3173 $script .= '});';
3174 $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
3175
3176 $toolbar = '<div id="toolbar"></div>';
3177
3178 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3179
3180 return $toolbar;
3181 }
3182
3183 /**
3184 * Returns an array of html code of the following checkboxes:
3185 * minor and watch
3186 *
3187 * @param $tabindex int Current tabindex
3188 * @param $checked Array of checkbox => bool, where bool indicates the checked
3189 * status of the checkbox
3190 *
3191 * @return array
3192 */
3193 public function getCheckboxes( &$tabindex, $checked ) {
3194 global $wgUser;
3195
3196 $checkboxes = array();
3197
3198 // don't show the minor edit checkbox if it's a new page or section
3199 if ( !$this->isNew ) {
3200 $checkboxes['minor'] = '';
3201 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
3202 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3203 $attribs = array(
3204 'tabindex' => ++$tabindex,
3205 'accesskey' => wfMsg( 'accesskey-minoredit' ),
3206 'id' => 'wpMinoredit',
3207 );
3208 $checkboxes['minor'] =
3209 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3210 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
3211 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3212 ">{$minorLabel}</label>";
3213 }
3214 }
3215
3216 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
3217 $checkboxes['watch'] = '';
3218 if ( $wgUser->isLoggedIn() ) {
3219 $attribs = array(
3220 'tabindex' => ++$tabindex,
3221 'accesskey' => wfMsg( 'accesskey-watch' ),
3222 'id' => 'wpWatchthis',
3223 );
3224 $checkboxes['watch'] =
3225 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3226 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
3227 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
3228 ">{$watchLabel}</label>";
3229 }
3230 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3231 return $checkboxes;
3232 }
3233
3234 /**
3235 * Returns an array of html code of the following buttons:
3236 * save, diff, preview and live
3237 *
3238 * @param $tabindex int Current tabindex
3239 *
3240 * @return array
3241 */
3242 public function getEditButtons( &$tabindex ) {
3243 $buttons = array();
3244
3245 $temp = array(
3246 'id' => 'wpSave',
3247 'name' => 'wpSave',
3248 'type' => 'submit',
3249 'tabindex' => ++$tabindex,
3250 'value' => wfMsg( 'savearticle' ),
3251 'accesskey' => wfMsg( 'accesskey-save' ),
3252 'title' => wfMsg( 'tooltip-save' ) . ' [' . wfMsg( 'accesskey-save' ) . ']',
3253 );
3254 $buttons['save'] = Xml::element( 'input', $temp, '' );
3255
3256 ++$tabindex; // use the same for preview and live preview
3257 $temp = array(
3258 'id' => 'wpPreview',
3259 'name' => 'wpPreview',
3260 'type' => 'submit',
3261 'tabindex' => $tabindex,
3262 'value' => wfMsg( 'showpreview' ),
3263 'accesskey' => wfMsg( 'accesskey-preview' ),
3264 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
3265 );
3266 $buttons['preview'] = Xml::element( 'input', $temp, '' );
3267 $buttons['live'] = '';
3268
3269 $temp = array(
3270 'id' => 'wpDiff',
3271 'name' => 'wpDiff',
3272 'type' => 'submit',
3273 'tabindex' => ++$tabindex,
3274 'value' => wfMsg( 'showdiff' ),
3275 'accesskey' => wfMsg( 'accesskey-diff' ),
3276 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
3277 );
3278 $buttons['diff'] = Xml::element( 'input', $temp, '' );
3279
3280 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3281 return $buttons;
3282 }
3283
3284 /**
3285 * Output preview text only. This can be sucked into the edit page
3286 * via JavaScript, and saves the server time rendering the skin as
3287 * well as theoretically being more robust on the client (doesn't
3288 * disturb the edit box's undo history, won't eat your text on
3289 * failure, etc).
3290 *
3291 * @todo This doesn't include category or interlanguage links.
3292 * Would need to enhance it a bit, <s>maybe wrap them in XML
3293 * or something...</s> that might also require more skin
3294 * initialization, so check whether that's a problem.
3295 */
3296 function livePreview() {
3297 global $wgOut;
3298 $wgOut->disable();
3299 header( 'Content-type: text/xml; charset=utf-8' );
3300 header( 'Cache-control: no-cache' );
3301
3302 $previewText = $this->getPreviewText();
3303 #$categories = $skin->getCategoryLinks();
3304
3305 $s =
3306 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3307 Xml::tags( 'livepreview', null,
3308 Xml::element( 'preview', null, $previewText )
3309 #. Xml::element( 'category', null, $categories )
3310 );
3311 echo $s;
3312 }
3313
3314 /**
3315 * Call the stock "user is blocked" page
3316 *
3317 * @deprecated in 1.19; throw an exception directly instead
3318 */
3319 function blockedPage() {
3320 wfDeprecated( __METHOD__, '1.19' );
3321 global $wgUser;
3322
3323 throw new UserBlockedError( $wgUser->getBlock() );
3324 }
3325
3326 /**
3327 * Produce the stock "please login to edit pages" page
3328 *
3329 * @deprecated in 1.19; throw an exception directly instead
3330 */
3331 function userNotLoggedInPage() {
3332 wfDeprecated( __METHOD__, '1.19' );
3333 throw new PermissionsError( 'edit' );
3334 }
3335
3336 /**
3337 * Show an error page saying to the user that he has insufficient permissions
3338 * to create a new page
3339 *
3340 * @deprecated in 1.19; throw an exception directly instead
3341 */
3342 function noCreatePermission() {
3343 wfDeprecated( __METHOD__, '1.19' );
3344 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
3345 throw new PermissionsError( $permission );
3346 }
3347
3348 /**
3349 * Creates a basic error page which informs the user that
3350 * they have attempted to edit a nonexistent section.
3351 */
3352 function noSuchSectionPage() {
3353 global $wgOut;
3354
3355 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3356
3357 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section );
3358 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3359 $wgOut->addHTML( $res );
3360
3361 $wgOut->returnToMain( false, $this->mTitle );
3362 }
3363
3364 /**
3365 * Produce the stock "your edit contains spam" page
3366 *
3367 * @param $match string Text which triggered one or more filters
3368 * @deprecated since 1.17 Use method spamPageWithContent() instead
3369 */
3370 static function spamPage( $match = false ) {
3371 wfDeprecated( __METHOD__, '1.17' );
3372
3373 global $wgOut, $wgTitle;
3374
3375 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3376
3377 $wgOut->addHTML( '<div id="spamprotected">' );
3378 $wgOut->addWikiMsg( 'spamprotectiontext' );
3379 if ( $match ) {
3380 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3381 }
3382 $wgOut->addHTML( '</div>' );
3383
3384 $wgOut->returnToMain( false, $wgTitle );
3385 }
3386
3387 /**
3388 * Show "your edit contains spam" page with your diff and text
3389 *
3390 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3391 */
3392 public function spamPageWithContent( $match = false ) {
3393 global $wgOut, $wgLang;
3394 $this->textbox2 = $this->textbox1;
3395
3396 if( is_array( $match ) ){
3397 $match = $wgLang->listToText( $match );
3398 }
3399 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3400
3401 $wgOut->addHTML( '<div id="spamprotected">' );
3402 $wgOut->addWikiMsg( 'spamprotectiontext' );
3403 if ( $match ) {
3404 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3405 }
3406 $wgOut->addHTML( '</div>' );
3407
3408 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3409
3410 $handler = ContentHandler::getForTitle( $this->getTitle() );
3411 $de = $handler->getDifferenceEngine( $this->mArticle->getContext() );
3412
3413 $content2 = ContentHandler::makeContent( $this->textbox2, $this->getTitle(), $this->content_model, $this->content_format ); #XXX: handle parse errors?
3414 $de->setContent( $this->getCurrentContent(), $content2 );
3415
3416 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
3417
3418 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3419 $this->showTextbox2();
3420
3421 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3422 }
3423
3424 /**
3425 * Format an anchor fragment as it would appear for a given section name
3426 * @param $text String
3427 * @return String
3428 * @private
3429 */
3430 function sectionAnchor( $text ) {
3431 global $wgParser;
3432 return $wgParser->guessSectionNameFromWikiText( $text );
3433 }
3434
3435 /**
3436 * Check if the browser is on a blacklist of user-agents known to
3437 * mangle UTF-8 data on form submission. Returns true if Unicode
3438 * should make it through, false if it's known to be a problem.
3439 * @return bool
3440 * @private
3441 */
3442 function checkUnicodeCompliantBrowser() {
3443 global $wgBrowserBlackList;
3444 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
3445 // No User-Agent header sent? Trust it by default...
3446 return true;
3447 }
3448 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
3449 foreach ( $wgBrowserBlackList as $browser ) {
3450 if ( preg_match( $browser, $currentbrowser ) ) {
3451 return false;
3452 }
3453 }
3454 return true;
3455 }
3456
3457 /**
3458 * Filter an input field through a Unicode de-armoring process if it
3459 * came from an old browser with known broken Unicode editing issues.
3460 *
3461 * @param $request WebRequest
3462 * @param $field String
3463 * @return String
3464 * @private
3465 */
3466 function safeUnicodeInput( $request, $field ) {
3467 $text = rtrim( $request->getText( $field ) );
3468 return $request->getBool( 'safemode' )
3469 ? $this->unmakesafe( $text )
3470 : $text;
3471 }
3472
3473 /**
3474 * @param $request WebRequest
3475 * @param $text string
3476 * @return string
3477 */
3478 function safeUnicodeText( $request, $text ) {
3479 $text = rtrim( $text );
3480 return $request->getBool( 'safemode' )
3481 ? $this->unmakesafe( $text )
3482 : $text;
3483 }
3484
3485 /**
3486 * Filter an output field through a Unicode armoring process if it is
3487 * going to an old browser with known broken Unicode editing issues.
3488 *
3489 * @param $text String
3490 * @return String
3491 * @private
3492 */
3493 function safeUnicodeOutput( $text ) {
3494 global $wgContLang;
3495 $codedText = $wgContLang->recodeForEdit( $text );
3496 return $this->checkUnicodeCompliantBrowser()
3497 ? $codedText
3498 : $this->makesafe( $codedText );
3499 }
3500
3501 /**
3502 * A number of web browsers are known to corrupt non-ASCII characters
3503 * in a UTF-8 text editing environment. To protect against this,
3504 * detected browsers will be served an armored version of the text,
3505 * with non-ASCII chars converted to numeric HTML character references.
3506 *
3507 * Preexisting such character references will have a 0 added to them
3508 * to ensure that round-trips do not alter the original data.
3509 *
3510 * @param $invalue String
3511 * @return String
3512 * @private
3513 */
3514 function makesafe( $invalue ) {
3515 // Armor existing references for reversability.
3516 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
3517
3518 $bytesleft = 0;
3519 $result = "";
3520 $working = 0;
3521 for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
3522 $bytevalue = ord( $invalue[$i] );
3523 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3524 $result .= chr( $bytevalue );
3525 $bytesleft = 0;
3526 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3527 $working = $working << 6;
3528 $working += ( $bytevalue & 0x3F );
3529 $bytesleft--;
3530 if ( $bytesleft <= 0 ) {
3531 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3532 }
3533 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3534 $working = $bytevalue & 0x1F;
3535 $bytesleft = 1;
3536 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3537 $working = $bytevalue & 0x0F;
3538 $bytesleft = 2;
3539 } else { // 1111 0xxx
3540 $working = $bytevalue & 0x07;
3541 $bytesleft = 3;
3542 }
3543 }
3544 return $result;
3545 }
3546
3547 /**
3548 * Reverse the previously applied transliteration of non-ASCII characters
3549 * back to UTF-8. Used to protect data from corruption by broken web browsers
3550 * as listed in $wgBrowserBlackList.
3551 *
3552 * @param $invalue String
3553 * @return String
3554 * @private
3555 */
3556 function unmakesafe( $invalue ) {
3557 $result = "";
3558 for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
3559 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
3560 $i += 3;
3561 $hexstring = "";
3562 do {
3563 $hexstring .= $invalue[$i];
3564 $i++;
3565 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3566
3567 // Do some sanity checks. These aren't needed for reversability,
3568 // but should help keep the breakage down if the editor
3569 // breaks one of the entities whilst editing.
3570 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3571 $codepoint = hexdec( $hexstring );
3572 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
3573 $codepoint = hexdec($hexstring);
3574 $result .= codepointToUtf8( $codepoint );
3575 } else {
3576 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3577 }
3578 } else {
3579 $result .= substr( $invalue, $i, 1 );
3580 }
3581 }
3582 // reverse the transform that we made for reversability reasons.
3583 return strtr( $result, array( "&#x0" => "&#x" ) );
3584 }
3585 }