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