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