7952f4f371eb52ebaa35a75a949f990855ac91ec
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * Contains the EditPage class
4 */
5
6 /**
7 * The edit page/HTML interface (split from Article)
8 * The actual database and text munging is still in Article,
9 * but it should get easier to call those from alternate
10 * interfaces.
11 */
12 class EditPage {
13 var $mArticle;
14 var $mTitle;
15 var $mMetaData = '';
16 var $isConflict = false;
17 var $isCssJsSubpage = false;
18 var $deletedSinceEdit = false;
19 var $formtype;
20 var $firsttime;
21 var $lastDelete;
22 var $mTokenOk = false;
23 var $mTokenOkExceptSuffix = false;
24 var $mTriedSave = false;
25 var $tooBig = false;
26 var $kblength = false;
27 var $missingComment = false;
28 var $missingSummary = false;
29 var $allowBlankSummary = false;
30 var $autoSumm = '';
31 var $hookError = '';
32 var $mPreviewTemplates;
33
34 # Form values
35 var $save = false, $preview = false, $diff = false;
36 var $minoredit = false, $watchthis = false, $recreate = false;
37 var $textbox1 = '', $textbox2 = '', $summary = '';
38 var $edittime = '', $section = '', $starttime = '';
39 var $oldid = 0, $editintro = '', $scrolltop = null;
40
41 # Placeholders for text injection by hooks (must be HTML)
42 # extensions should take care to _append_ to the present value
43 public $editFormPageTop; // Before even the preview
44 public $editFormTextTop;
45 public $editFormTextAfterWarn;
46 public $editFormTextAfterTools;
47 public $editFormTextBottom;
48
49 /**
50 * @todo document
51 * @param $article
52 */
53 function EditPage( $article ) {
54 $this->mArticle =& $article;
55 global $wgTitle;
56 $this->mTitle =& $wgTitle;
57
58 # Placeholders for text injection by hooks (empty per default)
59 $this->editFormPageTop =
60 $this->editFormTextTop =
61 $this->editFormTextAfterWarn =
62 $this->editFormTextAfterTools =
63 $this->editFormTextBottom = "";
64 }
65
66 /**
67 * Fetch initial editing page content.
68 */
69 private function getContent( $def_text = '' ) {
70 global $wgOut, $wgRequest, $wgParser;
71
72 # Get variables from query string :P
73 $section = $wgRequest->getVal( 'section' );
74 $preload = $wgRequest->getVal( 'preload' );
75 $undoafter = $wgRequest->getVal( 'undoafter' );
76 $undo = $wgRequest->getVal( 'undo' );
77
78 wfProfileIn( __METHOD__ );
79
80 $text = '';
81 if( !$this->mTitle->exists() ) {
82 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
83 # If this is a system message, get the default text.
84 $text = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
85 } else {
86 # If requested, preload some text.
87 $text = $this->getPreloadedText( $preload );
88 }
89 # We used to put MediaWiki:Newarticletext here if
90 # $text was empty at this point.
91 # This is now shown above the edit box instead.
92 } else {
93 // FIXME: may be better to use Revision class directly
94 // But don't mess with it just yet. Article knows how to
95 // fetch the page record from the high-priority server,
96 // which is needed to guarantee we don't pick up lagged
97 // information.
98
99 $text = $this->mArticle->getContent();
100
101 if ($undo > 0 && $undoafter > 0 && $undo < $undoafter) {
102 # If they got undoafter and undo round the wrong way, switch them
103 list( $undo, $undoafter ) = array( $undoafter, $undo );
104 }
105
106 if ( $undo > 0 && $undo > $undoafter ) {
107 # Undoing a specific edit overrides section editing; section-editing
108 # doesn't work with undoing.
109 if ( $undoafter ) {
110 $undorev = Revision::newFromId($undo);
111 $oldrev = Revision::newFromId($undoafter);
112 } else {
113 $undorev = Revision::newFromId($undo);
114 $oldrev = $undorev ? $undorev->getPrevious() : null;
115 }
116
117 #Sanity check, make sure it's the right page.
118 # Otherwise, $text will be left as-is.
119 if ( !is_null($undorev) && !is_null($oldrev) && $undorev->getPage()==$oldrev->getPage() && $undorev->getPage()==$this->mArticle->getID() ) {
120 $undorev_text = $undorev->getText();
121 $oldrev_text = $oldrev->getText();
122 $currev_text = $text;
123
124 #No use doing a merge if it's just a straight revert.
125 if ( $currev_text != $undorev_text ) {
126 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
127 } else {
128 $text = $oldrev_text;
129 $result = true;
130 }
131 } else {
132 // Failed basic sanity checks.
133 // Older revisions may have been removed since the link
134 // was created, or we may simply have got bogus input.
135 $result = false;
136 }
137
138 if( $result ) {
139 # Inform the user of our success and set an automatic edit summary
140 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
141 $firstrev = $oldrev->getNext();
142 # If we just undid one rev, use an autosummary
143 if ( $firstrev->mId == $undo ) {
144 $this->summary = wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
145 }
146 $this->formtype = 'diff';
147 } else {
148 # Warn the user that something went wrong
149 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
150 }
151 } else if( $section != '' ) {
152 if( $section == 'new' ) {
153 $text = $this->getPreloadedText( $preload );
154 } else {
155 $text = $wgParser->getSection( $text, $section, $def_text );
156 }
157 }
158 }
159
160 wfProfileOut( __METHOD__ );
161 return $text;
162 }
163
164 /**
165 * Get the contents of a page from its title and remove includeonly tags
166 *
167 * @param $preload String: the title of the page.
168 * @return string The contents of the page.
169 */
170 private function getPreloadedText($preload) {
171 if ( $preload === '' )
172 return '';
173 else {
174 $preloadTitle = Title::newFromText( $preload );
175 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
176 $rev=Revision::newFromTitle($preloadTitle);
177 if ( is_object( $rev ) ) {
178 $text = $rev->getText();
179 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
180 // its own mini-parser! -ævar
181 $text = preg_replace( '~</?includeonly>~', '', $text );
182 return $text;
183 } else
184 return '';
185 }
186 }
187 }
188
189 /**
190 * This is the function that extracts metadata from the article body on the first view.
191 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
192 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
193 */
194 function extractMetaDataFromArticle () {
195 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
196 $this->mMetaData = '' ;
197 if ( !$wgUseMetadataEdit ) return ;
198 if ( $wgMetadataWhitelist == '' ) return ;
199 $s = '' ;
200 $t = $this->getContent();
201
202 # MISSING : <nowiki> filtering
203
204 # Categories and language links
205 $t = explode ( "\n" , $t ) ;
206 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
207 $cat = $ll = array() ;
208 foreach ( $t AS $key => $x )
209 {
210 $y = trim ( strtolower ( $x ) ) ;
211 while ( substr ( $y , 0 , 2 ) == '[[' )
212 {
213 $y = explode ( ']]' , trim ( $x ) ) ;
214 $first = array_shift ( $y ) ;
215 $first = explode ( ':' , $first ) ;
216 $ns = array_shift ( $first ) ;
217 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
218 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
219 {
220 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
221 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
222 else $ll[] = $add ;
223 $x = implode ( ']]' , $y ) ;
224 $t[$key] = $x ;
225 $y = trim ( strtolower ( $x ) ) ;
226 }
227 }
228 }
229 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
230 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
231 $t = implode ( "\n" , $t ) ;
232
233 # Load whitelist
234 $sat = array () ; # stand-alone-templates; must be lowercase
235 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
236 $wl_article = new Article ( $wl_title ) ;
237 $wl = explode ( "\n" , $wl_article->getContent() ) ;
238 foreach ( $wl AS $x )
239 {
240 $isentry = false ;
241 $x = trim ( $x ) ;
242 while ( substr ( $x , 0 , 1 ) == '*' )
243 {
244 $isentry = true ;
245 $x = trim ( substr ( $x , 1 ) ) ;
246 }
247 if ( $isentry )
248 {
249 $sat[] = strtolower ( $x ) ;
250 }
251
252 }
253
254 # Templates, but only some
255 $t = explode ( '{{' , $t ) ;
256 $tl = array () ;
257 foreach ( $t AS $key => $x )
258 {
259 $y = explode ( '}}' , $x , 2 ) ;
260 if ( count ( $y ) == 2 )
261 {
262 $z = $y[0] ;
263 $z = explode ( '|' , $z ) ;
264 $tn = array_shift ( $z ) ;
265 if ( in_array ( strtolower ( $tn ) , $sat ) )
266 {
267 $tl[] = '{{' . $y[0] . '}}' ;
268 $t[$key] = $y[1] ;
269 $y = explode ( '}}' , $y[1] , 2 ) ;
270 }
271 else $t[$key] = '{{' . $x ;
272 }
273 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
274 else $t[$key] = $x ;
275 }
276 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
277 $t = implode ( '' , $t ) ;
278
279 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
280 $this->mArticle->mContent = $t ;
281 $this->mMetaData = $s ;
282 }
283
284 function submit() {
285 $this->edit();
286 }
287
288 /**
289 * This is the function that gets called for "action=edit". It
290 * sets up various member variables, then passes execution to
291 * another function, usually showEditForm()
292 *
293 * The edit form is self-submitting, so that when things like
294 * preview and edit conflicts occur, we get the same form back
295 * with the extra stuff added. Only when the final submission
296 * is made and all is well do we actually save and redirect to
297 * the newly-edited page.
298 */
299 function edit() {
300 global $wgOut, $wgUser, $wgRequest, $wgTitle;
301
302 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
303 return;
304
305 $fname = 'EditPage::edit';
306 wfProfileIn( $fname );
307 wfDebug( "$fname: enter\n" );
308
309 // this is not an article
310 $wgOut->setArticleFlag(false);
311
312 $this->importFormData( $wgRequest );
313 $this->firsttime = false;
314
315 if( $this->live ) {
316 $this->livePreview();
317 wfProfileOut( $fname );
318 return;
319 }
320
321 $permErrors = $this->mTitle->getUserPermissionsErrors('edit', $wgUser);
322 if( !$this->mTitle->exists() )
323 $permErrors += array_diff( $this->mTitle->getUserPermissionsErrors('create', $wgUser), $permErrors );
324
325 # Ignore some permissions errors.
326 $remove = array();
327 foreach( $permErrors as $error ) {
328 if ($this->preview || $this->diff &&
329 ($error[0] == 'blockedtext' || $error[0] == 'autoblockedtext'))
330 {
331 // Don't worry about blocks when previewing/diffing
332 $remove[] = $error;
333 }
334
335 if ($error[0] == 'readonlytext')
336 {
337 if ($this->edit) {
338 $this->formtype = 'preview';
339 } elseif ($this->save || $this->preview || $this->diff) {
340 $remove[] = $error;
341 }
342 }
343 }
344 # array_diff returns elements in $permErrors that are not in $remove.
345 $permErrors = array_diff( $permErrors, $remove );
346
347 if ( !empty($permErrors) )
348 {
349 wfDebug( "$fname: User can't edit\n" );
350 $wgOut->readOnlyPage( $this->getContent(), true, $permErrors );
351 wfProfileOut( $fname );
352 return;
353 } else {
354 if ( $this->save ) {
355 $this->formtype = 'save';
356 } else if ( $this->preview ) {
357 $this->formtype = 'preview';
358 } else if ( $this->diff ) {
359 $this->formtype = 'diff';
360 } else { # First time through
361 $this->firsttime = true;
362 if( $this->previewOnOpen() ) {
363 $this->formtype = 'preview';
364 } else {
365 $this->extractMetaDataFromArticle () ;
366 $this->formtype = 'initial';
367 }
368 }
369 }
370
371 wfProfileIn( "$fname-business-end" );
372
373 $this->isConflict = false;
374 // css / js subpages of user pages get a special treatment
375 $this->isCssJsSubpage = $wgTitle->isCssJsSubpage();
376 $this->isValidCssJsSubpage = $wgTitle->isValidCssJsSubpage();
377
378 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
379 * no matter it's current state
380 */
381 $this->deletedSinceEdit = false;
382 if ( $this->edittime != '' ) {
383 /* Note that we rely on logging table, which hasn't been always there,
384 * but that doesn't matter, because this only applies to brand new
385 * deletes. This is done on every preview and save request. Move it further down
386 * to only perform it on saves
387 */
388 if ( $this->mTitle->isDeleted() ) {
389 $this->lastDelete = $this->getLastDelete();
390 if ( !is_null($this->lastDelete) ) {
391 $deletetime = $this->lastDelete->log_timestamp;
392 if ( ($deletetime - $this->starttime) > 0 ) {
393 $this->deletedSinceEdit = true;
394 }
395 }
396 }
397 }
398
399 # Show applicable editing introductions
400 if( $this->formtype == 'initial' || $this->firsttime )
401 $this->showIntro();
402
403 if( $this->mTitle->isTalkPage() ) {
404 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
405 }
406
407 # Attempt submission here. This will check for edit conflicts,
408 # and redundantly check for locked database, blocked IPs, etc.
409 # that edit() already checked just in case someone tries to sneak
410 # in the back door with a hand-edited submission URL.
411
412 if ( 'save' == $this->formtype ) {
413 if ( !$this->attemptSave() ) {
414 wfProfileOut( "$fname-business-end" );
415 wfProfileOut( $fname );
416 return;
417 }
418 }
419
420 # First time through: get contents, set time for conflict
421 # checking, etc.
422 if ( 'initial' == $this->formtype || $this->firsttime ) {
423 if ($this->initialiseForm() === false) {
424 $this->noSuchSectionPage();
425 wfProfileOut( "$fname-business-end" );
426 wfProfileOut( $fname );
427 return;
428 }
429 if( !$this->mTitle->getArticleId() )
430 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
431 }
432
433 $this->showEditForm();
434 wfProfileOut( "$fname-business-end" );
435 wfProfileOut( $fname );
436 }
437
438 /**
439 * Should we show a preview when the edit form is first shown?
440 *
441 * @return bool
442 */
443 private function previewOnOpen() {
444 global $wgRequest, $wgUser;
445 if( $wgRequest->getVal( 'preview' ) == 'yes' ) {
446 // Explicit override from request
447 return true;
448 } elseif( $wgRequest->getVal( 'preview' ) == 'no' ) {
449 // Explicit override from request
450 return false;
451 } elseif( $this->section == 'new' ) {
452 // Nothing *to* preview for new sections
453 return false;
454 } elseif( ( $wgRequest->getVal( 'preload' ) !== '' || $this->mTitle->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
455 // Standard preference behaviour
456 return true;
457 } elseif( !$this->mTitle->exists() && $this->mTitle->getNamespace() == NS_CATEGORY ) {
458 // Categories are special
459 return true;
460 } else {
461 return false;
462 }
463 }
464
465 /**
466 * @todo document
467 * @param $request
468 */
469 function importFormData( &$request ) {
470 global $wgLang, $wgUser;
471 $fname = 'EditPage::importFormData';
472 wfProfileIn( $fname );
473
474 if( $request->wasPosted() ) {
475 # These fields need to be checked for encoding.
476 # Also remove trailing whitespace, but don't remove _initial_
477 # whitespace from the text boxes. This may be significant formatting.
478 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
479 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
480 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
481 # Truncate for whole multibyte characters. +5 bytes for ellipsis
482 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
483
484 $this->edittime = $request->getVal( 'wpEdittime' );
485 $this->starttime = $request->getVal( 'wpStarttime' );
486
487 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
488
489 if( is_null( $this->edittime ) ) {
490 # If the form is incomplete, force to preview.
491 wfDebug( "$fname: Form data appears to be incomplete\n" );
492 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
493 $this->preview = true;
494 } else {
495 /* Fallback for live preview */
496 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
497 $this->diff = $request->getCheck( 'wpDiff' );
498
499 // Remember whether a save was requested, so we can indicate
500 // if we forced preview due to session failure.
501 $this->mTriedSave = !$this->preview;
502
503 if ( $this->tokenOk( $request ) ) {
504 # Some browsers will not report any submit button
505 # if the user hits enter in the comment box.
506 # The unmarked state will be assumed to be a save,
507 # if the form seems otherwise complete.
508 wfDebug( "$fname: Passed token check.\n" );
509 } else if ( $this->diff ) {
510 # Failed token check, but only requested "Show Changes".
511 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
512 } else {
513 # Page might be a hack attempt posted from
514 # an external site. Preview instead of saving.
515 wfDebug( "$fname: Failed token check; forcing preview\n" );
516 $this->preview = true;
517 }
518 }
519 $this->save = ! ( $this->preview OR $this->diff );
520 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
521 $this->edittime = null;
522 }
523
524 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
525 $this->starttime = null;
526 }
527
528 $this->recreate = $request->getCheck( 'wpRecreate' );
529
530 $this->minoredit = $request->getCheck( 'wpMinoredit' );
531 $this->watchthis = $request->getCheck( 'wpWatchthis' );
532
533 # Don't force edit summaries when a user is editing their own user or talk page
534 if( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) && $this->mTitle->getText() == $wgUser->getName() ) {
535 $this->allowBlankSummary = true;
536 } else {
537 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' );
538 }
539
540 $this->autoSumm = $request->getText( 'wpAutoSummary' );
541 } else {
542 # Not a posted form? Start with nothing.
543 wfDebug( "$fname: Not a posted form.\n" );
544 $this->textbox1 = '';
545 $this->textbox2 = '';
546 $this->mMetaData = '';
547 $this->summary = '';
548 $this->edittime = '';
549 $this->starttime = wfTimestampNow();
550 $this->edit = false;
551 $this->preview = false;
552 $this->save = false;
553 $this->diff = false;
554 $this->minoredit = false;
555 $this->watchthis = false;
556 $this->recreate = false;
557 }
558
559 $this->oldid = $request->getInt( 'oldid' );
560
561 # Section edit can come from either the form or a link
562 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
563
564 $this->live = $request->getCheck( 'live' );
565 $this->editintro = $request->getText( 'editintro' );
566
567 wfProfileOut( $fname );
568 }
569
570 /**
571 * Make sure the form isn't faking a user's credentials.
572 *
573 * @param $request WebRequest
574 * @return bool
575 * @private
576 */
577 function tokenOk( &$request ) {
578 global $wgUser;
579 $token = $request->getVal( 'wpEditToken' );
580 $this->mTokenOk = $wgUser->matchEditToken( $token );
581 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
582 return $this->mTokenOk;
583 }
584
585 /**
586 * Show all applicable editing introductions
587 */
588 private function showIntro() {
589 global $wgOut, $wgUser;
590 if( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
591 if( $wgUser->isLoggedIn() ) {
592 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
593 } else {
594 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
595 }
596 $this->showDeletionLog( $wgOut );
597 }
598 }
599
600 /**
601 * Attempt to show a custom editing introduction, if supplied
602 *
603 * @return bool
604 */
605 private function showCustomIntro() {
606 if( $this->editintro ) {
607 $title = Title::newFromText( $this->editintro );
608 if( $title instanceof Title && $title->exists() && $title->userCanRead() ) {
609 global $wgOut;
610 $revision = Revision::newFromTitle( $title );
611 $wgOut->addSecondaryWikiText( $revision->getText() );
612 return true;
613 } else {
614 return false;
615 }
616 } else {
617 return false;
618 }
619 }
620
621 /**
622 * Attempt submission
623 * @return bool false if output is done, true if the rest of the form should be displayed
624 */
625 function attemptSave() {
626 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut, $wgParser;
627 global $wgMaxArticleSize;
628
629 $fname = 'EditPage::attemptSave';
630 wfProfileIn( $fname );
631 wfProfileIn( "$fname-checks" );
632
633 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
634 {
635 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
636 return false;
637 }
638
639 # Reintegrate metadata
640 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
641 $this->mMetaData = '' ;
642
643 # Check for spam
644 $matches = array();
645 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
646 $this->spamPage ( $matches[0] );
647 wfProfileOut( "$fname-checks" );
648 wfProfileOut( $fname );
649 return false;
650 }
651 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
652 # Error messages or other handling should be performed by the filter function
653 wfProfileOut( $fname );
654 wfProfileOut( "$fname-checks" );
655 return false;
656 }
657 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError ) ) ) {
658 # Error messages etc. could be handled within the hook...
659 wfProfileOut( $fname );
660 wfProfileOut( "$fname-checks" );
661 return false;
662 } elseif( $this->hookError != '' ) {
663 # ...or the hook could be expecting us to produce an error
664 wfProfileOut( "$fname-checks " );
665 wfProfileOut( $fname );
666 return true;
667 }
668 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
669 # Check block state against master, thus 'false'.
670 $this->blockedPage();
671 wfProfileOut( "$fname-checks" );
672 wfProfileOut( $fname );
673 return false;
674 }
675 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
676 if ( $this->kblength > $wgMaxArticleSize ) {
677 // Error will be displayed by showEditForm()
678 $this->tooBig = true;
679 wfProfileOut( "$fname-checks" );
680 wfProfileOut( $fname );
681 return true;
682 }
683
684 if ( !$wgUser->isAllowed('edit') ) {
685 if ( $wgUser->isAnon() ) {
686 $this->userNotLoggedInPage();
687 wfProfileOut( "$fname-checks" );
688 wfProfileOut( $fname );
689 return false;
690 }
691 else {
692 $wgOut->readOnlyPage();
693 wfProfileOut( "$fname-checks" );
694 wfProfileOut( $fname );
695 return false;
696 }
697 }
698
699 if ( wfReadOnly() ) {
700 $wgOut->readOnlyPage();
701 wfProfileOut( "$fname-checks" );
702 wfProfileOut( $fname );
703 return false;
704 }
705 if ( $wgUser->pingLimiter() ) {
706 $wgOut->rateLimited();
707 wfProfileOut( "$fname-checks" );
708 wfProfileOut( $fname );
709 return false;
710 }
711
712 # If the article has been deleted while editing, don't save it without
713 # confirmation
714 if ( $this->deletedSinceEdit && !$this->recreate ) {
715 wfProfileOut( "$fname-checks" );
716 wfProfileOut( $fname );
717 return true;
718 }
719
720 wfProfileOut( "$fname-checks" );
721
722 # If article is new, insert it.
723 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
724 if ( 0 == $aid ) {
725
726 // Late check for create permission, just in case *PARANOIA*
727 if ( !$this->mTitle->userCan( 'create' ) ) {
728 wfDebug( "$fname: no create permission\n" );
729 $this->noCreatePermission();
730 wfProfileOut( $fname );
731 return;
732 }
733
734 # Don't save a new article if it's blank.
735 if ( ( '' == $this->textbox1 ) ) {
736 $wgOut->redirect( $this->mTitle->getFullURL() );
737 wfProfileOut( $fname );
738 return false;
739 }
740
741 $isComment=($this->section=='new');
742 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
743 $this->minoredit, $this->watchthis, false, $isComment);
744
745 wfProfileOut( $fname );
746 return false;
747 }
748
749 # Article exists. Check for edit conflict.
750
751 $this->mArticle->clear(); # Force reload of dates, etc.
752 $this->mArticle->forUpdate( true ); # Lock the article
753
754 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
755
756 if( $this->mArticle->getTimestamp() != $this->edittime ) {
757 $this->isConflict = true;
758 if( $this->section == 'new' ) {
759 if( $this->mArticle->getUserText() == $wgUser->getName() &&
760 $this->mArticle->getComment() == $this->summary ) {
761 // Probably a duplicate submission of a new comment.
762 // This can happen when squid resends a request after
763 // a timeout but the first one actually went through.
764 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
765 } else {
766 // New comment; suppress conflict.
767 $this->isConflict = false;
768 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
769 }
770 }
771 }
772 $userid = $wgUser->getID();
773
774 if ( $this->isConflict) {
775 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
776 $this->mArticle->getTimestamp() . "')\n" );
777 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
778 }
779 else {
780 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
781 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
782 }
783 if( is_null( $text ) ) {
784 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
785 $this->isConflict = true;
786 $text = $this->textbox1;
787 }
788
789 # Suppress edit conflict with self, except for section edits where merging is required.
790 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
791 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
792 $this->isConflict = false;
793 } else {
794 # switch from section editing to normal editing in edit conflict
795 if($this->isConflict) {
796 # Attempt merge
797 if( $this->mergeChangesInto( $text ) ){
798 // Successful merge! Maybe we should tell the user the good news?
799 $this->isConflict = false;
800 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
801 } else {
802 $this->section = '';
803 $this->textbox1 = $text;
804 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
805 }
806 }
807 }
808
809 if ( $this->isConflict ) {
810 wfProfileOut( $fname );
811 return true;
812 }
813
814 $oldtext = $this->mArticle->getContent();
815
816 # Handle the user preference to force summaries here, but not for null edits
817 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary')
818 && 0 != strcmp($oldtext, $text) && !Article::getRedirectAutosummary( $text )) {
819 if( md5( $this->summary ) == $this->autoSumm ) {
820 $this->missingSummary = true;
821 wfProfileOut( $fname );
822 return( true );
823 }
824 }
825
826 #And a similar thing for new sections
827 if( $this->section == 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
828 if (trim($this->summary) == '') {
829 $this->missingSummary = true;
830 wfProfileOut( $fname );
831 return( true );
832 }
833 }
834
835 # All's well
836 wfProfileIn( "$fname-sectionanchor" );
837 $sectionanchor = '';
838 if( $this->section == 'new' ) {
839 if ( $this->textbox1 == '' ) {
840 $this->missingComment = true;
841 return true;
842 }
843 if( $this->summary != '' ) {
844 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary );
845 # This is a new section, so create a link to the new section
846 # in the revision summary.
847 $cleanSummary = $wgParser->stripSectionName( $this->summary );
848 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
849 }
850 } elseif( $this->section != '' ) {
851 # Try to get a section anchor from the section source, redirect to edited section if header found
852 # XXX: might be better to integrate this into Article::replaceSection
853 # for duplicate heading checking and maybe parsing
854 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
855 # we can't deal with anchors, includes, html etc in the header for now,
856 # headline would need to be parsed to improve this
857 if($hasmatch and strlen($matches[2]) > 0) {
858 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
859 }
860 }
861 wfProfileOut( "$fname-sectionanchor" );
862
863 // Save errors may fall down to the edit form, but we've now
864 // merged the section into full text. Clear the section field
865 // so that later submission of conflict forms won't try to
866 // replace that into a duplicated mess.
867 $this->textbox1 = $text;
868 $this->section = '';
869
870 // Check for length errors again now that the section is merged in
871 $this->kblength = (int)(strlen( $text ) / 1024);
872 if ( $this->kblength > $wgMaxArticleSize ) {
873 $this->tooBig = true;
874 wfProfileOut( $fname );
875 return true;
876 }
877
878 # update the article here
879 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
880 $this->watchthis, '', $sectionanchor ) ) {
881 wfProfileOut( $fname );
882 return false;
883 } else {
884 $this->isConflict = true;
885 }
886 wfProfileOut( $fname );
887 return true;
888 }
889
890 /**
891 * Initialise form fields in the object
892 * Called on the first invocation, e.g. when a user clicks an edit link
893 */
894 function initialiseForm() {
895 $this->edittime = $this->mArticle->getTimestamp();
896 $this->summary = '';
897 $this->textbox1 = $this->getContent(false);
898 if ($this->textbox1 === false) return false;
899
900 if ( !$this->mArticle->exists() && $this->mArticle->mTitle->getNamespace() == NS_MEDIAWIKI )
901 $this->textbox1 = wfMsgWeirdKey( $this->mArticle->mTitle->getText() );
902 wfProxyCheck();
903 return true;
904 }
905
906 /**
907 * Send the edit form and related headers to $wgOut
908 * @param $formCallback Optional callable that takes an OutputPage
909 * parameter; will be called during form output
910 * near the top, for captchas and the like.
911 */
912 function showEditForm( $formCallback=null ) {
913 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
914
915 $fname = 'EditPage::showEditForm';
916 wfProfileIn( $fname );
917
918 $sk = $wgUser->getSkin();
919
920 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
921
922 $wgOut->setRobotpolicy( 'noindex,nofollow' );
923
924 # Enabled article-related sidebar, toplinks, etc.
925 $wgOut->setArticleRelated( true );
926
927 if ( $this->formtype == 'preview' ) {
928 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
929 }
930
931 if ( $this->isConflict ) {
932 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
933 $wgOut->setPageTitle( $s );
934 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
935
936 $this->textbox2 = $this->textbox1;
937 $this->textbox1 = $this->getContent();
938 $this->edittime = $this->mArticle->getTimestamp();
939 } else {
940
941 if( $this->section != '' ) {
942 if( $this->section == 'new' ) {
943 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
944 } else {
945 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
946 $matches = array();
947 if( !$this->summary && !$this->preview && !$this->diff ) {
948 preg_match( "/^(=+)(.+)\\1/mi",
949 $this->textbox1,
950 $matches );
951 if( !empty( $matches[2] ) ) {
952 global $wgParser;
953 $this->summary = "/* " .
954 $wgParser->stripSectionName(trim($matches[2])) .
955 " */ ";
956 }
957 }
958 }
959 } else {
960 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
961 }
962 $wgOut->setPageTitle( $s );
963
964 if ( $this->missingComment ) {
965 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
966 }
967
968 if( $this->missingSummary && $this->section != 'new' ) {
969 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
970 }
971
972 if( $this->missingSummary && $this->section == 'new' ) {
973 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
974 }
975
976 if( !$this->hookError == '' ) {
977 $wgOut->addWikiText( $this->hookError );
978 }
979
980 if ( !$this->checkUnicodeCompliantBrowser() ) {
981 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
982 }
983 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
984 // Let sysop know that this will make private content public if saved
985
986 if( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) {
987 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
988 } else if( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
989 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
990 }
991
992 if( !$this->mArticle->mRevision->isCurrent() ) {
993 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
994 $wgOut->addWikiText( wfMsg( 'editingold' ) );
995 }
996 }
997 }
998
999 if( wfReadOnly() ) {
1000 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
1001 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
1002 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
1003 } else {
1004 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
1005 # Check the skin exists
1006 if( $this->isValidCssJsSubpage ) {
1007 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
1008 } else {
1009 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
1010 }
1011 }
1012 }
1013
1014 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1015 # Show a warning if editing an interface message
1016 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
1017 } elseif( $this->mTitle->isProtected( 'edit' ) ) {
1018 # Is the title semi-protected?
1019 if( $this->mTitle->isSemiProtected() ) {
1020 $notice = wfMsg( 'semiprotectedpagewarning' );
1021 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' )
1022 $notice = '';
1023 } else {
1024 # Then it must be protected based on static groups (regular)
1025 $notice = wfMsg( 'protectedpagewarning' );
1026 }
1027 $wgOut->addWikiText( $notice );
1028 }
1029 if ( $this->mTitle->isCascadeProtected() ) {
1030 # Is this page under cascading protection from some source pages?
1031 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1032 if ( count($cascadeSources) > 0 ) {
1033 # Explain, and list the titles responsible
1034 $notice = wfMsgExt( 'cascadeprotectedwarning', array('parsemag'), count($cascadeSources) ) . "\n";
1035 foreach( $cascadeSources as $page ) {
1036 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1037 }
1038 }
1039 $wgOut->addWikiText( $notice );
1040 }
1041
1042 if ( $this->kblength === false ) {
1043 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
1044 }
1045 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1046 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
1047 } elseif( $this->kblength > 29 ) {
1048 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
1049 }
1050
1051 #need to parse the preview early so that we know which templates are used,
1052 #otherwise users with "show preview after edit box" will get a blank list
1053 if ( $this->formtype == 'preview' ) {
1054 $previewOutput = $this->getPreviewText();
1055 }
1056
1057 $rows = $wgUser->getIntOption( 'rows' );
1058 $cols = $wgUser->getIntOption( 'cols' );
1059
1060 $ew = $wgUser->getOption( 'editwidth' );
1061 if ( $ew ) $ew = " style=\"width:100%\"";
1062 else $ew = '';
1063
1064 $q = 'action=submit';
1065 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1066 $action = $this->mTitle->escapeLocalURL( $q );
1067
1068 $summary = wfMsg('summary');
1069 $subject = wfMsg('subject');
1070
1071 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
1072 wfMsgExt('cancel', array('parseinline')) );
1073 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1074 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1075 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1076 htmlspecialchars( wfMsg( 'newwindow' ) );
1077
1078 global $wgRightsText;
1079 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1080 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
1081 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1082 $wgRightsText ) . "\n</div>";
1083
1084 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
1085 # prepare toolbar for edit buttons
1086 $toolbar = $this->getEditToolbar();
1087 } else {
1088 $toolbar = '';
1089 }
1090
1091 // activate checkboxes if user wants them to be always active
1092 if( !$this->preview && !$this->diff ) {
1093 # Sort out the "watch" checkbox
1094 if( $wgUser->getOption( 'watchdefault' ) ) {
1095 # Watch all edits
1096 $this->watchthis = true;
1097 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1098 # Watch creations
1099 $this->watchthis = true;
1100 } elseif( $this->mTitle->userIsWatching() ) {
1101 # Already watched
1102 $this->watchthis = true;
1103 }
1104
1105 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1106 }
1107
1108 $wgOut->addHTML( $this->editFormPageTop );
1109
1110 if ( $wgUser->getOption( 'previewontop' ) ) {
1111
1112 if ( 'preview' == $this->formtype ) {
1113 $this->showPreview( $previewOutput );
1114 } else {
1115 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1116 }
1117
1118 if ( 'diff' == $this->formtype ) {
1119 $this->showDiff();
1120 }
1121 }
1122
1123
1124 $wgOut->addHTML( $this->editFormTextTop );
1125
1126 # if this is a comment, show a subject line at the top, which is also the edit summary.
1127 # Otherwise, show a summary field at the bottom
1128 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
1129 if( $this->section == 'new' ) {
1130 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span>\n<div class='editOptions'>\n<input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
1131 $editsummary = '';
1132 $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1133 $summarypreview = '';
1134 } else {
1135 $commentsubject = '';
1136 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span>\n<div class='editOptions'>\n<input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
1137 $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1138 $subjectpreview = '';
1139 }
1140
1141 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1142 if( !$this->preview && !$this->diff ) {
1143 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1144 }
1145 $templates = ($this->preview || $this->section != '') ? $this->mPreviewTemplates : $this->mArticle->getUsedTemplates();
1146 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1147
1148 global $wgUseMetadataEdit ;
1149 if ( $wgUseMetadataEdit ) {
1150 $metadata = $this->mMetaData ;
1151 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1152 $top = wfMsgWikiHtml( 'metadata_help' );
1153 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1154 }
1155 else $metadata = "" ;
1156
1157 $hidden = '';
1158 $recreate = '';
1159 if ($this->deletedSinceEdit) {
1160 if ( 'save' != $this->formtype ) {
1161 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1162 } else {
1163 // Hide the toolbar and edit area, use can click preview to get it back
1164 // Add an confirmation checkbox and explanation.
1165 $toolbar = '';
1166 $hidden = 'type="hidden" style="display:none;"';
1167 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
1168 $recreate .=
1169 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1170 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1171 }
1172 }
1173
1174 $tabindex = 2;
1175
1176 $checkboxes = self::getCheckboxes( $tabindex, $sk,
1177 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1178
1179 $checkboxhtml = implode( $checkboxes, "\n" );
1180
1181 $buttons = $this->getEditButtons( $tabindex );
1182 $buttonshtml = implode( $buttons, "\n" );
1183
1184 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1185 ? '' : Xml::hidden( 'safemode', '1' );
1186
1187 $wgOut->addHTML( <<<END
1188 {$toolbar}
1189 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1190 END
1191 );
1192
1193 if( is_callable( $formCallback ) ) {
1194 call_user_func_array( $formCallback, array( &$wgOut ) );
1195 }
1196
1197 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1198
1199 // Put these up at the top to ensure they aren't lost on early form submission
1200 $wgOut->addHTML( "
1201 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1202 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1203 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1204 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1205
1206 $wgOut->addHTML( <<<END
1207 $recreate
1208 {$commentsubject}
1209 {$subjectpreview}
1210 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1211 cols='{$cols}'{$ew} $hidden>
1212 END
1213 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1214 "
1215 </textarea>
1216 " );
1217
1218 $wgOut->addWikiText( $copywarn );
1219 $wgOut->addHTML( $this->editFormTextAfterWarn );
1220 $wgOut->addHTML( "
1221 {$metadata}
1222 {$editsummary}
1223 {$summarypreview}
1224 {$checkboxhtml}
1225 {$safemodehtml}
1226 ");
1227
1228 $wgOut->addHTML(
1229 "<div class='editButtons'>
1230 {$buttonshtml}
1231 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1232 </div><!-- editButtons -->
1233 </div><!-- editOptions -->");
1234
1235 $wgOut->addHtml( '<div class="mw-editTools">' );
1236 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1237 $wgOut->addHtml( '</div>' );
1238
1239 $wgOut->addHTML( $this->editFormTextAfterTools );
1240
1241 $wgOut->addHTML( "
1242 <div class='templatesUsed'>
1243 {$formattedtemplates}
1244 </div>
1245 " );
1246
1247 /**
1248 * To make it harder for someone to slip a user a page
1249 * which submits an edit form to the wiki without their
1250 * knowledge, a random token is associated with the login
1251 * session. If it's not passed back with the submission,
1252 * we won't save the page, or render user JavaScript and
1253 * CSS previews.
1254 *
1255 * For anon editors, who may not have a session, we just
1256 * include the constant suffix to prevent editing from
1257 * broken text-mangling proxies.
1258 */
1259 $token = htmlspecialchars( $wgUser->editToken() );
1260 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1261
1262
1263 # If a blank edit summary was previously provided, and the appropriate
1264 # user preference is active, pass a hidden tag here. This will stop the
1265 # user being bounced back more than once in the event that a summary
1266 # is not required.
1267 if( $this->missingSummary ) {
1268 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1269 }
1270
1271 # For a bit more sophisticated detection of blank summaries, hash the
1272 # automatic one and pass that in a hidden field.
1273 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1274 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1275
1276 if ( $this->isConflict ) {
1277 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1278
1279 $de = new DifferenceEngine( $this->mTitle );
1280 $de->setText( $this->textbox2, $this->textbox1 );
1281 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1282
1283 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1284 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1285 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1286 }
1287 $wgOut->addHTML( $this->editFormTextBottom );
1288 $wgOut->addHTML( "</form>\n" );
1289 if ( !$wgUser->getOption( 'previewontop' ) ) {
1290
1291 if ( $this->formtype == 'preview') {
1292 $this->showPreview( $previewOutput );
1293 } else {
1294 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1295 }
1296
1297 if ( $this->formtype == 'diff') {
1298 $this->showDiff();
1299 }
1300
1301 }
1302
1303 wfProfileOut( $fname );
1304 }
1305
1306 /**
1307 * Append preview output to $wgOut.
1308 * Includes category rendering if this is a category page.
1309 *
1310 * @param string $text The HTML to be output for the preview.
1311 */
1312 private function showPreview( $text ) {
1313 global $wgOut;
1314
1315 $wgOut->addHTML( '<div id="wikiPreview">' );
1316 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1317 $this->mArticle->openShowCategory();
1318 }
1319 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1320 $wgOut->addHTML( $text );
1321 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1322 $this->mArticle->closeShowCategory();
1323 }
1324 $wgOut->addHTML( '</div>' );
1325 }
1326
1327 /**
1328 * Live Preview lets us fetch rendered preview page content and
1329 * add it to the page without refreshing the whole page.
1330 * If not supported by the browser it will fall through to the normal form
1331 * submission method.
1332 *
1333 * This function outputs a script tag to support live preview, and
1334 * returns an onclick handler which should be added to the attributes
1335 * of the preview button
1336 */
1337 function doLivePreviewScript() {
1338 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1339 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1340 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1341 '"></script>' . "\n" );
1342 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1343 return "return !lpDoPreview(" .
1344 "editform.wpTextbox1.value," .
1345 '"' . $liveAction . '"' . ")";
1346 }
1347
1348 function getLastDelete() {
1349 $dbr = wfGetDB( DB_SLAVE );
1350 $fname = 'EditPage::getLastDelete';
1351 $res = $dbr->select(
1352 array( 'logging', 'user' ),
1353 array( 'log_type',
1354 'log_action',
1355 'log_timestamp',
1356 'log_user',
1357 'log_namespace',
1358 'log_title',
1359 'log_comment',
1360 'log_params',
1361 'user_name', ),
1362 array( 'log_namespace' => $this->mTitle->getNamespace(),
1363 'log_title' => $this->mTitle->getDBkey(),
1364 'log_type' => 'delete',
1365 'log_action' => 'delete',
1366 'user_id=log_user' ),
1367 $fname,
1368 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1369
1370 if($dbr->numRows($res) == 1) {
1371 while ( $x = $dbr->fetchObject ( $res ) )
1372 $data = $x;
1373 $dbr->freeResult ( $res ) ;
1374 } else {
1375 $data = null;
1376 }
1377 return $data;
1378 }
1379
1380 /**
1381 * @todo document
1382 */
1383 function getPreviewText() {
1384 global $wgOut, $wgUser, $wgTitle, $wgParser;
1385
1386 $fname = 'EditPage::getPreviewText';
1387 wfProfileIn( $fname );
1388
1389 if ( $this->mTriedSave && !$this->mTokenOk ) {
1390 if ( $this->mTokenOkExceptSuffix ) {
1391 $msg = 'token_suffix_mismatch';
1392 } else {
1393 $msg = 'session_fail_preview';
1394 }
1395 } else {
1396 $msg = 'previewnote';
1397 }
1398 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1399 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1400 if ( $this->isConflict ) {
1401 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1402 }
1403
1404 $parserOptions = ParserOptions::newFromUser( $wgUser );
1405 $parserOptions->setEditSection( false );
1406
1407 global $wgRawHtml;
1408 if( $wgRawHtml && !$this->mTokenOk ) {
1409 // Could be an offsite preview attempt. This is very unsafe if
1410 // HTML is enabled, as it could be an attack.
1411 return $wgOut->parse( "<div class='previewnote'>" .
1412 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1413 }
1414
1415 # don't parse user css/js, show message about preview
1416 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1417
1418 if ( $this->isCssJsSubpage ) {
1419 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1420 $previewtext = wfMsg('usercsspreview');
1421 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1422 $previewtext = wfMsg('userjspreview');
1423 }
1424 $parserOptions->setTidy(true);
1425 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1426 $wgOut->addHTML( $parserOutput->mText );
1427 wfProfileOut( $fname );
1428 return $previewhead;
1429 } else {
1430 $toparse = $this->textbox1;
1431
1432 # If we're adding a comment, we need to show the
1433 # summary as the headline
1434 if($this->section=="new" && $this->summary!="") {
1435 $toparse="== {$this->summary} ==\n\n".$toparse;
1436 }
1437
1438 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1439 $parserOptions->setTidy(true);
1440 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1441 $wgTitle, $parserOptions );
1442
1443 $previewHTML = $parserOutput->getText();
1444 $wgOut->addParserOutputNoText( $parserOutput );
1445
1446 # ParserOutput might have altered the page title, so reset it
1447 $wgOut->setPageTitle( wfMsg( 'editing', $this->mTitle->getPrefixedText() ) );
1448
1449 foreach ( $parserOutput->getTemplates() as $ns => $template)
1450 foreach ( array_keys( $template ) as $dbk)
1451 $this->mPreviewTemplates[] = Title::makeTitle($ns, $dbk);
1452
1453 wfProfileOut( $fname );
1454 return $previewhead . $previewHTML;
1455 }
1456 }
1457
1458 /**
1459 * Call the stock "user is blocked" page
1460 */
1461 function blockedPage() {
1462 global $wgOut, $wgUser;
1463 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1464
1465 # If the user made changes, preserve them when showing the markup
1466 # (This happens when a user is blocked during edit, for instance)
1467 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1468 if( $first ) {
1469 $source = $this->mTitle->exists() ? $this->getContent() : false;
1470 } else {
1471 $source = $this->textbox1;
1472 }
1473
1474 # Spit out the source or the user's modified version
1475 if( $source !== false ) {
1476 $rows = $wgUser->getOption( 'rows' );
1477 $cols = $wgUser->getOption( 'cols' );
1478 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1479 $wgOut->addHtml( '<hr />' );
1480 $wgOut->addWikiText( wfMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() ) );
1481 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1482 }
1483 }
1484
1485 /**
1486 * Produce the stock "please login to edit pages" page
1487 */
1488 function userNotLoggedInPage() {
1489 global $wgUser, $wgOut;
1490 $skin = $wgUser->getSkin();
1491
1492 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1493 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle->getPrefixedUrl() );
1494
1495 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1496 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1497 $wgOut->setArticleRelated( false );
1498
1499 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1500 $wgOut->returnToMain( false, $this->mTitle );
1501 }
1502
1503 /**
1504 * Creates a basic error page which informs the user that
1505 * they have to validate their email address before being
1506 * allowed to edit.
1507 */
1508 function userNotConfirmedPage() {
1509 global $wgOut;
1510
1511 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1512 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1513 $wgOut->setArticleRelated( false );
1514
1515 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1516 $wgOut->returnToMain( false, $this->mTitle );
1517 }
1518
1519 /**
1520 * Creates a basic error page which informs the user that
1521 * they have attempted to edit a nonexistant section.
1522 */
1523 function noSuchSectionPage() {
1524 global $wgOut;
1525
1526 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1527 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1528 $wgOut->setArticleRelated( false );
1529
1530 $wgOut->addWikiText( wfMsg( 'nosuchsectiontext', $this->section ) );
1531 $wgOut->returnToMain( false, $this->mTitle );
1532 }
1533
1534 /**
1535 * Produce the stock "your edit contains spam" page
1536 *
1537 * @param $match Text which triggered one or more filters
1538 */
1539 function spamPage( $match = false ) {
1540 global $wgOut;
1541
1542 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1543 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1544 $wgOut->setArticleRelated( false );
1545
1546 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1547 if ( $match )
1548 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1549
1550 $wgOut->returnToMain( false, $this->mTitle );
1551 }
1552
1553 /**
1554 * @private
1555 * @todo document
1556 */
1557 function mergeChangesInto( &$editText ){
1558 $fname = 'EditPage::mergeChangesInto';
1559 wfProfileIn( $fname );
1560
1561 $db = wfGetDB( DB_MASTER );
1562
1563 // This is the revision the editor started from
1564 $baseRevision = Revision::loadFromTimestamp(
1565 $db, $this->mArticle->mTitle, $this->edittime );
1566 if( is_null( $baseRevision ) ) {
1567 wfProfileOut( $fname );
1568 return false;
1569 }
1570 $baseText = $baseRevision->getText();
1571
1572 // The current state, we want to merge updates into it
1573 $currentRevision = Revision::loadFromTitle(
1574 $db, $this->mArticle->mTitle );
1575 if( is_null( $currentRevision ) ) {
1576 wfProfileOut( $fname );
1577 return false;
1578 }
1579 $currentText = $currentRevision->getText();
1580
1581 $result = '';
1582 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1583 $editText = $result;
1584 wfProfileOut( $fname );
1585 return true;
1586 } else {
1587 wfProfileOut( $fname );
1588 return false;
1589 }
1590 }
1591
1592 /**
1593 * Check if the browser is on a blacklist of user-agents known to
1594 * mangle UTF-8 data on form submission. Returns true if Unicode
1595 * should make it through, false if it's known to be a problem.
1596 * @return bool
1597 * @private
1598 */
1599 function checkUnicodeCompliantBrowser() {
1600 global $wgBrowserBlackList;
1601 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1602 // No User-Agent header sent? Trust it by default...
1603 return true;
1604 }
1605 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1606 foreach ( $wgBrowserBlackList as $browser ) {
1607 if ( preg_match($browser, $currentbrowser) ) {
1608 return false;
1609 }
1610 }
1611 return true;
1612 }
1613
1614 /**
1615 * @deprecated use $wgParser->stripSectionName()
1616 */
1617 function pseudoParseSectionAnchor( $text ) {
1618 global $wgParser;
1619 return $wgParser->stripSectionName( $text );
1620 }
1621
1622 /**
1623 * Format an anchor fragment as it would appear for a given section name
1624 * @param string $text
1625 * @return string
1626 * @private
1627 */
1628 function sectionAnchor( $text ) {
1629 global $wgParser;
1630 return $wgParser->guessSectionNameFromWikiText( $text );
1631 }
1632
1633 /**
1634 * Shows a bulletin board style toolbar for common editing functions.
1635 * It can be disabled in the user preferences.
1636 * The necessary JavaScript code can be found in style/wikibits.js.
1637 */
1638 function getEditToolbar() {
1639 global $wgStylePath, $wgContLang, $wgJsMimeType;
1640
1641 /**
1642 * toolarray an array of arrays which each include the filename of
1643 * the button image (without path), the opening tag, the closing tag,
1644 * and optionally a sample text that is inserted between the two when no
1645 * selection is highlighted.
1646 * The tip text is shown when the user moves the mouse over the button.
1647 *
1648 * Already here are accesskeys (key), which are not used yet until someone
1649 * can figure out a way to make them work in IE. However, we should make
1650 * sure these keys are not defined on the edit page.
1651 */
1652 $toolarray = array(
1653 array( 'image' => 'button_bold.png',
1654 'id' => 'mw-editbutton-bold',
1655 'open' => '\\\'\\\'\\\'',
1656 'close' => '\\\'\\\'\\\'',
1657 'sample'=> wfMsg('bold_sample'),
1658 'tip' => wfMsg('bold_tip'),
1659 'key' => 'B'
1660 ),
1661 array( 'image' => 'button_italic.png',
1662 'id' => 'mw-editbutton-italic',
1663 'open' => '\\\'\\\'',
1664 'close' => '\\\'\\\'',
1665 'sample'=> wfMsg('italic_sample'),
1666 'tip' => wfMsg('italic_tip'),
1667 'key' => 'I'
1668 ),
1669 array( 'image' => 'button_link.png',
1670 'id' => 'mw-editbutton-link',
1671 'open' => '[[',
1672 'close' => ']]',
1673 'sample'=> wfMsg('link_sample'),
1674 'tip' => wfMsg('link_tip'),
1675 'key' => 'L'
1676 ),
1677 array( 'image' => 'button_extlink.png',
1678 'id' => 'mw-editbutton-extlink',
1679 'open' => '[',
1680 'close' => ']',
1681 'sample'=> wfMsg('extlink_sample'),
1682 'tip' => wfMsg('extlink_tip'),
1683 'key' => 'X'
1684 ),
1685 array( 'image' => 'button_headline.png',
1686 'id' => 'mw-editbutton-headline',
1687 'open' => "\\n== ",
1688 'close' => " ==\\n",
1689 'sample'=> wfMsg('headline_sample'),
1690 'tip' => wfMsg('headline_tip'),
1691 'key' => 'H'
1692 ),
1693 array( 'image' => 'button_image.png',
1694 'id' => 'mw-editbutton-image',
1695 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1696 'close' => ']]',
1697 'sample'=> wfMsg('image_sample'),
1698 'tip' => wfMsg('image_tip'),
1699 'key' => 'D'
1700 ),
1701 array( 'image' => 'button_media.png',
1702 'id' => 'mw-editbutton-media',
1703 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1704 'close' => ']]',
1705 'sample'=> wfMsg('media_sample'),
1706 'tip' => wfMsg('media_tip'),
1707 'key' => 'M'
1708 ),
1709 array( 'image' => 'button_math.png',
1710 'id' => 'mw-editbutton-math',
1711 'open' => "<math>",
1712 'close' => "<\\/math>",
1713 'sample'=> wfMsg('math_sample'),
1714 'tip' => wfMsg('math_tip'),
1715 'key' => 'C'
1716 ),
1717 array( 'image' => 'button_nowiki.png',
1718 'id' => 'mw-editbutton-nowiki',
1719 'open' => "<nowiki>",
1720 'close' => "<\\/nowiki>",
1721 'sample'=> wfMsg('nowiki_sample'),
1722 'tip' => wfMsg('nowiki_tip'),
1723 'key' => 'N'
1724 ),
1725 array( 'image' => 'button_sig.png',
1726 'id' => 'mw-editbutton-signature',
1727 'open' => '--~~~~',
1728 'close' => '',
1729 'sample'=> '',
1730 'tip' => wfMsg('sig_tip'),
1731 'key' => 'Y'
1732 ),
1733 array( 'image' => 'button_hr.png',
1734 'id' => 'mw-editbutton-hr',
1735 'open' => "\\n----\\n",
1736 'close' => '',
1737 'sample'=> '',
1738 'tip' => wfMsg('hr_tip'),
1739 'key' => 'R'
1740 )
1741 );
1742 $toolbar = "<div id='toolbar'>\n";
1743 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1744
1745 foreach($toolarray as $tool) {
1746
1747 $cssId = $tool['id'];
1748 $image=$wgStylePath.'/common/images/'.$tool['image'];
1749 $open=$tool['open'];
1750 $close=$tool['close'];
1751 $sample = wfEscapeJsString( $tool['sample'] );
1752
1753 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1754 // Older browsers show a "speedtip" type message only for ALT.
1755 // Ideally these should be different, realistically they
1756 // probably don't need to be.
1757 $tip = wfEscapeJsString( $tool['tip'] );
1758
1759 #$key = $tool["key"];
1760
1761 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1762 }
1763
1764 $toolbar.="/*]]>*/\n</script>";
1765 $toolbar.="\n</div>";
1766 return $toolbar;
1767 }
1768
1769 /**
1770 * Returns an array of html code of the following checkboxes:
1771 * minor and watch
1772 *
1773 * @param $tabindex Current tabindex
1774 * @param $skin Skin object
1775 * @param $checked Array of checkbox => bool, where bool indicates the checked
1776 * status of the checkbox
1777 *
1778 * @return array
1779 */
1780 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1781 global $wgUser;
1782
1783 $checkboxes = array();
1784
1785 $checkboxes['minor'] = '';
1786 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1787 if ( $wgUser->isAllowed('minoredit') ) {
1788 $attribs = array(
1789 'tabindex' => ++$tabindex,
1790 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1791 'id' => 'wpMinoredit',
1792 );
1793 $checkboxes['minor'] =
1794 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1795 "&nbsp;<label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1796 }
1797
1798 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1799 $checkboxes['watch'] = '';
1800 if ( $wgUser->isLoggedIn() ) {
1801 $attribs = array(
1802 'tabindex' => ++$tabindex,
1803 'accesskey' => wfMsg( 'accesskey-watch' ),
1804 'id' => 'wpWatchthis',
1805 );
1806 $checkboxes['watch'] =
1807 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1808 "&nbsp;<label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1809 }
1810 return $checkboxes;
1811 }
1812
1813 /**
1814 * Returns an array of html code of the following buttons:
1815 * save, diff, preview and live
1816 *
1817 * @param $tabindex Current tabindex
1818 *
1819 * @return array
1820 */
1821 public function getEditButtons(&$tabindex) {
1822 global $wgLivePreview, $wgUser;
1823
1824 $buttons = array();
1825
1826 $temp = array(
1827 'id' => 'wpSave',
1828 'name' => 'wpSave',
1829 'type' => 'submit',
1830 'tabindex' => ++$tabindex,
1831 'value' => wfMsg('savearticle'),
1832 'accesskey' => wfMsg('accesskey-save'),
1833 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1834 );
1835 $buttons['save'] = wfElement('input', $temp, '');
1836
1837 ++$tabindex; // use the same for preview and live preview
1838 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1839 $temp = array(
1840 'id' => 'wpPreview',
1841 'name' => 'wpPreview',
1842 'type' => 'submit',
1843 'tabindex' => $tabindex,
1844 'value' => wfMsg('showpreview'),
1845 'accesskey' => '',
1846 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1847 'style' => 'display: none;',
1848 );
1849 $buttons['preview'] = wfElement('input', $temp, '');
1850
1851 $temp = array(
1852 'id' => 'wpLivePreview',
1853 'name' => 'wpLivePreview',
1854 'type' => 'submit',
1855 'tabindex' => $tabindex,
1856 'value' => wfMsg('showlivepreview'),
1857 'accesskey' => wfMsg('accesskey-preview'),
1858 'title' => '',
1859 'onclick' => $this->doLivePreviewScript(),
1860 );
1861 $buttons['live'] = wfElement('input', $temp, '');
1862 } else {
1863 $temp = array(
1864 'id' => 'wpPreview',
1865 'name' => 'wpPreview',
1866 'type' => 'submit',
1867 'tabindex' => $tabindex,
1868 'value' => wfMsg('showpreview'),
1869 'accesskey' => wfMsg('accesskey-preview'),
1870 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1871 );
1872 $buttons['preview'] = wfElement('input', $temp, '');
1873 $buttons['live'] = '';
1874 }
1875
1876 $temp = array(
1877 'id' => 'wpDiff',
1878 'name' => 'wpDiff',
1879 'type' => 'submit',
1880 'tabindex' => ++$tabindex,
1881 'value' => wfMsg('showdiff'),
1882 'accesskey' => wfMsg('accesskey-diff'),
1883 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1884 );
1885 $buttons['diff'] = wfElement('input', $temp, '');
1886
1887 return $buttons;
1888 }
1889
1890 /**
1891 * Output preview text only. This can be sucked into the edit page
1892 * via JavaScript, and saves the server time rendering the skin as
1893 * well as theoretically being more robust on the client (doesn't
1894 * disturb the edit box's undo history, won't eat your text on
1895 * failure, etc).
1896 *
1897 * @todo This doesn't include category or interlanguage links.
1898 * Would need to enhance it a bit, <s>maybe wrap them in XML
1899 * or something...</s> that might also require more skin
1900 * initialization, so check whether that's a problem.
1901 */
1902 function livePreview() {
1903 global $wgOut;
1904 $wgOut->disable();
1905 header( 'Content-type: text/xml; charset=utf-8' );
1906 header( 'Cache-control: no-cache' );
1907
1908 $previewText = $this->getPreviewText();
1909 #$categories = $skin->getCategoryLinks();
1910
1911 $s =
1912 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1913 Xml::tags( 'livepreview', null,
1914 Xml::element( 'preview', null, $previewText )
1915 #. Xml::element( 'category', null, $categories )
1916 );
1917 echo $s;
1918 }
1919
1920
1921 /**
1922 * Get a diff between the current contents of the edit box and the
1923 * version of the page we're editing from.
1924 *
1925 * If this is a section edit, we'll replace the section as for final
1926 * save and then make a comparison.
1927 */
1928 function showDiff() {
1929 $oldtext = $this->mArticle->fetchContent();
1930 $newtext = $this->mArticle->replaceSection(
1931 $this->section, $this->textbox1, $this->summary, $this->edittime );
1932 $newtext = $this->mArticle->preSaveTransform( $newtext );
1933 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1934 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1935 if ( $oldtext !== false || $newtext != '' ) {
1936 $de = new DifferenceEngine( $this->mTitle );
1937 $de->setText( $oldtext, $newtext );
1938 $difftext = $de->getDiff( $oldtitle, $newtitle );
1939 $de->showDiffStyle();
1940 } else {
1941 $difftext = '';
1942 }
1943
1944 global $wgOut;
1945 $wgOut->addHtml( '<div id="wikiDiff">' . $difftext . '</div>' );
1946 }
1947
1948 /**
1949 * Filter an input field through a Unicode de-armoring process if it
1950 * came from an old browser with known broken Unicode editing issues.
1951 *
1952 * @param WebRequest $request
1953 * @param string $field
1954 * @return string
1955 * @private
1956 */
1957 function safeUnicodeInput( $request, $field ) {
1958 $text = rtrim( $request->getText( $field ) );
1959 return $request->getBool( 'safemode' )
1960 ? $this->unmakesafe( $text )
1961 : $text;
1962 }
1963
1964 /**
1965 * Filter an output field through a Unicode armoring process if it is
1966 * going to an old browser with known broken Unicode editing issues.
1967 *
1968 * @param string $text
1969 * @return string
1970 * @private
1971 */
1972 function safeUnicodeOutput( $text ) {
1973 global $wgContLang;
1974 $codedText = $wgContLang->recodeForEdit( $text );
1975 return $this->checkUnicodeCompliantBrowser()
1976 ? $codedText
1977 : $this->makesafe( $codedText );
1978 }
1979
1980 /**
1981 * A number of web browsers are known to corrupt non-ASCII characters
1982 * in a UTF-8 text editing environment. To protect against this,
1983 * detected browsers will be served an armored version of the text,
1984 * with non-ASCII chars converted to numeric HTML character references.
1985 *
1986 * Preexisting such character references will have a 0 added to them
1987 * to ensure that round-trips do not alter the original data.
1988 *
1989 * @param string $invalue
1990 * @return string
1991 * @private
1992 */
1993 function makesafe( $invalue ) {
1994 // Armor existing references for reversability.
1995 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1996
1997 $bytesleft = 0;
1998 $result = "";
1999 $working = 0;
2000 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2001 $bytevalue = ord( $invalue{$i} );
2002 if( $bytevalue <= 0x7F ) { //0xxx xxxx
2003 $result .= chr( $bytevalue );
2004 $bytesleft = 0;
2005 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
2006 $working = $working << 6;
2007 $working += ($bytevalue & 0x3F);
2008 $bytesleft--;
2009 if( $bytesleft <= 0 ) {
2010 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2011 }
2012 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
2013 $working = $bytevalue & 0x1F;
2014 $bytesleft = 1;
2015 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
2016 $working = $bytevalue & 0x0F;
2017 $bytesleft = 2;
2018 } else { //1111 0xxx
2019 $working = $bytevalue & 0x07;
2020 $bytesleft = 3;
2021 }
2022 }
2023 return $result;
2024 }
2025
2026 /**
2027 * Reverse the previously applied transliteration of non-ASCII characters
2028 * back to UTF-8. Used to protect data from corruption by broken web browsers
2029 * as listed in $wgBrowserBlackList.
2030 *
2031 * @param string $invalue
2032 * @return string
2033 * @private
2034 */
2035 function unmakesafe( $invalue ) {
2036 $result = "";
2037 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2038 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
2039 $i += 3;
2040 $hexstring = "";
2041 do {
2042 $hexstring .= $invalue{$i};
2043 $i++;
2044 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2045
2046 // Do some sanity checks. These aren't needed for reversability,
2047 // but should help keep the breakage down if the editor
2048 // breaks one of the entities whilst editing.
2049 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2050 $codepoint = hexdec($hexstring);
2051 $result .= codepointToUtf8( $codepoint );
2052 } else {
2053 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2054 }
2055 } else {
2056 $result .= substr( $invalue, $i, 1 );
2057 }
2058 }
2059 // reverse the transform that we made for reversability reasons.
2060 return strtr( $result, array( "&#x0" => "&#x" ) );
2061 }
2062
2063 function noCreatePermission() {
2064 global $wgOut;
2065 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2066 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
2067 }
2068
2069 /**
2070 * If there are rows in the deletion log for this page, show them,
2071 * along with a nice little note for the user
2072 *
2073 * @param OutputPage $out
2074 */
2075 private function showDeletionLog( $out ) {
2076 $title = $this->mArticle->getTitle();
2077 $reader = new LogReader(
2078 new FauxRequest(
2079 array(
2080 'page' => $title->getPrefixedText(),
2081 'type' => 'delete',
2082 )
2083 )
2084 );
2085 if( $reader->hasRows() ) {
2086 $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
2087 $out->addWikiText( wfMsg( 'recreate-deleted-warn' ) );
2088 $viewer = new LogViewer( $reader );
2089 $viewer->showList( $out );
2090 $out->addHtml( '</div>' );
2091 }
2092 }
2093
2094 }
2095
2096