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