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