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