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