Setting the feed messages to be optional, and removing them from he.
[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 if ( $this->diff ) {
443 # Failed token check, but only requested "Show Changes".
444 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
445 } else {
446 # Page might be a hack attempt posted from
447 # an external site. Preview instead of saving.
448 wfDebug( "$fname: Failed token check; forcing preview\n" );
449 $this->preview = true;
450 }
451 }
452 $this->save = ! ( $this->preview OR $this->diff );
453 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
454 $this->edittime = null;
455 }
456
457 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
458 $this->starttime = null;
459 }
460
461 $this->recreate = $request->getCheck( 'wpRecreate' );
462
463 $this->minoredit = $request->getCheck( 'wpMinoredit' );
464 $this->watchthis = $request->getCheck( 'wpWatchthis' );
465
466 # Don't force edit summaries when a user is editing their own user or talk page
467 if( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) && $this->mTitle->getText() == $wgUser->getName() ) {
468 $this->allowBlankSummary = true;
469 } else {
470 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' );
471 }
472
473 $this->autoSumm = $request->getText( 'wpAutoSummary' );
474 } else {
475 # Not a posted form? Start with nothing.
476 wfDebug( "$fname: Not a posted form.\n" );
477 $this->textbox1 = '';
478 $this->textbox2 = '';
479 $this->mMetaData = '';
480 $this->summary = '';
481 $this->edittime = '';
482 $this->starttime = wfTimestampNow();
483 $this->preview = false;
484 $this->save = false;
485 $this->diff = false;
486 $this->minoredit = false;
487 $this->watchthis = false;
488 $this->recreate = false;
489 }
490
491 $this->oldid = $request->getInt( 'oldid' );
492
493 # Section edit can come from either the form or a link
494 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
495
496 $this->live = $request->getCheck( 'live' );
497 $this->editintro = $request->getText( 'editintro' );
498
499 wfProfileOut( $fname );
500 }
501
502 /**
503 * Make sure the form isn't faking a user's credentials.
504 *
505 * @param $request WebRequest
506 * @return bool
507 * @private
508 */
509 function tokenOk( &$request ) {
510 global $wgUser;
511 if( $wgUser->isAnon() ) {
512 # Anonymous users may not have a session
513 # open. Don't tokenize.
514 $this->mTokenOk = true;
515 } else {
516 $this->mTokenOk = $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
517 }
518 return $this->mTokenOk;
519 }
520
521 /** */
522 function showIntro() {
523 global $wgOut, $wgUser;
524 $addstandardintro=true;
525 if($this->editintro) {
526 $introtitle=Title::newFromText($this->editintro);
527 if(isset($introtitle) && $introtitle->userCanRead()) {
528 $rev=Revision::newFromTitle($introtitle);
529 if($rev) {
530 $wgOut->addSecondaryWikiText($rev->getText());
531 $addstandardintro=false;
532 }
533 }
534 }
535 if($addstandardintro) {
536 if ( $wgUser->isLoggedIn() )
537 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
538 else
539 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
540 }
541 }
542
543 /**
544 * Attempt submission
545 * @return bool false if output is done, true if the rest of the form should be displayed
546 */
547 function attemptSave() {
548 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
549 global $wgMaxArticleSize;
550
551 $fname = 'EditPage::attemptSave';
552 wfProfileIn( $fname );
553 wfProfileIn( "$fname-checks" );
554
555 # Reintegrate metadata
556 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
557 $this->mMetaData = '' ;
558
559 # Check for spam
560 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
561 $this->spamPage ( $matches[0] );
562 wfProfileOut( "$fname-checks" );
563 wfProfileOut( $fname );
564 return false;
565 }
566 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
567 # Error messages or other handling should be performed by the filter function
568 wfProfileOut( $fname );
569 wfProfileOut( "$fname-checks" );
570 return false;
571 }
572 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError ) ) ) {
573 # Error messages etc. could be handled within the hook...
574 wfProfileOut( $fname );
575 wfProfileOut( "$fname-checks" );
576 return false;
577 } elseif( $this->hookError != '' ) {
578 # ...or the hook could be expecting us to produce an error
579 wfProfileOut( "$fname-checks " );
580 wfProfileOut( $fname );
581 return true;
582 }
583 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
584 # Check block state against master, thus 'false'.
585 $this->blockedPage();
586 wfProfileOut( "$fname-checks" );
587 wfProfileOut( $fname );
588 return false;
589 }
590 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
591 if ( $this->kblength > $wgMaxArticleSize ) {
592 // Error will be displayed by showEditForm()
593 $this->tooBig = true;
594 wfProfileOut( "$fname-checks" );
595 wfProfileOut( $fname );
596 return true;
597 }
598
599 if ( !$wgUser->isAllowed('edit') ) {
600 if ( $wgUser->isAnon() ) {
601 $this->userNotLoggedInPage();
602 wfProfileOut( "$fname-checks" );
603 wfProfileOut( $fname );
604 return false;
605 }
606 else {
607 $wgOut->readOnlyPage();
608 wfProfileOut( "$fname-checks" );
609 wfProfileOut( $fname );
610 return false;
611 }
612 }
613
614 if ( wfReadOnly() ) {
615 $wgOut->readOnlyPage();
616 wfProfileOut( "$fname-checks" );
617 wfProfileOut( $fname );
618 return false;
619 }
620 if ( $wgUser->pingLimiter() ) {
621 $wgOut->rateLimited();
622 wfProfileOut( "$fname-checks" );
623 wfProfileOut( $fname );
624 return false;
625 }
626
627 # If the article has been deleted while editing, don't save it without
628 # confirmation
629 if ( $this->deletedSinceEdit && !$this->recreate ) {
630 wfProfileOut( "$fname-checks" );
631 wfProfileOut( $fname );
632 return true;
633 }
634
635 wfProfileOut( "$fname-checks" );
636
637 # If article is new, insert it.
638 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
639 if ( 0 == $aid ) {
640 // Late check for create permission, just in case *PARANOIA*
641 if ( !$this->mTitle->userCanCreate() ) {
642 wfDebug( "$fname: no create permission\n" );
643 $this->noCreatePermission();
644 wfProfileOut( $fname );
645 return;
646 }
647
648 # Don't save a new article if it's blank.
649 if ( ( '' == $this->textbox1 ) ) {
650 $wgOut->redirect( $this->mTitle->getFullURL() );
651 wfProfileOut( $fname );
652 return false;
653 }
654
655 # If no edit comment was given when creating a new page, and what's being
656 # created is a redirect, be smart and fill in a neat auto-comment
657 if( $this->summary == '' ) {
658 $rt = Title::newFromRedirect( $this->textbox1 );
659 if( is_object( $rt ) )
660 $this->summary = wfMsgForContent( 'autoredircomment', $rt->getPrefixedText() );
661 }
662
663 $isComment=($this->section=='new');
664 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
665 $this->minoredit, $this->watchthis, false, $isComment);
666
667 wfProfileOut( $fname );
668 return false;
669 }
670
671 # Article exists. Check for edit conflict.
672
673 $this->mArticle->clear(); # Force reload of dates, etc.
674 $this->mArticle->forUpdate( true ); # Lock the article
675
676 if( $this->mArticle->getTimestamp() != $this->edittime ) {
677 $this->isConflict = true;
678 if( $this->section == 'new' ) {
679 if( $this->mArticle->getUserText() == $wgUser->getName() &&
680 $this->mArticle->getComment() == $this->summary ) {
681 // Probably a duplicate submission of a new comment.
682 // This can happen when squid resends a request after
683 // a timeout but the first one actually went through.
684 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
685 } else {
686 // New comment; suppress conflict.
687 $this->isConflict = false;
688 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
689 }
690 }
691 }
692 $userid = $wgUser->getID();
693
694 if ( $this->isConflict) {
695 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
696 $this->mArticle->getTimestamp() . "'\n" );
697 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
698 }
699 else {
700 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
701 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
702 }
703 if( is_null( $text ) ) {
704 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
705 $this->isConflict = true;
706 $text = $this->textbox1;
707 }
708
709 # Suppress edit conflict with self, except for section edits where merging is required.
710 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
711 wfDebug( "Suppressing edit conflict, same user.\n" );
712 $this->isConflict = false;
713 } else {
714 # switch from section editing to normal editing in edit conflict
715 if($this->isConflict) {
716 # Attempt merge
717 if( $this->mergeChangesInto( $text ) ){
718 // Successful merge! Maybe we should tell the user the good news?
719 $this->isConflict = false;
720 wfDebug( "Suppressing edit conflict, successful merge.\n" );
721 } else {
722 $this->section = '';
723 $this->textbox1 = $text;
724 wfDebug( "Keeping edit conflict, failed merge.\n" );
725 }
726 }
727 }
728
729 if ( $this->isConflict ) {
730 wfProfileOut( $fname );
731 return true;
732 }
733
734 # If no edit comment was given when turning a page into a redirect, be smart
735 # and fill in a neat auto-comment
736 if( $this->summary == '' ) {
737 $rt = Title::newFromRedirect( $this->textbox1 );
738 if( is_object( $rt ) )
739 $this->summary = wfMsgForContent( 'autoredircomment', $rt->getPrefixedText() );
740 }
741
742 # Handle the user preference to force summaries here
743 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
744 if( md5( $this->summary ) == $this->autoSumm ) {
745 $this->missingSummary = true;
746 wfProfileOut( $fname );
747 return( true );
748 }
749 }
750
751 #And a similar thing for new sections
752 if( $this->section == 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
753 if (trim($this->summary) == '') {
754 $this->missingSummary = true;
755 wfProfileOut( $fname );
756 return( true );
757 }
758 }
759
760 # All's well
761 wfProfileIn( "$fname-sectionanchor" );
762 $sectionanchor = '';
763 if( $this->section == 'new' ) {
764 if ( $this->textbox1 == '' ) {
765 $this->missingComment = true;
766 return true;
767 }
768 if( $this->summary != '' ) {
769 $sectionanchor = $this->sectionAnchor( $this->summary );
770 }
771 } elseif( $this->section != '' ) {
772 # Try to get a section anchor from the section source, redirect to edited section if header found
773 # XXX: might be better to integrate this into Article::replaceSection
774 # for duplicate heading checking and maybe parsing
775 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
776 # we can't deal with anchors, includes, html etc in the header for now,
777 # headline would need to be parsed to improve this
778 if($hasmatch and strlen($matches[2]) > 0) {
779 $sectionanchor = $this->sectionAnchor( $matches[2] );
780 }
781 }
782 wfProfileOut( "$fname-sectionanchor" );
783
784 // Save errors may fall down to the edit form, but we've now
785 // merged the section into full text. Clear the section field
786 // so that later submission of conflict forms won't try to
787 // replace that into a duplicated mess.
788 $this->textbox1 = $text;
789 $this->section = '';
790
791 // Check for length errors again now that the section is merged in
792 $this->kblength = (int)(strlen( $text ) / 1024);
793 if ( $this->kblength > $wgMaxArticleSize ) {
794 $this->tooBig = true;
795 wfProfileOut( $fname );
796 return true;
797 }
798
799 # update the article here
800 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
801 $this->watchthis, '', $sectionanchor ) ) {
802 wfProfileOut( $fname );
803 return false;
804 } else {
805 $this->isConflict = true;
806 }
807 wfProfileOut( $fname );
808 return true;
809 }
810
811 /**
812 * Initialise form fields in the object
813 * Called on the first invocation, e.g. when a user clicks an edit link
814 */
815 function initialiseForm() {
816 $this->edittime = $this->mArticle->getTimestamp();
817 $this->textbox1 = $this->getContent();
818 $this->summary = '';
819 if ( !$this->mArticle->exists() && $this->mArticle->mTitle->getNamespace() == NS_MEDIAWIKI )
820 $this->textbox1 = wfMsgWeirdKey( $this->mArticle->mTitle->getText() ) ;
821 wfProxyCheck();
822 }
823
824 /**
825 * Send the edit form and related headers to $wgOut
826 * @param $formCallback Optional callable that takes an OutputPage
827 * parameter; will be called during form output
828 * near the top, for captchas and the like.
829 */
830 function showEditForm( $formCallback=null ) {
831 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
832
833 $fname = 'EditPage::showEditForm';
834 wfProfileIn( $fname );
835
836 $sk =& $wgUser->getSkin();
837
838 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
839
840 $wgOut->setRobotpolicy( 'noindex,nofollow' );
841
842 # Enabled article-related sidebar, toplinks, etc.
843 $wgOut->setArticleRelated( true );
844
845 if ( $this->isConflict ) {
846 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
847 $wgOut->setPageTitle( $s );
848 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
849
850 $this->textbox2 = $this->textbox1;
851 $this->textbox1 = $this->getContent();
852 $this->edittime = $this->mArticle->getTimestamp();
853 } else {
854
855 if( $this->section != '' ) {
856 if( $this->section == 'new' ) {
857 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
858 } else {
859 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
860 if( !$this->summary && !$this->preview && !$this->diff ) {
861 preg_match( "/^(=+)(.+)\\1/mi",
862 $this->textbox1,
863 $matches );
864 if( !empty( $matches[2] ) ) {
865 $this->summary = "/* ". trim($matches[2])." */ ";
866 }
867 }
868 }
869 } else {
870 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
871 }
872 $wgOut->setPageTitle( $s );
873
874 if ( $this->missingComment ) {
875 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
876 }
877
878 if( $this->missingSummary && $this->section != 'new' ) {
879 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
880 }
881
882 if( $this->missingSummary && $this->section == 'new' ) {
883 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
884 }
885
886 if( !$this->hookError == '' ) {
887 $wgOut->addWikiText( $this->hookError );
888 }
889
890 if ( !$this->checkUnicodeCompliantBrowser() ) {
891 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
892 }
893 if ( isset( $this->mArticle )
894 && isset( $this->mArticle->mRevision )
895 && !$this->mArticle->mRevision->isCurrent() ) {
896 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
897 $wgOut->addWikiText( wfMsg( 'editingold' ) );
898 }
899 }
900
901 if( wfReadOnly() ) {
902 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
903 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
904 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
905 } else {
906 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
907 # Check the skin exists
908 if( $this->isValidCssJsSubpage ) {
909 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
910 } else {
911 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
912 }
913 }
914 }
915
916 if( $this->mTitle->isProtected( 'edit' ) ) {
917 # Is the protection due to the namespace, e.g. interface text?
918 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
919 # Yes; remind the user
920 $notice = wfMsg( 'editinginterface' );
921 } elseif( $this->mTitle->isSemiProtected() ) {
922 # No; semi protected
923 $notice = wfMsg( 'semiprotectedpagewarning' );
924 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' ) {
925 $notice = '';
926 }
927 } else {
928 # No; regular protection
929 $notice = wfMsg( 'protectedpagewarning' );
930 }
931 $wgOut->addWikiText( $notice );
932 }
933
934 if ( $this->kblength === false ) {
935 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
936 }
937 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
938 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
939 } elseif( $this->kblength > 29 ) {
940 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
941 }
942
943 $rows = $wgUser->getIntOption( 'rows' );
944 $cols = $wgUser->getIntOption( 'cols' );
945
946 $ew = $wgUser->getOption( 'editwidth' );
947 if ( $ew ) $ew = " style=\"width:100%\"";
948 else $ew = '';
949
950 $q = 'action=submit';
951 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
952 $action = $this->mTitle->escapeLocalURL( $q );
953
954 $summary = wfMsg('summary');
955 $subject = wfMsg('subject');
956 $minor = wfMsgExt('minoredit', array('parseinline'));
957 $watchthis = wfMsgExt('watchthis', array('parseinline'));
958
959 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
960 wfMsgExt('cancel', array('parseinline')) );
961 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
962 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
963 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
964 htmlspecialchars( wfMsg( 'newwindow' ) );
965
966 global $wgRightsText;
967 $copywarn = "<div id=\"editpage-copywarn\">\n" .
968 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
969 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
970 $wgRightsText ) . "\n</div>";
971
972 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
973 # prepare toolbar for edit buttons
974 $toolbar = $this->getEditToolbar();
975 } else {
976 $toolbar = '';
977 }
978
979 // activate checkboxes if user wants them to be always active
980 if( !$this->preview && !$this->diff ) {
981 # Sort out the "watch" checkbox
982 if( $wgUser->getOption( 'watchdefault' ) ) {
983 # Watch all edits
984 $this->watchthis = true;
985 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
986 # Watch creations
987 $this->watchthis = true;
988 } elseif( $this->mTitle->userIsWatching() ) {
989 # Already watched
990 $this->watchthis = true;
991 }
992
993 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
994 }
995
996 $minoredithtml = '';
997
998 if ( $wgUser->isAllowed('minoredit') ) {
999 $minoredithtml =
1000 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
1001 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />\n".
1002 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>\n";
1003 }
1004
1005 $watchhtml = '';
1006
1007 if ( $wgUser->isLoggedIn() ) {
1008 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
1009 ($this->watchthis?" checked='checked'":"").
1010 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />\n".
1011 "<label for='wpWatchthis' title=\"" .
1012 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>\n";
1013 }
1014
1015 $checkboxhtml = $minoredithtml . $watchhtml;
1016
1017 if ( $wgUser->getOption( 'previewontop' ) ) {
1018
1019 if ( 'preview' == $this->formtype ) {
1020 $this->showPreview();
1021 } else {
1022 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1023 }
1024
1025 if ( 'diff' == $this->formtype ) {
1026 $wgOut->addHTML( $this->getDiff() );
1027 }
1028 }
1029
1030
1031 # if this is a comment, show a subject line at the top, which is also the edit summary.
1032 # Otherwise, show a summary field at the bottom
1033 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
1034 if( $this->section == 'new' ) {
1035 $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 />";
1036 $editsummary = '';
1037 } else {
1038 $commentsubject = '';
1039 $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 />";
1040 }
1041
1042 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1043 if( !$this->preview && !$this->diff ) {
1044 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1045 }
1046 $templates = $this->formatTemplates();
1047
1048 global $wgUseMetadataEdit ;
1049 if ( $wgUseMetadataEdit ) {
1050 $metadata = $this->mMetaData ;
1051 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1052 $top = wfMsgWikiHtml( 'metadata_help' );
1053 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1054 }
1055 else $metadata = "" ;
1056
1057 $hidden = '';
1058 $recreate = '';
1059 if ($this->deletedSinceEdit) {
1060 if ( 'save' != $this->formtype ) {
1061 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1062 } else {
1063 // Hide the toolbar and edit area, use can click preview to get it back
1064 // Add an confirmation checkbox and explanation.
1065 $toolbar = '';
1066 $hidden = 'type="hidden" style="display:none;"';
1067 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
1068 $recreate .=
1069 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1070 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1071 }
1072 }
1073
1074 $temp = array(
1075 'id' => 'wpSave',
1076 'name' => 'wpSave',
1077 'type' => 'submit',
1078 'tabindex' => '5',
1079 'value' => wfMsg('savearticle'),
1080 'accesskey' => wfMsg('accesskey-save'),
1081 'title' => wfMsg('tooltip-save'),
1082 );
1083 $buttons['save'] = wfElement('input', $temp, '');
1084 $temp = array(
1085 'id' => 'wpDiff',
1086 'name' => 'wpDiff',
1087 'type' => 'submit',
1088 'tabindex' => '7',
1089 'value' => wfMsg('showdiff'),
1090 'accesskey' => wfMsg('accesskey-diff'),
1091 'title' => wfMsg('tooltip-diff'),
1092 );
1093 $buttons['diff'] = wfElement('input', $temp, '');
1094
1095 global $wgLivePreview;
1096 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1097 $temp = array(
1098 'id' => 'wpPreview',
1099 'name' => 'wpPreview',
1100 'type' => 'submit',
1101 'tabindex' => '6',
1102 'value' => wfMsg('showpreview'),
1103 'accesskey' => '',
1104 'title' => wfMsg('tooltip-preview'),
1105 'style' => 'display: none;',
1106 );
1107 $buttons['preview'] = wfElement('input', $temp, '');
1108 $temp = array(
1109 'id' => 'wpLivePreview',
1110 'name' => 'wpLivePreview',
1111 'type' => 'submit',
1112 'tabindex' => '6',
1113 'value' => wfMsg('showlivepreview'),
1114 'accesskey' => wfMsg('accesskey-preview'),
1115 'title' => '',
1116 'onclick' => $this->doLivePreviewScript(),
1117 );
1118 $buttons['live'] = wfElement('input', $temp, '');
1119 } else {
1120 $temp = array(
1121 'id' => 'wpPreview',
1122 'name' => 'wpPreview',
1123 'type' => 'submit',
1124 'tabindex' => '6',
1125 'value' => wfMsg('showpreview'),
1126 'accesskey' => wfMsg('accesskey-preview'),
1127 'title' => wfMsg('tooltip-preview'),
1128 );
1129 $buttons['preview'] = wfElement('input', $temp, '');
1130 $buttons['live'] = '';
1131 }
1132
1133 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1134 ? ""
1135 : "<input type='hidden' name=\"safemode\" value='1' />\n";
1136
1137 $wgOut->addHTML( <<<END
1138 {$toolbar}
1139 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1140 END
1141 );
1142
1143 if( is_callable( $formCallback ) ) {
1144 call_user_func_array( $formCallback, array( &$wgOut ) );
1145 }
1146
1147 // Put these up at the top to ensure they aren't lost on early form submission
1148 $wgOut->addHTML( "
1149 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1150 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1151 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1152 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1153
1154 $wgOut->addHTML( <<<END
1155 $recreate
1156 {$commentsubject}
1157 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1158 cols='{$cols}'{$ew} $hidden>
1159 END
1160 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1161 "
1162 </textarea>
1163 " );
1164
1165 $wgOut->addWikiText( $copywarn );
1166 $wgOut->addHTML( "
1167 {$metadata}
1168 {$editsummary}
1169 {$checkboxhtml}
1170 {$safemodehtml}
1171 ");
1172
1173 $wgOut->addHTML(
1174 "<div class='editButtons'>
1175 {$buttons['save']}
1176 {$buttons['preview']}
1177 {$buttons['live']}
1178 {$buttons['diff']}
1179 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1180 </div><!-- editButtons -->
1181 </div><!-- editOptions -->");
1182
1183 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1184
1185 $wgOut->addHTML( "
1186 <div class='templatesUsed'>
1187 {$templates}
1188 </div>
1189 " );
1190
1191 if ( $wgUser->isLoggedIn() ) {
1192 /**
1193 * To make it harder for someone to slip a user a page
1194 * which submits an edit form to the wiki without their
1195 * knowledge, a random token is associated with the login
1196 * session. If it's not passed back with the submission,
1197 * we won't save the page, or render user JavaScript and
1198 * CSS previews.
1199 */
1200 $token = htmlspecialchars( $wgUser->editToken() );
1201 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1202 }
1203
1204 # If a blank edit summary was previously provided, and the appropriate
1205 # user preference is active, pass a hidden tag here. This will stop the
1206 # user being bounced back more than once in the event that a summary
1207 # is not required.
1208 if( $this->missingSummary ) {
1209 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1210 }
1211
1212 # For a bit more sophisticated detection of blank summaries, hash the
1213 # automatic one and pass that in a hidden field.
1214 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1215 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1216
1217 if ( $this->isConflict ) {
1218 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1219
1220 $de = new DifferenceEngine( $this->mTitle );
1221 $de->setText( $this->textbox2, $this->textbox1 );
1222 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1223
1224 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1225 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1226 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1227 }
1228 $wgOut->addHTML( "</form>\n" );
1229 if ( !$wgUser->getOption( 'previewontop' ) ) {
1230
1231 if ( $this->formtype == 'preview') {
1232 $this->showPreview();
1233 } else {
1234 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1235 }
1236
1237 if ( $this->formtype == 'diff') {
1238 $wgOut->addHTML( $this->getDiff() );
1239 }
1240
1241 }
1242
1243 wfProfileOut( $fname );
1244 }
1245
1246 /**
1247 * Append preview output to $wgOut.
1248 * Includes category rendering if this is a category page.
1249 * @private
1250 */
1251 function showPreview() {
1252 global $wgOut;
1253 $wgOut->addHTML( '<div id="wikiPreview">' );
1254 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1255 $this->mArticle->openShowCategory();
1256 }
1257 $previewOutput = $this->getPreviewText();
1258 $wgOut->addHTML( $previewOutput );
1259 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1260 $this->mArticle->closeShowCategory();
1261 }
1262 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
1263 $wgOut->addHTML( '</div>' );
1264 }
1265
1266 /**
1267 * Prepare a list of templates used by this page. Returns HTML.
1268 */
1269 function formatTemplates() {
1270 global $wgUser;
1271
1272 $fname = 'EditPage::formatTemplates';
1273 wfProfileIn( $fname );
1274
1275 $sk =& $wgUser->getSkin();
1276
1277 $outText = '';
1278 $templates = $this->mArticle->getUsedTemplates();
1279 if ( count( $templates ) > 0 ) {
1280 # Do a batch existence check
1281 $batch = new LinkBatch;
1282 foreach( $templates as $title ) {
1283 $batch->addObj( $title );
1284 }
1285 $batch->execute();
1286
1287 # Construct the HTML
1288 $outText = '<div class="mw-templatesUsedExplanation">' .
1289 wfMsgExt( 'templatesused', array( 'parse' ) ) .
1290 '</div><ul>';
1291 foreach ( $templates as $titleObj ) {
1292 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
1293 }
1294 $outText .= '</ul>';
1295 }
1296 wfProfileOut( $fname );
1297 return $outText;
1298 }
1299
1300 /**
1301 * Live Preview lets us fetch rendered preview page content and
1302 * add it to the page without refreshing the whole page.
1303 * If not supported by the browser it will fall through to the normal form
1304 * submission method.
1305 *
1306 * This function outputs a script tag to support live preview, and
1307 * returns an onclick handler which should be added to the attributes
1308 * of the preview button
1309 */
1310 function doLivePreviewScript() {
1311 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1312 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1313 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1314 '"></script>' . "\n" );
1315 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1316 return "return !livePreview(" .
1317 "getElementById('wikiPreview')," .
1318 "editform.wpTextbox1.value," .
1319 '"' . $liveAction . '"' . ")";
1320 }
1321
1322 function getLastDelete() {
1323 $dbr =& wfGetDB( DB_SLAVE );
1324 $fname = 'EditPage::getLastDelete';
1325 $res = $dbr->select(
1326 array( 'logging', 'user' ),
1327 array( 'log_type',
1328 'log_action',
1329 'log_timestamp',
1330 'log_user',
1331 'log_namespace',
1332 'log_title',
1333 'log_comment',
1334 'log_params',
1335 'user_name', ),
1336 array( 'log_namespace' => $this->mTitle->getNamespace(),
1337 'log_title' => $this->mTitle->getDBkey(),
1338 'log_type' => 'delete',
1339 'log_action' => 'delete',
1340 'user_id=log_user' ),
1341 $fname,
1342 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1343
1344 if($dbr->numRows($res) == 1) {
1345 while ( $x = $dbr->fetchObject ( $res ) )
1346 $data = $x;
1347 $dbr->freeResult ( $res ) ;
1348 } else {
1349 $data = null;
1350 }
1351 return $data;
1352 }
1353
1354 /**
1355 * @todo document
1356 */
1357 function getPreviewText() {
1358 global $wgOut, $wgUser, $wgTitle, $wgParser;
1359
1360 $fname = 'EditPage::getPreviewText';
1361 wfProfileIn( $fname );
1362
1363 if ( $this->mTriedSave && !$this->mTokenOk ) {
1364 $msg = 'session_fail_preview';
1365 } else {
1366 $msg = 'previewnote';
1367 }
1368 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1369 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1370 if ( $this->isConflict ) {
1371 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1372 }
1373
1374 $parserOptions = ParserOptions::newFromUser( $wgUser );
1375 $parserOptions->setEditSection( false );
1376
1377 global $wgRawHtml;
1378 if( $wgRawHtml && !$this->mTokenOk ) {
1379 // Could be an offsite preview attempt. This is very unsafe if
1380 // HTML is enabled, as it could be an attack.
1381 return $wgOut->parse( "<div class='previewnote'>" .
1382 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1383 }
1384
1385 # don't parse user css/js, show message about preview
1386 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1387
1388 if ( $this->isCssJsSubpage ) {
1389 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1390 $previewtext = wfMsg('usercsspreview');
1391 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1392 $previewtext = wfMsg('userjspreview');
1393 }
1394 $parserOptions->setTidy(true);
1395 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1396 $wgOut->addHTML( $parserOutput->mText );
1397 wfProfileOut( $fname );
1398 return $previewhead;
1399 } else {
1400 $toparse = $this->textbox1;
1401
1402 # If we're adding a comment, we need to show the
1403 # summary as the headline
1404 if($this->section=="new" && $this->summary!="") {
1405 $toparse="== {$this->summary} ==\n\n".$toparse;
1406 }
1407
1408 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1409 $parserOptions->setTidy(true);
1410 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1411 $wgTitle, $parserOptions );
1412
1413 $previewHTML = $parserOutput->getText();
1414 $wgOut->addParserOutputNoText( $parserOutput );
1415
1416 wfProfileOut( $fname );
1417 return $previewhead . $previewHTML;
1418 }
1419 }
1420
1421 /**
1422 * Call the stock "user is blocked" page
1423 */
1424 function blockedPage() {
1425 global $wgOut, $wgUser;
1426 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1427
1428 # If the user made changes, preserve them when showing the markup
1429 # (This happens when a user is blocked during edit, for instance)
1430 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1431 if( $first ) {
1432 $source = $this->mTitle->exists() ? $this->getContent() : false;
1433 } else {
1434 $source = $this->textbox1;
1435 }
1436
1437 # Spit out the source or the user's modified version
1438 if( $source !== false ) {
1439 $rows = $wgUser->getOption( 'rows' );
1440 $cols = $wgUser->getOption( 'cols' );
1441 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1442 $wgOut->addHtml( '<hr />' );
1443 $wgOut->addWikiText( wfMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() ) );
1444 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1445 }
1446 }
1447
1448 /**
1449 * Produce the stock "please login to edit pages" page
1450 */
1451 function userNotLoggedInPage() {
1452 global $wgUser, $wgOut;
1453 $skin = $wgUser->getSkin();
1454
1455 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1456 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle->getPrefixedUrl() );
1457
1458 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1459 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1460 $wgOut->setArticleRelated( false );
1461
1462 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1463 $wgOut->returnToMain( false, $this->mTitle->getPrefixedUrl() );
1464 }
1465
1466 /**
1467 * Creates a basic error page which informs the user that
1468 * they have to validate their email address before being
1469 * allowed to edit.
1470 */
1471 function userNotConfirmedPage() {
1472 global $wgOut;
1473
1474 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1475 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1476 $wgOut->setArticleRelated( false );
1477
1478 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1479 $wgOut->returnToMain( false );
1480 }
1481
1482 /**
1483 * Produce the stock "your edit contains spam" page
1484 *
1485 * @param $match Text which triggered one or more filters
1486 */
1487 function spamPage( $match = false ) {
1488 global $wgOut;
1489
1490 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1491 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1492 $wgOut->setArticleRelated( false );
1493
1494 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1495 if ( $match )
1496 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1497
1498 $wgOut->returnToMain( false );
1499 }
1500
1501 /**
1502 * @private
1503 * @todo document
1504 */
1505 function mergeChangesInto( &$editText ){
1506 $fname = 'EditPage::mergeChangesInto';
1507 wfProfileIn( $fname );
1508
1509 $db =& wfGetDB( DB_MASTER );
1510
1511 // This is the revision the editor started from
1512 $baseRevision = Revision::loadFromTimestamp(
1513 $db, $this->mArticle->mTitle, $this->edittime );
1514 if( is_null( $baseRevision ) ) {
1515 wfProfileOut( $fname );
1516 return false;
1517 }
1518 $baseText = $baseRevision->getText();
1519
1520 // The current state, we want to merge updates into it
1521 $currentRevision = Revision::loadFromTitle(
1522 $db, $this->mArticle->mTitle );
1523 if( is_null( $currentRevision ) ) {
1524 wfProfileOut( $fname );
1525 return false;
1526 }
1527 $currentText = $currentRevision->getText();
1528
1529 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1530 $editText = $result;
1531 wfProfileOut( $fname );
1532 return true;
1533 } else {
1534 wfProfileOut( $fname );
1535 return false;
1536 }
1537 }
1538
1539 /**
1540 * Check if the browser is on a blacklist of user-agents known to
1541 * mangle UTF-8 data on form submission. Returns true if Unicode
1542 * should make it through, false if it's known to be a problem.
1543 * @return bool
1544 * @private
1545 */
1546 function checkUnicodeCompliantBrowser() {
1547 global $wgBrowserBlackList;
1548 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1549 // No User-Agent header sent? Trust it by default...
1550 return true;
1551 }
1552 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1553 foreach ( $wgBrowserBlackList as $browser ) {
1554 if ( preg_match($browser, $currentbrowser) ) {
1555 return false;
1556 }
1557 }
1558 return true;
1559 }
1560
1561 /**
1562 * Format an anchor fragment as it would appear for a given section name
1563 * @param string $text
1564 * @return string
1565 * @private
1566 */
1567 function sectionAnchor( $text ) {
1568 $headline = Sanitizer::decodeCharReferences( $text );
1569 # strip out HTML
1570 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1571 $headline = trim( $headline );
1572 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1573 $replacearray = array(
1574 '%3A' => ':',
1575 '%' => '.'
1576 );
1577 return str_replace(
1578 array_keys( $replacearray ),
1579 array_values( $replacearray ),
1580 $sectionanchor );
1581 }
1582
1583 /**
1584 * Shows a bulletin board style toolbar for common editing functions.
1585 * It can be disabled in the user preferences.
1586 * The necessary JavaScript code can be found in style/wikibits.js.
1587 */
1588 function getEditToolbar() {
1589 global $wgStylePath, $wgContLang, $wgJsMimeType;
1590
1591 /**
1592 * toolarray an array of arrays which each include the filename of
1593 * the button image (without path), the opening tag, the closing tag,
1594 * and optionally a sample text that is inserted between the two when no
1595 * selection is highlighted.
1596 * The tip text is shown when the user moves the mouse over the button.
1597 *
1598 * Already here are accesskeys (key), which are not used yet until someone
1599 * can figure out a way to make them work in IE. However, we should make
1600 * sure these keys are not defined on the edit page.
1601 */
1602 $toolarray=array(
1603 array( 'image'=>'button_bold.png',
1604 'open' => "\'\'\'",
1605 'close' => "\'\'\'",
1606 'sample'=> wfMsg('bold_sample'),
1607 'tip' => wfMsg('bold_tip'),
1608 'key' => 'B'
1609 ),
1610 array( 'image'=>'button_italic.png',
1611 'open' => "\'\'",
1612 'close' => "\'\'",
1613 'sample'=> wfMsg('italic_sample'),
1614 'tip' => wfMsg('italic_tip'),
1615 'key' => 'I'
1616 ),
1617 array( 'image'=>'button_link.png',
1618 'open' => '[[',
1619 'close' => ']]',
1620 'sample'=> wfMsg('link_sample'),
1621 'tip' => wfMsg('link_tip'),
1622 'key' => 'L'
1623 ),
1624 array( 'image'=>'button_extlink.png',
1625 'open' => '[',
1626 'close' => ']',
1627 'sample'=> wfMsg('extlink_sample'),
1628 'tip' => wfMsg('extlink_tip'),
1629 'key' => 'X'
1630 ),
1631 array( 'image'=>'button_headline.png',
1632 'open' => "\\n== ",
1633 'close' => " ==\\n",
1634 'sample'=> wfMsg('headline_sample'),
1635 'tip' => wfMsg('headline_tip'),
1636 'key' => 'H'
1637 ),
1638 array( 'image'=>'button_image.png',
1639 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1640 'close' => ']]',
1641 'sample'=> wfMsg('image_sample'),
1642 'tip' => wfMsg('image_tip'),
1643 'key' => 'D'
1644 ),
1645 array( 'image' =>'button_media.png',
1646 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1647 'close' => ']]',
1648 'sample'=> wfMsg('media_sample'),
1649 'tip' => wfMsg('media_tip'),
1650 'key' => 'M'
1651 ),
1652 array( 'image' =>'button_math.png',
1653 'open' => "<math>",
1654 'close' => "<\\/math>",
1655 'sample'=> wfMsg('math_sample'),
1656 'tip' => wfMsg('math_tip'),
1657 'key' => 'C'
1658 ),
1659 array( 'image' =>'button_nowiki.png',
1660 'open' => "<nowiki>",
1661 'close' => "<\\/nowiki>",
1662 'sample'=> wfMsg('nowiki_sample'),
1663 'tip' => wfMsg('nowiki_tip'),
1664 'key' => 'N'
1665 ),
1666 array( 'image' =>'button_sig.png',
1667 'open' => '--~~~~',
1668 'close' => '',
1669 'sample'=> '',
1670 'tip' => wfMsg('sig_tip'),
1671 'key' => 'Y'
1672 ),
1673 array( 'image' =>'button_hr.png',
1674 'open' => "\\n----\\n",
1675 'close' => '',
1676 'sample'=> '',
1677 'tip' => wfMsg('hr_tip'),
1678 'key' => 'R'
1679 )
1680 );
1681 $toolbar = "<div id='toolbar'>\n";
1682 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1683
1684 foreach($toolarray as $tool) {
1685
1686 $image=$wgStylePath.'/common/images/'.$tool['image'];
1687 $open=$tool['open'];
1688 $close=$tool['close'];
1689 $sample = wfEscapeJsString( $tool['sample'] );
1690
1691 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1692 // Older browsers show a "speedtip" type message only for ALT.
1693 // Ideally these should be different, realistically they
1694 // probably don't need to be.
1695 $tip = wfEscapeJsString( $tool['tip'] );
1696
1697 #$key = $tool["key"];
1698
1699 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1700 }
1701
1702 $toolbar.="/*]]>*/\n</script>";
1703 $toolbar.="\n</div>";
1704 return $toolbar;
1705 }
1706
1707 /**
1708 * Output preview text only. This can be sucked into the edit page
1709 * via JavaScript, and saves the server time rendering the skin as
1710 * well as theoretically being more robust on the client (doesn't
1711 * disturb the edit box's undo history, won't eat your text on
1712 * failure, etc).
1713 *
1714 * @todo This doesn't include category or interlanguage links.
1715 * Would need to enhance it a bit, maybe wrap them in XML
1716 * or something... that might also require more skin
1717 * initialization, so check whether that's a problem.
1718 */
1719 function livePreview() {
1720 global $wgOut;
1721 $wgOut->disable();
1722 header( 'Content-type: text/xml' );
1723 header( 'Cache-control: no-cache' );
1724 # FIXME
1725 echo $this->getPreviewText( );
1726 /* To not shake screen up and down between preview and live-preview */
1727 echo "<br style=\"clear:both;\" />\n";
1728 }
1729
1730
1731 /**
1732 * Get a diff between the current contents of the edit box and the
1733 * version of the page we're editing from.
1734 *
1735 * If this is a section edit, we'll replace the section as for final
1736 * save and then make a comparison.
1737 *
1738 * @return string HTML
1739 */
1740 function getDiff() {
1741 $oldtext = $this->mArticle->fetchContent();
1742 $newtext = $this->mArticle->replaceSection(
1743 $this->section, $this->textbox1, $this->summary, $this->edittime );
1744 $newtext = $this->mArticle->preSaveTransform( $newtext );
1745 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1746 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1747 if ( $oldtext !== false || $newtext != '' ) {
1748 $de = new DifferenceEngine( $this->mTitle );
1749 $de->setText( $oldtext, $newtext );
1750 $difftext = $de->getDiff( $oldtitle, $newtitle );
1751 } else {
1752 $difftext = '';
1753 }
1754
1755 return '<div id="wikiDiff">' . $difftext . '</div>';
1756 }
1757
1758 /**
1759 * Filter an input field through a Unicode de-armoring process if it
1760 * came from an old browser with known broken Unicode editing issues.
1761 *
1762 * @param WebRequest $request
1763 * @param string $field
1764 * @return string
1765 * @private
1766 */
1767 function safeUnicodeInput( $request, $field ) {
1768 $text = rtrim( $request->getText( $field ) );
1769 return $request->getBool( 'safemode' )
1770 ? $this->unmakesafe( $text )
1771 : $text;
1772 }
1773
1774 /**
1775 * Filter an output field through a Unicode armoring process if it is
1776 * going to an old browser with known broken Unicode editing issues.
1777 *
1778 * @param string $text
1779 * @return string
1780 * @private
1781 */
1782 function safeUnicodeOutput( $text ) {
1783 global $wgContLang;
1784 $codedText = $wgContLang->recodeForEdit( $text );
1785 return $this->checkUnicodeCompliantBrowser()
1786 ? $codedText
1787 : $this->makesafe( $codedText );
1788 }
1789
1790 /**
1791 * A number of web browsers are known to corrupt non-ASCII characters
1792 * in a UTF-8 text editing environment. To protect against this,
1793 * detected browsers will be served an armored version of the text,
1794 * with non-ASCII chars converted to numeric HTML character references.
1795 *
1796 * Preexisting such character references will have a 0 added to them
1797 * to ensure that round-trips do not alter the original data.
1798 *
1799 * @param string $invalue
1800 * @return string
1801 * @private
1802 */
1803 function makesafe( $invalue ) {
1804 // Armor existing references for reversability.
1805 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1806
1807 $bytesleft = 0;
1808 $result = "";
1809 $working = 0;
1810 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1811 $bytevalue = ord( $invalue{$i} );
1812 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1813 $result .= chr( $bytevalue );
1814 $bytesleft = 0;
1815 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1816 $working = $working << 6;
1817 $working += ($bytevalue & 0x3F);
1818 $bytesleft--;
1819 if( $bytesleft <= 0 ) {
1820 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1821 }
1822 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1823 $working = $bytevalue & 0x1F;
1824 $bytesleft = 1;
1825 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1826 $working = $bytevalue & 0x0F;
1827 $bytesleft = 2;
1828 } else { //1111 0xxx
1829 $working = $bytevalue & 0x07;
1830 $bytesleft = 3;
1831 }
1832 }
1833 return $result;
1834 }
1835
1836 /**
1837 * Reverse the previously applied transliteration of non-ASCII characters
1838 * back to UTF-8. Used to protect data from corruption by broken web browsers
1839 * as listed in $wgBrowserBlackList.
1840 *
1841 * @param string $invalue
1842 * @return string
1843 * @private
1844 */
1845 function unmakesafe( $invalue ) {
1846 $result = "";
1847 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1848 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1849 $i += 3;
1850 $hexstring = "";
1851 do {
1852 $hexstring .= $invalue{$i};
1853 $i++;
1854 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1855
1856 // Do some sanity checks. These aren't needed for reversability,
1857 // but should help keep the breakage down if the editor
1858 // breaks one of the entities whilst editing.
1859 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1860 $codepoint = hexdec($hexstring);
1861 $result .= codepointToUtf8( $codepoint );
1862 } else {
1863 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1864 }
1865 } else {
1866 $result .= substr( $invalue, $i, 1 );
1867 }
1868 }
1869 // reverse the transform that we made for reversability reasons.
1870 return strtr( $result, array( "&#x0" => "&#x" ) );
1871 }
1872
1873 function noCreatePermission() {
1874 global $wgOut;
1875 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1876 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
1877 }
1878
1879 }
1880
1881 ?>