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