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