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