Use spiffier variable swap method. Might not be as pretty as those iterators Tim...
[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 global $wgEmailConfirmToEdit;
302
303 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
304 return;
305
306 $fname = 'EditPage::edit';
307 wfProfileIn( $fname );
308 wfDebug( "$fname: enter\n" );
309
310 // this is not an article
311 $wgOut->setArticleFlag(false);
312
313 $this->importFormData( $wgRequest );
314 $this->firsttime = false;
315
316 if( $this->live ) {
317 $this->livePreview();
318 wfProfileOut( $fname );
319 return;
320 }
321
322 if ( ! $this->mTitle->userCan( 'edit' ) ) {
323 wfDebug( "$fname: user can't edit\n" );
324 $wgOut->readOnlyPage( $this->getContent(), true );
325 wfProfileOut( $fname );
326 return;
327 }
328 wfDebug( "$fname: Checking blocks\n" );
329 if ( !$this->preview && !$this->diff && $wgUser->isBlockedFrom( $this->mTitle, !$this->save ) ) {
330 # When previewing, don't check blocked state - will get caught at save time.
331 # Also, check when starting edition is done against slave to improve performance.
332 wfDebug( "$fname: user is blocked\n" );
333 $this->blockedPage();
334 wfProfileOut( $fname );
335 return;
336 }
337 if ( !$wgUser->isAllowed('edit') ) {
338 if ( $wgUser->isAnon() ) {
339 wfDebug( "$fname: user must log in\n" );
340 $this->userNotLoggedInPage();
341 wfProfileOut( $fname );
342 return;
343 } else {
344 wfDebug( "$fname: read-only page\n" );
345 $wgOut->readOnlyPage( $this->getContent(), true );
346 wfProfileOut( $fname );
347 return;
348 }
349 }
350 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
351 wfDebug("$fname: user must confirm e-mail address\n");
352 $this->userNotConfirmedPage();
353 wfProfileOut($fname);
354 return;
355 }
356 if ( !$this->mTitle->userCan( 'create' ) && !$this->mTitle->exists() ) {
357 wfDebug( "$fname: no create permission\n" );
358 $this->noCreatePermission();
359 wfProfileOut( $fname );
360 return;
361 }
362 if ( wfReadOnly() ) {
363 wfDebug( "$fname: read-only mode is engaged\n" );
364 if( $this->save || $this->preview ) {
365 $this->formtype = 'preview';
366 } else if ( $this->diff ) {
367 $this->formtype = 'diff';
368 } else {
369 $wgOut->readOnlyPage( $this->getContent() );
370 wfProfileOut( $fname );
371 return;
372 }
373 } else {
374 if ( $this->save ) {
375 $this->formtype = 'save';
376 } else if ( $this->preview ) {
377 $this->formtype = 'preview';
378 } else if ( $this->diff ) {
379 $this->formtype = 'diff';
380 } else { # First time through
381 $this->firsttime = true;
382 if( $this->previewOnOpen() ) {
383 $this->formtype = 'preview';
384 } else {
385 $this->extractMetaDataFromArticle () ;
386 $this->formtype = 'initial';
387 }
388 }
389 }
390
391 wfProfileIn( "$fname-business-end" );
392
393 $this->isConflict = false;
394 // css / js subpages of user pages get a special treatment
395 $this->isCssJsSubpage = $wgTitle->isCssJsSubpage();
396 $this->isValidCssJsSubpage = $wgTitle->isValidCssJsSubpage();
397
398 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
399 * no matter it's current state
400 */
401 $this->deletedSinceEdit = false;
402 if ( $this->edittime != '' ) {
403 /* Note that we rely on logging table, which hasn't been always there,
404 * but that doesn't matter, because this only applies to brand new
405 * deletes. This is done on every preview and save request. Move it further down
406 * to only perform it on saves
407 */
408 if ( $this->mTitle->isDeleted() ) {
409 $this->lastDelete = $this->getLastDelete();
410 if ( !is_null($this->lastDelete) ) {
411 $deletetime = $this->lastDelete->log_timestamp;
412 if ( ($deletetime - $this->starttime) > 0 ) {
413 $this->deletedSinceEdit = true;
414 }
415 }
416 }
417 }
418
419 # Show applicable editing introductions
420 if( $this->formtype == 'initial' || $this->firsttime )
421 $this->showIntro();
422
423 if( $this->mTitle->isTalkPage() ) {
424 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
425 }
426
427 # Attempt submission here. This will check for edit conflicts,
428 # and redundantly check for locked database, blocked IPs, etc.
429 # that edit() already checked just in case someone tries to sneak
430 # in the back door with a hand-edited submission URL.
431
432 if ( 'save' == $this->formtype ) {
433 if ( !$this->attemptSave() ) {
434 wfProfileOut( "$fname-business-end" );
435 wfProfileOut( $fname );
436 return;
437 }
438 }
439
440 # First time through: get contents, set time for conflict
441 # checking, etc.
442 if ( 'initial' == $this->formtype || $this->firsttime ) {
443 if ($this->initialiseForm() === false) {
444 $this->noSuchSectionPage();
445 wfProfileOut( "$fname-business-end" );
446 wfProfileOut( $fname );
447 return;
448 }
449 if( !$this->mTitle->getArticleId() )
450 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
451 }
452
453 $this->showEditForm();
454 wfProfileOut( "$fname-business-end" );
455 wfProfileOut( $fname );
456 }
457
458 /**
459 * Return true if this page should be previewed when the edit form
460 * is initially opened.
461 * @return bool
462 * @private
463 */
464 function previewOnOpen() {
465 global $wgUser;
466 return $this->section != 'new' &&
467 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle->exists() ) ||
468 ( $this->mTitle->getNamespace() == NS_CATEGORY &&
469 !$this->mTitle->exists() ) );
470 }
471
472 /**
473 * @todo document
474 * @param $request
475 */
476 function importFormData( &$request ) {
477 global $wgLang, $wgUser;
478 $fname = 'EditPage::importFormData';
479 wfProfileIn( $fname );
480
481 if( $request->wasPosted() ) {
482 # These fields need to be checked for encoding.
483 # Also remove trailing whitespace, but don't remove _initial_
484 # whitespace from the text boxes. This may be significant formatting.
485 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
486 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
487 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
488 # Truncate for whole multibyte characters. +5 bytes for ellipsis
489 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
490
491 $this->edittime = $request->getVal( 'wpEdittime' );
492 $this->starttime = $request->getVal( 'wpStarttime' );
493
494 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
495
496 if( is_null( $this->edittime ) ) {
497 # If the form is incomplete, force to preview.
498 wfDebug( "$fname: Form data appears to be incomplete\n" );
499 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
500 $this->preview = true;
501 } else {
502 /* Fallback for live preview */
503 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
504 $this->diff = $request->getCheck( 'wpDiff' );
505
506 // Remember whether a save was requested, so we can indicate
507 // if we forced preview due to session failure.
508 $this->mTriedSave = !$this->preview;
509
510 if ( $this->tokenOk( $request ) ) {
511 # Some browsers will not report any submit button
512 # if the user hits enter in the comment box.
513 # The unmarked state will be assumed to be a save,
514 # if the form seems otherwise complete.
515 wfDebug( "$fname: Passed token check.\n" );
516 } else if ( $this->diff ) {
517 # Failed token check, but only requested "Show Changes".
518 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
519 } else {
520 # Page might be a hack attempt posted from
521 # an external site. Preview instead of saving.
522 wfDebug( "$fname: Failed token check; forcing preview\n" );
523 $this->preview = true;
524 }
525 }
526 $this->save = ! ( $this->preview OR $this->diff );
527 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
528 $this->edittime = null;
529 }
530
531 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
532 $this->starttime = null;
533 }
534
535 $this->recreate = $request->getCheck( 'wpRecreate' );
536
537 $this->minoredit = $request->getCheck( 'wpMinoredit' );
538 $this->watchthis = $request->getCheck( 'wpWatchthis' );
539
540 # Don't force edit summaries when a user is editing their own user or talk page
541 if( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) && $this->mTitle->getText() == $wgUser->getName() ) {
542 $this->allowBlankSummary = true;
543 } else {
544 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' );
545 }
546
547 $this->autoSumm = $request->getText( 'wpAutoSummary' );
548 } else {
549 # Not a posted form? Start with nothing.
550 wfDebug( "$fname: Not a posted form.\n" );
551 $this->textbox1 = '';
552 $this->textbox2 = '';
553 $this->mMetaData = '';
554 $this->summary = '';
555 $this->edittime = '';
556 $this->starttime = wfTimestampNow();
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->showCustomIntro() && !$this->mTitle->exists() ) {
597 if( $wgUser->isLoggedIn() ) {
598 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
599 } else {
600 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
601 }
602 $this->showDeletionLog( $wgOut );
603 }
604 }
605
606 /**
607 * Attempt to show a custom editing introduction, if supplied
608 *
609 * @return bool
610 */
611 private function showCustomIntro() {
612 if( $this->editintro ) {
613 $title = Title::newFromText( $this->editintro );
614 if( $title instanceof Title && $title->exists() && $title->userCanRead() ) {
615 global $wgOut;
616 $revision = Revision::newFromTitle( $title );
617 $wgOut->addSecondaryWikiText( $revision->getText() );
618 return true;
619 } else {
620 return false;
621 }
622 } else {
623 return false;
624 }
625 }
626
627 /**
628 * Attempt submission
629 * @return bool false if output is done, true if the rest of the form should be displayed
630 */
631 function attemptSave() {
632 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
633 global $wgMaxArticleSize;
634
635 $fname = 'EditPage::attemptSave';
636 wfProfileIn( $fname );
637 wfProfileIn( "$fname-checks" );
638
639 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
640 {
641 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
642 return false;
643 }
644
645 # Reintegrate metadata
646 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
647 $this->mMetaData = '' ;
648
649 # Check for spam
650 $matches = array();
651 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
652 $this->spamPage ( $matches[0] );
653 wfProfileOut( "$fname-checks" );
654 wfProfileOut( $fname );
655 return false;
656 }
657 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
658 # Error messages or other handling should be performed by the filter function
659 wfProfileOut( $fname );
660 wfProfileOut( "$fname-checks" );
661 return false;
662 }
663 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError ) ) ) {
664 # Error messages etc. could be handled within the hook...
665 wfProfileOut( $fname );
666 wfProfileOut( "$fname-checks" );
667 return false;
668 } elseif( $this->hookError != '' ) {
669 # ...or the hook could be expecting us to produce an error
670 wfProfileOut( "$fname-checks " );
671 wfProfileOut( $fname );
672 return true;
673 }
674 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
675 # Check block state against master, thus 'false'.
676 $this->blockedPage();
677 wfProfileOut( "$fname-checks" );
678 wfProfileOut( $fname );
679 return false;
680 }
681 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
682 if ( $this->kblength > $wgMaxArticleSize ) {
683 // Error will be displayed by showEditForm()
684 $this->tooBig = true;
685 wfProfileOut( "$fname-checks" );
686 wfProfileOut( $fname );
687 return true;
688 }
689
690 if ( !$wgUser->isAllowed('edit') ) {
691 if ( $wgUser->isAnon() ) {
692 $this->userNotLoggedInPage();
693 wfProfileOut( "$fname-checks" );
694 wfProfileOut( $fname );
695 return false;
696 }
697 else {
698 $wgOut->readOnlyPage();
699 wfProfileOut( "$fname-checks" );
700 wfProfileOut( $fname );
701 return false;
702 }
703 }
704
705 if ( wfReadOnly() ) {
706 $wgOut->readOnlyPage();
707 wfProfileOut( "$fname-checks" );
708 wfProfileOut( $fname );
709 return false;
710 }
711 if ( $wgUser->pingLimiter() ) {
712 $wgOut->rateLimited();
713 wfProfileOut( "$fname-checks" );
714 wfProfileOut( $fname );
715 return false;
716 }
717
718 # If the article has been deleted while editing, don't save it without
719 # confirmation
720 if ( $this->deletedSinceEdit && !$this->recreate ) {
721 wfProfileOut( "$fname-checks" );
722 wfProfileOut( $fname );
723 return true;
724 }
725
726 wfProfileOut( "$fname-checks" );
727
728 # If article is new, insert it.
729 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
730 if ( 0 == $aid ) {
731
732 // Late check for create permission, just in case *PARANOIA*
733 if ( !$this->mTitle->userCan( 'create' ) ) {
734 wfDebug( "$fname: no create permission\n" );
735 $this->noCreatePermission();
736 wfProfileOut( $fname );
737 return;
738 }
739
740 # Don't save a new article if it's blank.
741 if ( ( '' == $this->textbox1 ) ) {
742 $wgOut->redirect( $this->mTitle->getFullURL() );
743 wfProfileOut( $fname );
744 return false;
745 }
746
747 $isComment=($this->section=='new');
748 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
749 $this->minoredit, $this->watchthis, false, $isComment);
750
751 wfProfileOut( $fname );
752 return false;
753 }
754
755 # Article exists. Check for edit conflict.
756
757 $this->mArticle->clear(); # Force reload of dates, etc.
758 $this->mArticle->forUpdate( true ); # Lock the article
759
760 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
761
762 if( $this->mArticle->getTimestamp() != $this->edittime ) {
763 $this->isConflict = true;
764 if( $this->section == 'new' ) {
765 if( $this->mArticle->getUserText() == $wgUser->getName() &&
766 $this->mArticle->getComment() == $this->summary ) {
767 // Probably a duplicate submission of a new comment.
768 // This can happen when squid resends a request after
769 // a timeout but the first one actually went through.
770 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
771 } else {
772 // New comment; suppress conflict.
773 $this->isConflict = false;
774 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
775 }
776 }
777 }
778 $userid = $wgUser->getID();
779
780 if ( $this->isConflict) {
781 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
782 $this->mArticle->getTimestamp() . "'\n" );
783 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
784 }
785 else {
786 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
787 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
788 }
789 if( is_null( $text ) ) {
790 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
791 $this->isConflict = true;
792 $text = $this->textbox1;
793 }
794
795 # Suppress edit conflict with self, except for section edits where merging is required.
796 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
797 wfDebug( "Suppressing edit conflict, same user.\n" );
798 $this->isConflict = false;
799 } else {
800 # switch from section editing to normal editing in edit conflict
801 if($this->isConflict) {
802 # Attempt merge
803 if( $this->mergeChangesInto( $text ) ){
804 // Successful merge! Maybe we should tell the user the good news?
805 $this->isConflict = false;
806 wfDebug( "Suppressing edit conflict, successful merge.\n" );
807 } else {
808 $this->section = '';
809 $this->textbox1 = $text;
810 wfDebug( "Keeping edit conflict, failed merge.\n" );
811 }
812 }
813 }
814
815 if ( $this->isConflict ) {
816 wfProfileOut( $fname );
817 return true;
818 }
819
820 $oldtext = $this->mArticle->getContent();
821
822 # Handle the user preference to force summaries here, but not for null edits
823 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary')
824 && 0 != strcmp($oldtext, $text) && !Article::getRedirectAutosummary( $text )) {
825 if( md5( $this->summary ) == $this->autoSumm ) {
826 $this->missingSummary = true;
827 wfProfileOut( $fname );
828 return( true );
829 }
830 }
831
832 #And a similar thing for new sections
833 if( $this->section == 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
834 if (trim($this->summary) == '') {
835 $this->missingSummary = true;
836 wfProfileOut( $fname );
837 return( true );
838 }
839 }
840
841 # All's well
842 wfProfileIn( "$fname-sectionanchor" );
843 $sectionanchor = '';
844 if( $this->section == 'new' ) {
845 if ( $this->textbox1 == '' ) {
846 $this->missingComment = true;
847 return true;
848 }
849 if( $this->summary != '' ) {
850 $sectionanchor = $this->sectionAnchor( $this->summary );
851 }
852 } elseif( $this->section != '' ) {
853 # Try to get a section anchor from the section source, redirect to edited section if header found
854 # XXX: might be better to integrate this into Article::replaceSection
855 # for duplicate heading checking and maybe parsing
856 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
857 # we can't deal with anchors, includes, html etc in the header for now,
858 # headline would need to be parsed to improve this
859 if($hasmatch and strlen($matches[2]) > 0) {
860 $sectionanchor = $this->sectionAnchor( $matches[2] );
861 }
862 }
863 wfProfileOut( "$fname-sectionanchor" );
864
865 // Save errors may fall down to the edit form, but we've now
866 // merged the section into full text. Clear the section field
867 // so that later submission of conflict forms won't try to
868 // replace that into a duplicated mess.
869 $this->textbox1 = $text;
870 $this->section = '';
871
872 // Check for length errors again now that the section is merged in
873 $this->kblength = (int)(strlen( $text ) / 1024);
874 if ( $this->kblength > $wgMaxArticleSize ) {
875 $this->tooBig = true;
876 wfProfileOut( $fname );
877 return true;
878 }
879
880 # update the article here
881 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
882 $this->watchthis, '', $sectionanchor ) ) {
883 wfProfileOut( $fname );
884 return false;
885 } else {
886 $this->isConflict = true;
887 }
888 wfProfileOut( $fname );
889 return true;
890 }
891
892 /**
893 * Initialise form fields in the object
894 * Called on the first invocation, e.g. when a user clicks an edit link
895 */
896 function initialiseForm() {
897 $this->edittime = $this->mArticle->getTimestamp();
898 $this->summary = '';
899 $this->textbox1 = $this->getContent(false);
900 if ($this->textbox1 === false) return false;
901
902 if ( !$this->mArticle->exists() && $this->mArticle->mTitle->getNamespace() == NS_MEDIAWIKI )
903 $this->textbox1 = wfMsgWeirdKey( $this->mArticle->mTitle->getText() );
904 wfProxyCheck();
905 return true;
906 }
907
908 /**
909 * Send the edit form and related headers to $wgOut
910 * @param $formCallback Optional callable that takes an OutputPage
911 * parameter; will be called during form output
912 * near the top, for captchas and the like.
913 */
914 function showEditForm( $formCallback=null ) {
915 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
916
917 $fname = 'EditPage::showEditForm';
918 wfProfileIn( $fname );
919
920 $sk = $wgUser->getSkin();
921
922 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
923
924 $wgOut->setRobotpolicy( 'noindex,nofollow' );
925
926 # Enabled article-related sidebar, toplinks, etc.
927 $wgOut->setArticleRelated( true );
928
929 if ( $this->isConflict ) {
930 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
931 $wgOut->setPageTitle( $s );
932 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
933
934 $this->textbox2 = $this->textbox1;
935 $this->textbox1 = $this->getContent();
936 $this->edittime = $this->mArticle->getTimestamp();
937 } else {
938
939 if( $this->section != '' ) {
940 if( $this->section == 'new' ) {
941 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
942 } else {
943 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
944 $matches = array();
945 if( !$this->summary && !$this->preview && !$this->diff ) {
946 preg_match( "/^(=+)(.+)\\1/mi",
947 $this->textbox1,
948 $matches );
949 if( !empty( $matches[2] ) ) {
950 $this->summary = "/* ". trim($matches[2])." */ ";
951 }
952 }
953 }
954 } else {
955 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
956 }
957 $wgOut->setPageTitle( $s );
958
959 if ( $this->missingComment ) {
960 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
961 }
962
963 if( $this->missingSummary && $this->section != 'new' ) {
964 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
965 }
966
967 if( $this->missingSummary && $this->section == 'new' ) {
968 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
969 }
970
971 if( !$this->hookError == '' ) {
972 $wgOut->addWikiText( $this->hookError );
973 }
974
975 if ( !$this->checkUnicodeCompliantBrowser() ) {
976 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
977 }
978 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
979 // Let sysop know that this will make private content public if saved
980 if( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
981 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
982 }
983 if( !$this->mArticle->mRevision->isCurrent() ) {
984 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
985 $wgOut->addWikiText( wfMsg( 'editingold' ) );
986 }
987 }
988 }
989
990 if( wfReadOnly() ) {
991 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
992 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
993 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
994 } else {
995 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
996 # Check the skin exists
997 if( $this->isValidCssJsSubpage ) {
998 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
999 } else {
1000 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
1001 }
1002 }
1003 }
1004
1005 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1006 # Show a warning if editing an interface message
1007 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
1008 } elseif( $this->mTitle->isProtected( 'edit' ) ) {
1009 # Is the title semi-protected?
1010 if( $this->mTitle->isSemiProtected() ) {
1011 $notice = wfMsg( 'semiprotectedpagewarning' );
1012 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' )
1013 $notice = '';
1014 } else {
1015 # Then it must be protected based on static groups (regular)
1016 $notice = wfMsg( 'protectedpagewarning' );
1017 }
1018 $wgOut->addWikiText( $notice );
1019 }
1020 if ( $this->mTitle->isCascadeProtected() ) {
1021 # Is this page under cascading protection from some source pages?
1022 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1023 if ( count($cascadeSources) > 0 ) {
1024 # Explain, and list the titles responsible
1025 $notice = wfMsgExt( 'cascadeprotectedwarning', array('parsemag'), count($cascadeSources) ) . "\n";
1026 foreach( $cascadeSources as $id => $page )
1027 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1028 }
1029 $wgOut->addWikiText( $notice );
1030 }
1031
1032 if ( $this->kblength === false ) {
1033 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
1034 }
1035 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1036 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
1037 } elseif( $this->kblength > 29 ) {
1038 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
1039 }
1040
1041 #need to parse the preview early so that we know which templates are used,
1042 #otherwise users with "show preview after edit box" will get a blank list
1043 if ( $this->formtype == 'preview' ) {
1044 $previewOutput = $this->getPreviewText();
1045 }
1046
1047 $rows = $wgUser->getIntOption( 'rows' );
1048 $cols = $wgUser->getIntOption( 'cols' );
1049
1050 $ew = $wgUser->getOption( 'editwidth' );
1051 if ( $ew ) $ew = " style=\"width:100%\"";
1052 else $ew = '';
1053
1054 $q = 'action=submit';
1055 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1056 $action = $this->mTitle->escapeLocalURL( $q );
1057
1058 $summary = wfMsg('summary');
1059 $subject = wfMsg('subject');
1060
1061 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
1062 wfMsgExt('cancel', array('parseinline')) );
1063 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1064 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1065 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1066 htmlspecialchars( wfMsg( 'newwindow' ) );
1067
1068 global $wgRightsText;
1069 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1070 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
1071 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1072 $wgRightsText ) . "\n</div>";
1073
1074 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
1075 # prepare toolbar for edit buttons
1076 $toolbar = $this->getEditToolbar();
1077 } else {
1078 $toolbar = '';
1079 }
1080
1081 // activate checkboxes if user wants them to be always active
1082 if( !$this->preview && !$this->diff ) {
1083 # Sort out the "watch" checkbox
1084 if( $wgUser->getOption( 'watchdefault' ) ) {
1085 # Watch all edits
1086 $this->watchthis = true;
1087 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1088 # Watch creations
1089 $this->watchthis = true;
1090 } elseif( $this->mTitle->userIsWatching() ) {
1091 # Already watched
1092 $this->watchthis = true;
1093 }
1094
1095 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1096 }
1097
1098 $wgOut->addHTML( $this->editFormPageTop );
1099
1100 if ( $wgUser->getOption( 'previewontop' ) ) {
1101
1102 if ( 'preview' == $this->formtype ) {
1103 $this->showPreview( $previewOutput );
1104 } else {
1105 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1106 }
1107
1108 if ( 'diff' == $this->formtype ) {
1109 $this->showDiff();
1110 }
1111 }
1112
1113
1114 $wgOut->addHTML( $this->editFormTextTop );
1115
1116 # if this is a comment, show a subject line at the top, which is also the edit summary.
1117 # Otherwise, show a summary field at the bottom
1118 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
1119 if( $this->section == 'new' ) {
1120 $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 />";
1121 $editsummary = '';
1122 $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1123 $summarypreview = '';
1124 } else {
1125 $commentsubject = '';
1126 $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 />";
1127 $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1128 $subjectpreview = '';
1129 }
1130
1131 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1132 if( !$this->preview && !$this->diff ) {
1133 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1134 }
1135 $templates = ($this->preview || $this->section != '') ? $this->mPreviewTemplates : $this->mArticle->getUsedTemplates();
1136 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1137
1138 global $wgUseMetadataEdit ;
1139 if ( $wgUseMetadataEdit ) {
1140 $metadata = $this->mMetaData ;
1141 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1142 $top = wfMsgWikiHtml( 'metadata_help' );
1143 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1144 }
1145 else $metadata = "" ;
1146
1147 $hidden = '';
1148 $recreate = '';
1149 if ($this->deletedSinceEdit) {
1150 if ( 'save' != $this->formtype ) {
1151 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1152 } else {
1153 // Hide the toolbar and edit area, use can click preview to get it back
1154 // Add an confirmation checkbox and explanation.
1155 $toolbar = '';
1156 $hidden = 'type="hidden" style="display:none;"';
1157 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
1158 $recreate .=
1159 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1160 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1161 }
1162 }
1163
1164 $tabindex = 2;
1165
1166 $checkboxes = self::getCheckboxes( $tabindex, $sk,
1167 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1168
1169 $checkboxhtml = implode( $checkboxes, "\n" );
1170
1171 $buttons = $this->getEditButtons( $tabindex );
1172 $buttonshtml = implode( $buttons, "\n" );
1173
1174 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1175 ? '' : Xml::hidden( 'safemode', '1' );
1176
1177 $wgOut->addHTML( <<<END
1178 {$toolbar}
1179 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1180 END
1181 );
1182
1183 if( is_callable( $formCallback ) ) {
1184 call_user_func_array( $formCallback, array( &$wgOut ) );
1185 }
1186
1187 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1188
1189 // Put these up at the top to ensure they aren't lost on early form submission
1190 $wgOut->addHTML( "
1191 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1192 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1193 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1194 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1195
1196 $wgOut->addHTML( <<<END
1197 $recreate
1198 {$commentsubject}
1199 {$subjectpreview}
1200 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1201 cols='{$cols}'{$ew} $hidden>
1202 END
1203 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1204 "
1205 </textarea>
1206 " );
1207
1208 $wgOut->addWikiText( $copywarn );
1209 $wgOut->addHTML( $this->editFormTextAfterWarn );
1210 $wgOut->addHTML( "
1211 {$metadata}
1212 {$editsummary}
1213 {$summarypreview}
1214 {$checkboxhtml}
1215 {$safemodehtml}
1216 ");
1217
1218 $wgOut->addHTML(
1219 "<div class='editButtons'>
1220 {$buttonshtml}
1221 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1222 </div><!-- editButtons -->
1223 </div><!-- editOptions -->");
1224
1225 $wgOut->addHtml( '<div class="mw-editTools">' );
1226 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1227 $wgOut->addHtml( '</div>' );
1228
1229 $wgOut->addHTML( $this->editFormTextAfterTools );
1230
1231 $wgOut->addHTML( "
1232 <div class='templatesUsed'>
1233 {$formattedtemplates}
1234 </div>
1235 " );
1236
1237 /**
1238 * To make it harder for someone to slip a user a page
1239 * which submits an edit form to the wiki without their
1240 * knowledge, a random token is associated with the login
1241 * session. If it's not passed back with the submission,
1242 * we won't save the page, or render user JavaScript and
1243 * CSS previews.
1244 *
1245 * For anon editors, who may not have a session, we just
1246 * include the constant suffix to prevent editing from
1247 * broken text-mangling proxies.
1248 */
1249 $token = htmlspecialchars( $wgUser->editToken() );
1250 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1251
1252
1253 # If a blank edit summary was previously provided, and the appropriate
1254 # user preference is active, pass a hidden tag here. This will stop the
1255 # user being bounced back more than once in the event that a summary
1256 # is not required.
1257 if( $this->missingSummary ) {
1258 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1259 }
1260
1261 # For a bit more sophisticated detection of blank summaries, hash the
1262 # automatic one and pass that in a hidden field.
1263 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1264 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1265
1266 if ( $this->isConflict ) {
1267 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1268
1269 $de = new DifferenceEngine( $this->mTitle );
1270 $de->setText( $this->textbox2, $this->textbox1 );
1271 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1272
1273 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1274 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1275 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1276 }
1277 $wgOut->addHTML( $this->editFormTextBottom );
1278 $wgOut->addHTML( "</form>\n" );
1279 if ( !$wgUser->getOption( 'previewontop' ) ) {
1280
1281 if ( $this->formtype == 'preview') {
1282 $this->showPreview( $previewOutput );
1283 } else {
1284 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1285 }
1286
1287 if ( $this->formtype == 'diff') {
1288 $this->showDiff();
1289 }
1290
1291 }
1292
1293 wfProfileOut( $fname );
1294 }
1295
1296 /**
1297 * Append preview output to $wgOut.
1298 * Includes category rendering if this is a category page.
1299 *
1300 * @param string $text The HTML to be output for the preview.
1301 */
1302 private function showPreview( $text ) {
1303 global $wgOut;
1304
1305 $wgOut->addHTML( '<div id="wikiPreview">' );
1306 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1307 $this->mArticle->openShowCategory();
1308 }
1309 $wgOut->addHTML( $text );
1310 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1311 $this->mArticle->closeShowCategory();
1312 }
1313 $wgOut->addHTML( '</div>' );
1314 }
1315
1316 /**
1317 * Live Preview lets us fetch rendered preview page content and
1318 * add it to the page without refreshing the whole page.
1319 * If not supported by the browser it will fall through to the normal form
1320 * submission method.
1321 *
1322 * This function outputs a script tag to support live preview, and
1323 * returns an onclick handler which should be added to the attributes
1324 * of the preview button
1325 */
1326 function doLivePreviewScript() {
1327 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1328 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1329 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1330 '"></script>' . "\n" );
1331 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1332 return "return !livePreview(" .
1333 "getElementById('wikiPreview')," .
1334 "editform.wpTextbox1.value," .
1335 '"' . $liveAction . '"' . ")";
1336 }
1337
1338 function getLastDelete() {
1339 $dbr = wfGetDB( DB_SLAVE );
1340 $fname = 'EditPage::getLastDelete';
1341 $res = $dbr->select(
1342 array( 'logging', 'user' ),
1343 array( 'log_type',
1344 'log_action',
1345 'log_timestamp',
1346 'log_user',
1347 'log_namespace',
1348 'log_title',
1349 'log_comment',
1350 'log_params',
1351 'user_name', ),
1352 array( 'log_namespace' => $this->mTitle->getNamespace(),
1353 'log_title' => $this->mTitle->getDBkey(),
1354 'log_type' => 'delete',
1355 'log_action' => 'delete',
1356 'user_id=log_user' ),
1357 $fname,
1358 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1359
1360 if($dbr->numRows($res) == 1) {
1361 while ( $x = $dbr->fetchObject ( $res ) )
1362 $data = $x;
1363 $dbr->freeResult ( $res ) ;
1364 } else {
1365 $data = null;
1366 }
1367 return $data;
1368 }
1369
1370 /**
1371 * @todo document
1372 */
1373 function getPreviewText() {
1374 global $wgOut, $wgUser, $wgTitle, $wgParser;
1375
1376 $fname = 'EditPage::getPreviewText';
1377 wfProfileIn( $fname );
1378
1379 if ( $this->mTriedSave && !$this->mTokenOk ) {
1380 if ( $this->mTokenOkExceptSuffix ) {
1381 $msg = 'token_suffix_mismatch';
1382 } else {
1383 $msg = 'session_fail_preview';
1384 }
1385 } else {
1386 $msg = 'previewnote';
1387 }
1388 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1389 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1390 if ( $this->isConflict ) {
1391 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1392 }
1393
1394 $parserOptions = ParserOptions::newFromUser( $wgUser );
1395 $parserOptions->setEditSection( false );
1396
1397 global $wgRawHtml;
1398 if( $wgRawHtml && !$this->mTokenOk ) {
1399 // Could be an offsite preview attempt. This is very unsafe if
1400 // HTML is enabled, as it could be an attack.
1401 return $wgOut->parse( "<div class='previewnote'>" .
1402 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1403 }
1404
1405 # don't parse user css/js, show message about preview
1406 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1407
1408 if ( $this->isCssJsSubpage ) {
1409 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1410 $previewtext = wfMsg('usercsspreview');
1411 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1412 $previewtext = wfMsg('userjspreview');
1413 }
1414 $parserOptions->setTidy(true);
1415 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1416 $wgOut->addHTML( $parserOutput->mText );
1417 wfProfileOut( $fname );
1418 return $previewhead;
1419 } else {
1420 $toparse = $this->textbox1;
1421
1422 # If we're adding a comment, we need to show the
1423 # summary as the headline
1424 if($this->section=="new" && $this->summary!="") {
1425 $toparse="== {$this->summary} ==\n\n".$toparse;
1426 }
1427
1428 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1429 $parserOptions->setTidy(true);
1430 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1431 $wgTitle, $parserOptions );
1432
1433 $previewHTML = $parserOutput->getText();
1434 $wgOut->addParserOutputNoText( $parserOutput );
1435
1436 # ParserOutput might have altered the page title, so reset it
1437 $wgOut->setPageTitle( wfMsg( 'editing', $this->mTitle->getPrefixedText() ) );
1438
1439 foreach ( $parserOutput->getTemplates() as $ns => $template)
1440 foreach ( array_keys( $template ) as $dbk)
1441 $this->mPreviewTemplates[] = Title::makeTitle($ns, $dbk);
1442
1443 wfProfileOut( $fname );
1444 return $previewhead . $previewHTML;
1445 }
1446 }
1447
1448 /**
1449 * Call the stock "user is blocked" page
1450 */
1451 function blockedPage() {
1452 global $wgOut, $wgUser;
1453 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1454
1455 # If the user made changes, preserve them when showing the markup
1456 # (This happens when a user is blocked during edit, for instance)
1457 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1458 if( $first ) {
1459 $source = $this->mTitle->exists() ? $this->getContent() : false;
1460 } else {
1461 $source = $this->textbox1;
1462 }
1463
1464 # Spit out the source or the user's modified version
1465 if( $source !== false ) {
1466 $rows = $wgUser->getOption( 'rows' );
1467 $cols = $wgUser->getOption( 'cols' );
1468 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1469 $wgOut->addHtml( '<hr />' );
1470 $wgOut->addWikiText( wfMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() ) );
1471 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1472 }
1473 }
1474
1475 /**
1476 * Produce the stock "please login to edit pages" page
1477 */
1478 function userNotLoggedInPage() {
1479 global $wgUser, $wgOut;
1480 $skin = $wgUser->getSkin();
1481
1482 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1483 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle->getPrefixedUrl() );
1484
1485 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1486 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1487 $wgOut->setArticleRelated( false );
1488
1489 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1490 $wgOut->returnToMain( false, $this->mTitle->getPrefixedUrl() );
1491 }
1492
1493 /**
1494 * Creates a basic error page which informs the user that
1495 * they have to validate their email address before being
1496 * allowed to edit.
1497 */
1498 function userNotConfirmedPage() {
1499 global $wgOut;
1500
1501 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1502 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1503 $wgOut->setArticleRelated( false );
1504
1505 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1506 $wgOut->returnToMain( false );
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->getPrefixedUrl() );
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 );
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->mTitle, $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->mTitle );
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 * Format an anchor fragment as it would appear for a given section name
1606 * @param string $text
1607 * @return string
1608 * @private
1609 */
1610 function sectionAnchor( $text ) {
1611 $headline = Sanitizer::decodeCharReferences( $text );
1612 # strip out HTML
1613 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1614 $headline = trim( $headline );
1615 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1616 $replacearray = array(
1617 '%3A' => ':',
1618 '%' => '.'
1619 );
1620 return str_replace(
1621 array_keys( $replacearray ),
1622 array_values( $replacearray ),
1623 $sectionanchor );
1624 }
1625
1626 /**
1627 * Shows a bulletin board style toolbar for common editing functions.
1628 * It can be disabled in the user preferences.
1629 * The necessary JavaScript code can be found in style/wikibits.js.
1630 */
1631 function getEditToolbar() {
1632 global $wgStylePath, $wgContLang, $wgJsMimeType;
1633
1634 /**
1635 * toolarray an array of arrays which each include the filename of
1636 * the button image (without path), the opening tag, the closing tag,
1637 * and optionally a sample text that is inserted between the two when no
1638 * selection is highlighted.
1639 * The tip text is shown when the user moves the mouse over the button.
1640 *
1641 * Already here are accesskeys (key), which are not used yet until someone
1642 * can figure out a way to make them work in IE. However, we should make
1643 * sure these keys are not defined on the edit page.
1644 */
1645 $toolarray = array(
1646 array( 'image' => 'button_bold.png',
1647 'id' => 'mw-editbutton-bold',
1648 'open' => '\\\'\\\'\\\'',
1649 'close' => '\\\'\\\'\\\'',
1650 'sample'=> wfMsg('bold_sample'),
1651 'tip' => wfMsg('bold_tip'),
1652 'key' => 'B'
1653 ),
1654 array( 'image' => 'button_italic.png',
1655 'id' => 'mw-editbutton-italic',
1656 'open' => '\\\'\\\'',
1657 'close' => '\\\'\\\'',
1658 'sample'=> wfMsg('italic_sample'),
1659 'tip' => wfMsg('italic_tip'),
1660 'key' => 'I'
1661 ),
1662 array( 'image' => 'button_link.png',
1663 'id' => 'mw-editbutton-link',
1664 'open' => '[[',
1665 'close' => ']]',
1666 'sample'=> wfMsg('link_sample'),
1667 'tip' => wfMsg('link_tip'),
1668 'key' => 'L'
1669 ),
1670 array( 'image' => 'button_extlink.png',
1671 'id' => 'mw-editbutton-extlink',
1672 'open' => '[',
1673 'close' => ']',
1674 'sample'=> wfMsg('extlink_sample'),
1675 'tip' => wfMsg('extlink_tip'),
1676 'key' => 'X'
1677 ),
1678 array( 'image' => 'button_headline.png',
1679 'id' => 'mw-editbutton-headline',
1680 'open' => "\\n== ",
1681 'close' => " ==\\n",
1682 'sample'=> wfMsg('headline_sample'),
1683 'tip' => wfMsg('headline_tip'),
1684 'key' => 'H'
1685 ),
1686 array( 'image' => 'button_image.png',
1687 'id' => 'mw-editbutton-image',
1688 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1689 'close' => ']]',
1690 'sample'=> wfMsg('image_sample'),
1691 'tip' => wfMsg('image_tip'),
1692 'key' => 'D'
1693 ),
1694 array( 'image' => 'button_media.png',
1695 'id' => 'mw-editbutton-media',
1696 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1697 'close' => ']]',
1698 'sample'=> wfMsg('media_sample'),
1699 'tip' => wfMsg('media_tip'),
1700 'key' => 'M'
1701 ),
1702 array( 'image' => 'button_math.png',
1703 'id' => 'mw-editbutton-math',
1704 'open' => "<math>",
1705 'close' => "<\\/math>",
1706 'sample'=> wfMsg('math_sample'),
1707 'tip' => wfMsg('math_tip'),
1708 'key' => 'C'
1709 ),
1710 array( 'image' => 'button_nowiki.png',
1711 'id' => 'mw-editbutton-nowiki',
1712 'open' => "<nowiki>",
1713 'close' => "<\\/nowiki>",
1714 'sample'=> wfMsg('nowiki_sample'),
1715 'tip' => wfMsg('nowiki_tip'),
1716 'key' => 'N'
1717 ),
1718 array( 'image' => 'button_sig.png',
1719 'id' => 'mw-editbutton-signature',
1720 'open' => '--~~~~',
1721 'close' => '',
1722 'sample'=> '',
1723 'tip' => wfMsg('sig_tip'),
1724 'key' => 'Y'
1725 ),
1726 array( 'image' => 'button_hr.png',
1727 'id' => 'mw-editbutton-hr',
1728 'open' => "\\n----\\n",
1729 'close' => '',
1730 'sample'=> '',
1731 'tip' => wfMsg('hr_tip'),
1732 'key' => 'R'
1733 )
1734 );
1735 $toolbar = "<div id='toolbar'>\n";
1736 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1737
1738 foreach($toolarray as $tool) {
1739
1740 $cssId = $tool['id'];
1741 $image=$wgStylePath.'/common/images/'.$tool['image'];
1742 $open=$tool['open'];
1743 $close=$tool['close'];
1744 $sample = wfEscapeJsString( $tool['sample'] );
1745
1746 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1747 // Older browsers show a "speedtip" type message only for ALT.
1748 // Ideally these should be different, realistically they
1749 // probably don't need to be.
1750 $tip = wfEscapeJsString( $tool['tip'] );
1751
1752 #$key = $tool["key"];
1753
1754 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1755 }
1756
1757 $toolbar.="/*]]>*/\n</script>";
1758 $toolbar.="\n</div>";
1759 return $toolbar;
1760 }
1761
1762 /**
1763 * Returns an array of html code of the following checkboxes:
1764 * minor and watch
1765 *
1766 * @param $tabindex Current tabindex
1767 * @param $skin Skin object
1768 * @param $checked Array of checkbox => bool, where bool indicates the checked
1769 * status of the checkbox
1770 *
1771 * @return array
1772 */
1773 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1774 global $wgUser;
1775
1776 $checkboxes = array();
1777
1778 $checkboxes['minor'] = '';
1779 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1780 if ( $wgUser->isAllowed('minoredit') ) {
1781 $attribs = array(
1782 'tabindex' => ++$tabindex,
1783 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1784 'id' => 'wpMinoredit',
1785 );
1786 $checkboxes['minor'] =
1787 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1788 "&nbsp;<label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1789 }
1790
1791 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1792 $checkboxes['watch'] = '';
1793 if ( $wgUser->isLoggedIn() ) {
1794 $attribs = array(
1795 'tabindex' => ++$tabindex,
1796 'accesskey' => wfMsg( 'accesskey-watch' ),
1797 'id' => 'wpWatchthis',
1798 );
1799 $checkboxes['watch'] =
1800 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1801 "&nbsp;<label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1802 }
1803 return $checkboxes;
1804 }
1805
1806 /**
1807 * Returns an array of html code of the following buttons:
1808 * save, diff, preview and live
1809 *
1810 * @param $tabindex Current tabindex
1811 *
1812 * @return array
1813 */
1814 public function getEditButtons(&$tabindex) {
1815 global $wgLivePreview, $wgUser;
1816
1817 $buttons = array();
1818
1819 $temp = array(
1820 'id' => 'wpSave',
1821 'name' => 'wpSave',
1822 'type' => 'submit',
1823 'tabindex' => ++$tabindex,
1824 'value' => wfMsg('savearticle'),
1825 'accesskey' => wfMsg('accesskey-save'),
1826 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1827 );
1828 $buttons['save'] = wfElement('input', $temp, '');
1829
1830 ++$tabindex; // use the same for preview and live preview
1831 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1832 $temp = array(
1833 'id' => 'wpPreview',
1834 'name' => 'wpPreview',
1835 'type' => 'submit',
1836 'tabindex' => $tabindex,
1837 'value' => wfMsg('showpreview'),
1838 'accesskey' => '',
1839 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1840 'style' => 'display: none;',
1841 );
1842 $buttons['preview'] = wfElement('input', $temp, '');
1843
1844 $temp = array(
1845 'id' => 'wpLivePreview',
1846 'name' => 'wpLivePreview',
1847 'type' => 'submit',
1848 'tabindex' => $tabindex,
1849 'value' => wfMsg('showlivepreview'),
1850 'accesskey' => wfMsg('accesskey-preview'),
1851 'title' => '',
1852 'onclick' => $this->doLivePreviewScript(),
1853 );
1854 $buttons['live'] = wfElement('input', $temp, '');
1855 } else {
1856 $temp = array(
1857 'id' => 'wpPreview',
1858 'name' => 'wpPreview',
1859 'type' => 'submit',
1860 'tabindex' => $tabindex,
1861 'value' => wfMsg('showpreview'),
1862 'accesskey' => wfMsg('accesskey-preview'),
1863 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1864 );
1865 $buttons['preview'] = wfElement('input', $temp, '');
1866 $buttons['live'] = '';
1867 }
1868
1869 $temp = array(
1870 'id' => 'wpDiff',
1871 'name' => 'wpDiff',
1872 'type' => 'submit',
1873 'tabindex' => ++$tabindex,
1874 'value' => wfMsg('showdiff'),
1875 'accesskey' => wfMsg('accesskey-diff'),
1876 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1877 );
1878 $buttons['diff'] = wfElement('input', $temp, '');
1879
1880 return $buttons;
1881 }
1882
1883 /**
1884 * Output preview text only. This can be sucked into the edit page
1885 * via JavaScript, and saves the server time rendering the skin as
1886 * well as theoretically being more robust on the client (doesn't
1887 * disturb the edit box's undo history, won't eat your text on
1888 * failure, etc).
1889 *
1890 * @todo This doesn't include category or interlanguage links.
1891 * Would need to enhance it a bit, <s>maybe wrap them in XML
1892 * or something...</s> that might also require more skin
1893 * initialization, so check whether that's a problem.
1894 */
1895 function livePreview() {
1896 global $wgOut;
1897 $wgOut->disable();
1898 header( 'Content-type: text/xml; charset=utf-8' );
1899 header( 'Cache-control: no-cache' );
1900
1901 $s =
1902 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1903 Xml::openElement( 'livepreview' ) .
1904 Xml::element( 'preview', null, $this->getPreviewText() ) .
1905 Xml::element( 'br', array( 'style' => 'clear: both;' ) ) .
1906 Xml::closeElement( 'livepreview' );
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->mTitle );
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