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