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