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