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