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