3 * Contain the EditPage class
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
20 var $isConflict = false;
21 var $isCssJsSubpage = false;
22 var $deletedSinceEdit = false;
26 var $mTokenOk = false;
27 var $mTriedSave = false;
29 var $kblength = false;
30 var $missingComment = false;
31 var $missingSummary = false;
32 var $allowBlankSummary = false;
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;
47 function EditPage( $article ) {
48 $this->mArticle
=& $article;
50 $this->mTitle
=& $wgTitle;
54 * This is the function that extracts metadata from the article body on the first view.
55 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
56 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
58 function extractMetaDataFromArticle () {
59 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
60 $this->mMetaData
= '' ;
61 if ( !$wgUseMetadataEdit ) return ;
62 if ( $wgMetadataWhitelist == '' ) return ;
64 $t = $this->mArticle
->getContent();
66 # MISSING : <nowiki> filtering
68 # Categories and language links
69 $t = explode ( "\n" , $t ) ;
70 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
71 $cat = $ll = array() ;
72 foreach ( $t AS $key => $x )
74 $y = trim ( strtolower ( $x ) ) ;
75 while ( substr ( $y , 0 , 2 ) == '[[' )
77 $y = explode ( ']]' , trim ( $x ) ) ;
78 $first = array_shift ( $y ) ;
79 $first = explode ( ':' , $first ) ;
80 $ns = array_shift ( $first ) ;
81 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
82 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
84 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
85 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
87 $x = implode ( ']]' , $y ) ;
89 $y = trim ( strtolower ( $x ) ) ;
93 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
94 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
95 $t = implode ( "\n" , $t ) ;
98 $sat = array () ; # stand-alone-templates; must be lowercase
99 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
100 $wl_article = new Article ( $wl_title ) ;
101 $wl = explode ( "\n" , $wl_article->getContent() ) ;
102 foreach ( $wl AS $x )
106 while ( substr ( $x , 0 , 1 ) == '*' )
109 $x = trim ( substr ( $x , 1 ) ) ;
113 $sat[] = strtolower ( $x ) ;
118 # Templates, but only some
119 $t = explode ( '{{' , $t ) ;
121 foreach ( $t AS $key => $x )
123 $y = explode ( '}}' , $x , 2 ) ;
124 if ( count ( $y ) == 2 )
127 $z = explode ( '|' , $z ) ;
128 $tn = array_shift ( $z ) ;
129 if ( in_array ( strtolower ( $tn ) , $sat ) )
131 $tl[] = '{{' . $y[0] . '}}' ;
133 $y = explode ( '}}' , $y[1] , 2 ) ;
135 else $t[$key] = '{{' . $x ;
137 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
140 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
141 $t = implode ( '' , $t ) ;
143 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
144 $this->mArticle
->mContent
= $t ;
145 $this->mMetaData
= $s ;
153 * This is the function that gets called for "action=edit". It
154 * sets up various member variables, then passes execution to
155 * another function, usually showEditForm()
157 * The edit form is self-submitting, so that when things like
158 * preview and edit conflicts occur, we get the same form back
159 * with the extra stuff added. Only when the final submission
160 * is made and all is well do we actually save and redirect to
161 * the newly-edited page.
164 global $wgOut, $wgUser, $wgRequest, $wgTitle;
165 global $wgEmailConfirmToEdit;
167 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
170 $fname = 'EditPage::edit';
171 wfProfileIn( $fname );
172 wfDebug( "$fname: enter\n" );
174 // this is not an article
175 $wgOut->setArticleFlag(false);
177 $this->importFormData( $wgRequest );
178 $this->firsttime
= false;
181 $this->livePreview();
182 wfProfileOut( $fname );
186 if ( ! $this->mTitle
->userCanEdit() ) {
187 wfDebug( "$fname: user can't edit\n" );
188 $wgOut->readOnlyPage( $this->mArticle
->getContent(), true );
189 wfProfileOut( $fname );
192 wfDebug( "$fname: Checking blocks\n" );
193 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
194 # When previewing, don't check blocked state - will get caught at save time.
195 # Also, check when starting edition is done against slave to improve performance.
196 wfDebug( "$fname: user is blocked\n" );
197 $wgOut->blockedPage();
198 wfProfileOut( $fname );
201 if ( !$wgUser->isAllowed('edit') ) {
202 if ( $wgUser->isAnon() ) {
203 wfDebug( "$fname: user must log in\n" );
204 $this->userNotLoggedInPage();
205 wfProfileOut( $fname );
208 wfDebug( "$fname: read-only page\n" );
209 $wgOut->readOnlyPage( $this->mArticle
->getContent(), true );
210 wfProfileOut( $fname );
214 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
215 wfDebug("$fname: user must confirm e-mail address\n");
216 $this->userNotConfirmedPage();
217 wfProfileOut($fname);
220 if ( !$this->mTitle
->userCan( 'create' ) && !$this->mTitle
->exists() ) {
221 wfDebug( "$fname: no create permission\n" );
222 $this->noCreatePermission();
223 wfProfileOut( $fname );
226 if ( wfReadOnly() ) {
227 wfDebug( "$fname: read-only mode is engaged\n" );
228 if( $this->save ||
$this->preview
) {
229 $this->formtype
= 'preview';
230 } else if ( $this->diff
) {
231 $this->formtype
= 'diff';
233 $wgOut->readOnlyPage( $this->mArticle
->getContent() );
234 wfProfileOut( $fname );
239 $this->formtype
= 'save';
240 } else if ( $this->preview
) {
241 $this->formtype
= 'preview';
242 } else if ( $this->diff
) {
243 $this->formtype
= 'diff';
244 } else { # First time through
245 $this->firsttime
= true;
246 if( $this->previewOnOpen() ) {
247 $this->formtype
= 'preview';
249 $this->extractMetaDataFromArticle () ;
250 $this->formtype
= 'initial';
255 wfProfileIn( "$fname-business-end" );
257 $this->isConflict
= false;
258 // css / js subpages of user pages get a special treatment
259 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
260 $this->isValidCssJsSubpage
= $wgTitle->isValidCssJsSubpage();
262 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
263 * no matter it's current state
265 $this->deletedSinceEdit
= false;
266 if ( $this->edittime
!= '' ) {
267 /* Note that we rely on logging table, which hasn't been always there,
268 * but that doesn't matter, because this only applies to brand new
269 * deletes. This is done on every preview and save request. Move it further down
270 * to only perform it on saves
272 if ( $this->mTitle
->isDeleted() ) {
273 $this->lastDelete
= $this->getLastDelete();
274 if ( !is_null($this->lastDelete
) ) {
275 $deletetime = $this->lastDelete
->log_timestamp
;
276 if ( ($deletetime - $this->starttime
) > 0 ) {
277 $this->deletedSinceEdit
= true;
283 if(!$this->mTitle
->getArticleID() && ('initial' == $this->formtype ||
$this->firsttime
)) { # new article
286 if( $this->mTitle
->isTalkPage() ) {
287 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
290 # Attempt submission here. This will check for edit conflicts,
291 # and redundantly check for locked database, blocked IPs, etc.
292 # that edit() already checked just in case someone tries to sneak
293 # in the back door with a hand-edited submission URL.
295 if ( 'save' == $this->formtype
) {
296 if ( !$this->attemptSave() ) {
297 wfProfileOut( "$fname-business-end" );
298 wfProfileOut( $fname );
303 # First time through: get contents, set time for conflict
305 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
306 $this->initialiseForm();
307 if( !$this->mTitle
->getArticleId() )
308 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
311 $this->showEditForm();
312 wfProfileOut( "$fname-business-end" );
313 wfProfileOut( $fname );
317 * Return true if this page should be previewed when the edit form
318 * is initially opened.
322 function previewOnOpen() {
324 return $this->section
!= 'new' &&
325 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle
->exists() ) ||
326 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
327 !$this->mTitle
->exists() ) );
334 function importFormData( &$request ) {
335 global $wgLang, $wgUser;
336 $fname = 'EditPage::importFormData';
337 wfProfileIn( $fname );
339 if( $request->wasPosted() ) {
340 # These fields need to be checked for encoding.
341 # Also remove trailing whitespace, but don't remove _initial_
342 # whitespace from the text boxes. This may be significant formatting.
343 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
344 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
345 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
346 # Truncate for whole multibyte characters. +5 bytes for ellipsis
347 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
349 $this->edittime
= $request->getVal( 'wpEdittime' );
350 $this->starttime
= $request->getVal( 'wpStarttime' );
352 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
354 if( is_null( $this->edittime
) ) {
355 # If the form is incomplete, force to preview.
356 wfDebug( "$fname: Form data appears to be incomplete\n" );
357 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
358 $this->preview
= true;
360 /* Fallback for live preview */
361 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
362 $this->diff
= $request->getCheck( 'wpDiff' );
364 // Remember whether a save was requested, so we can indicate
365 // if we forced preview due to session failure.
366 $this->mTriedSave
= !$this->preview
;
368 if ( $this->tokenOk( $request ) ) {
369 # Some browsers will not report any submit button
370 # if the user hits enter in the comment box.
371 # The unmarked state will be assumed to be a save,
372 # if the form seems otherwise complete.
373 wfDebug( "$fname: Passed token check.\n" );
375 # Page might be a hack attempt posted from
376 # an external site. Preview instead of saving.
377 wfDebug( "$fname: Failed token check; forcing preview\n" );
378 $this->preview
= true;
381 $this->save
= ! ( $this->preview
OR $this->diff
);
382 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
383 $this->edittime
= null;
386 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
387 $this->starttime
= null;
390 $this->recreate
= $request->getCheck( 'wpRecreate' );
392 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
393 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
395 # Don't force edit summaries when a user is editing their own user or talk page
396 if( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) && $this->mTitle
->getText() == $wgUser->getName() ) {
397 $this->allowBlankSummary
= true;
399 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
402 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
404 # Not a posted form? Start with nothing.
405 wfDebug( "$fname: Not a posted form.\n" );
406 $this->textbox1
= '';
407 $this->textbox2
= '';
408 $this->mMetaData
= '';
410 $this->edittime
= '';
411 $this->starttime
= wfTimestampNow();
412 $this->preview
= false;
415 $this->minoredit
= false;
416 $this->watchthis
= false;
417 $this->recreate
= false;
420 $this->oldid
= $request->getInt( 'oldid' );
422 # Section edit can come from either the form or a link
423 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
425 $this->live
= $request->getCheck( 'live' );
426 $this->editintro
= $request->getText( 'editintro' );
428 wfProfileOut( $fname );
432 * Make sure the form isn't faking a user's credentials.
434 * @param $request WebRequest
438 function tokenOk( &$request ) {
440 if( $wgUser->isAnon() ) {
441 # Anonymous users may not have a session
442 # open. Don't tokenize.
443 $this->mTokenOk
= true;
445 $this->mTokenOk
= $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
447 return $this->mTokenOk
;
451 function showIntro() {
452 global $wgOut, $wgUser;
453 $addstandardintro=true;
454 if($this->editintro
) {
455 $introtitle=Title
::newFromText($this->editintro
);
456 if(isset($introtitle) && $introtitle->userCanRead()) {
457 $rev=Revision
::newFromTitle($introtitle);
459 $wgOut->addSecondaryWikiText($rev->getText());
460 $addstandardintro=false;
464 if($addstandardintro) {
465 if ( $wgUser->isLoggedIn() )
466 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
468 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
474 * @return bool false if output is done, true if the rest of the form should be displayed
476 function attemptSave() {
477 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
478 global $wgMaxArticleSize;
480 $fname = 'EditPage::attemptSave';
481 wfProfileIn( $fname );
482 wfProfileIn( "$fname-checks" );
484 # Reintegrate metadata
485 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
486 $this->mMetaData
= '' ;
489 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
490 $this->spamPage ( $matches[0] );
491 wfProfileOut( "$fname-checks" );
492 wfProfileOut( $fname );
495 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
496 # Error messages or other handling should be performed by the filter function
497 wfProfileOut( $fname );
498 wfProfileOut( "$fname-checks" );
501 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
) ) ) {
502 # Error messages etc. could be handled within the hook...
503 wfProfileOut( $fname );
504 wfProfileOut( "$fname-checks" );
506 } elseif( $this->hookError
!= '' ) {
507 # ...or the hook could be expecting us to produce an error
508 wfProfileOut( "$fname-checks " );
509 wfProfileOut( $fname );
512 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
513 # Check block state against master, thus 'false'.
514 $this->blockedIPpage();
515 wfProfileOut( "$fname-checks" );
516 wfProfileOut( $fname );
519 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
520 if ( $this->kblength
> $wgMaxArticleSize ) {
521 // Error will be displayed by showEditForm()
522 $this->tooBig
= true;
523 wfProfileOut( "$fname-checks" );
524 wfProfileOut( $fname );
528 if ( !$wgUser->isAllowed('edit') ) {
529 if ( $wgUser->isAnon() ) {
530 $this->userNotLoggedInPage();
531 wfProfileOut( "$fname-checks" );
532 wfProfileOut( $fname );
536 $wgOut->readOnlyPage();
537 wfProfileOut( "$fname-checks" );
538 wfProfileOut( $fname );
543 if ( wfReadOnly() ) {
544 $wgOut->readOnlyPage();
545 wfProfileOut( "$fname-checks" );
546 wfProfileOut( $fname );
549 if ( $wgUser->pingLimiter() ) {
550 $wgOut->rateLimited();
551 wfProfileOut( "$fname-checks" );
552 wfProfileOut( $fname );
556 # If the article has been deleted while editing, don't save it without
558 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
559 wfProfileOut( "$fname-checks" );
560 wfProfileOut( $fname );
564 wfProfileOut( "$fname-checks" );
566 # If article is new, insert it.
567 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
569 // Late check for create permission, just in case *PARANOIA*
570 if ( !$this->mTitle
->userCan( 'create' ) ) {
571 wfDebug( "$fname: no create permission\n" );
572 $this->noCreatePermission();
573 wfProfileOut( $fname );
577 # Don't save a new article if it's blank.
578 if ( ( '' == $this->textbox1
) ) {
579 $wgOut->redirect( $this->mTitle
->getFullURL() );
580 wfProfileOut( $fname );
584 # If no edit comment was given when creating a new page, and what's being
585 # created is a redirect, be smart and fill in a neat auto-comment
586 if( $this->summary
== '' ) {
587 $rt = Title
::newFromRedirect( $this->textbox1
);
588 if( is_object( $rt ) )
589 $this->summary
= wfMsgForContent( 'autoredircomment', $rt->getPrefixedText() );
592 $isComment=($this->section
=='new');
593 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
594 $this->minoredit
, $this->watchthis
, false, $isComment);
596 wfProfileOut( $fname );
600 # Article exists. Check for edit conflict.
602 $this->mArticle
->clear(); # Force reload of dates, etc.
603 $this->mArticle
->forUpdate( true ); # Lock the article
605 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
606 $this->isConflict
= true;
607 if( $this->section
== 'new' ) {
608 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
609 $this->mArticle
->getComment() == $this->summary
) {
610 // Probably a duplicate submission of a new comment.
611 // This can happen when squid resends a request after
612 // a timeout but the first one actually went through.
613 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
615 // New comment; suppress conflict.
616 $this->isConflict
= false;
617 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
621 $userid = $wgUser->getID();
623 if ( $this->isConflict
) {
624 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
625 $this->mArticle
->getTimestamp() . "'\n" );
626 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
629 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
630 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
632 if( is_null( $text ) ) {
633 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
634 $this->isConflict
= true;
635 $text = $this->textbox1
;
638 # Suppress edit conflict with self, except for section edits where merging is required.
639 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
640 wfDebug( "Suppressing edit conflict, same user.\n" );
641 $this->isConflict
= false;
643 # switch from section editing to normal editing in edit conflict
644 if($this->isConflict
) {
646 if( $this->mergeChangesInto( $text ) ){
647 // Successful merge! Maybe we should tell the user the good news?
648 $this->isConflict
= false;
649 wfDebug( "Suppressing edit conflict, successful merge.\n" );
652 $this->textbox1
= $text;
653 wfDebug( "Keeping edit conflict, failed merge.\n" );
658 if ( $this->isConflict
) {
659 wfProfileOut( $fname );
663 # If no edit comment was given when turning a page into a redirect, be smart
664 # and fill in a neat auto-comment
665 if( $this->summary
== '' ) {
666 $rt = Title
::newFromRedirect( $this->textbox1
);
667 if( is_object( $rt ) )
668 $this->summary
= wfMsgForContent( 'autoredircomment', $rt->getPrefixedText() );
671 # Handle the user preference to force summaries here
672 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
673 if( md5( $this->summary
) == $this->autoSumm
) {
674 $this->missingSummary
= true;
675 wfProfileOut( $fname );
681 wfProfileIn( "$fname-sectionanchor" );
683 if( $this->section
== 'new' ) {
684 if ( $this->textbox1
== '' ) {
685 $this->missingComment
= true;
688 if( $this->summary
!= '' ) {
689 $sectionanchor = $this->sectionAnchor( $this->summary
);
691 } elseif( $this->section
!= '' ) {
692 # Try to get a section anchor from the section source, redirect to edited section if header found
693 # XXX: might be better to integrate this into Article::replaceSection
694 # for duplicate heading checking and maybe parsing
695 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
696 # we can't deal with anchors, includes, html etc in the header for now,
697 # headline would need to be parsed to improve this
698 if($hasmatch and strlen($matches[2]) > 0) {
699 $sectionanchor = $this->sectionAnchor( $matches[2] );
702 wfProfileOut( "$fname-sectionanchor" );
704 // Save errors may fall down to the edit form, but we've now
705 // merged the section into full text. Clear the section field
706 // so that later submission of conflict forms won't try to
707 // replace that into a duplicated mess.
708 $this->textbox1
= $text;
711 // Check for length errors again now that the section is merged in
712 $this->kblength
= (int)(strlen( $text ) / 1024);
713 if ( $this->kblength
> $wgMaxArticleSize ) {
714 $this->tooBig
= true;
715 wfProfileOut( $fname );
719 # update the article here
720 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
721 $this->watchthis
, '', $sectionanchor ) ) {
722 wfProfileOut( $fname );
725 $this->isConflict
= true;
727 wfProfileOut( $fname );
732 * Initialise form fields in the object
733 * Called on the first invocation, e.g. when a user clicks an edit link
735 function initialiseForm() {
736 $this->edittime
= $this->mArticle
->getTimestamp();
737 $this->textbox1
= $this->mArticle
->getContent();
739 if ( !$this->mArticle
->exists() && $this->mArticle
->mTitle
->getNamespace() == NS_MEDIAWIKI
)
740 $this->textbox1
= wfMsgWeirdKey ( $this->mArticle
->mTitle
->getText() ) ;
745 * Send the edit form and related headers to $wgOut
746 * @param $formCallback Optional callable that takes an OutputPage
747 * parameter; will be called during form output
748 * near the top, for captchas and the like.
750 function showEditForm( $formCallback=null ) {
751 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
753 $fname = 'EditPage::showEditForm';
754 wfProfileIn( $fname );
756 $sk =& $wgUser->getSkin();
758 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
760 $wgOut->setRobotpolicy( 'noindex,nofollow' );
762 # Enabled article-related sidebar, toplinks, etc.
763 $wgOut->setArticleRelated( true );
765 if ( $this->isConflict
) {
766 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
767 $wgOut->setPageTitle( $s );
768 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
770 $this->textbox2
= $this->textbox1
;
771 $this->textbox1
= $this->mArticle
->getContent();
772 $this->edittime
= $this->mArticle
->getTimestamp();
775 if( $this->section
!= '' ) {
776 if( $this->section
== 'new' ) {
777 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
779 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
780 if( !$this->preview
&& !$this->diff
) {
781 preg_match( "/^(=+)(.+)\\1/mi",
784 if( !empty( $matches[2] ) ) {
785 $this->summary
= "/* ". trim($matches[2])." */ ";
790 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
792 $wgOut->setPageTitle( $s );
794 if ( $this->missingComment
) {
795 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
798 if( $this->missingSummary
) {
799 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
802 if( !$this->hookError
== '' ) {
803 $wgOut->addWikiText( $this->hookError
);
806 if ( !$this->checkUnicodeCompliantBrowser() ) {
807 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
809 if ( isset( $this->mArticle
)
810 && isset( $this->mArticle
->mRevision
)
811 && !$this->mArticle
->mRevision
->isCurrent() ) {
812 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
813 $wgOut->addWikiText( wfMsg( 'editingold' ) );
817 $curUP = $wgUser->getUserPage();
818 $editingOTP = substr( $this->mTitle
->getPrefixedText(), 0, strlen( $curUP->getPrefixedText() ) ) != $curUP->getPrefixedText()
819 && $this->formtype
!= 'preview'
820 && $this->formtype
!= 'diff';
822 $utpLink = $sk->makeKnownLinkObj( $this->mTitle
->getTalkPage(), wfMsgHtml( 'editinguserpagetalklink' ), 'action=edit' );
823 $wgOut->addHtml( wfMsgWikiHtml( 'editinguserpage', $utpLink ) );
827 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
828 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
829 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
831 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
832 # Check the skin exists
833 if( $this->isValidCssJsSubpage
) {
834 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
836 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
841 if( $this->mTitle
->isProtected( 'edit' ) ) {
842 # Is the protection due to the namespace, e.g. interface text?
843 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
844 # Yes; remind the user
845 $notice = wfMsg( 'editinginterface' );
846 } elseif( $this->mTitle
->isSemiProtected() ) {
848 $notice = wfMsg( 'semiprotectedpagewarning' );
849 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) ||
$notice == '-' ) {
853 # No; regular protection
854 $notice = wfMsg( 'protectedpagewarning' );
856 $wgOut->addWikiText( $notice );
859 if ( $this->kblength
=== false ) {
860 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
862 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
863 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgMaxArticleSize ) );
864 } elseif( $this->kblength
> 29 ) {
865 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) ) );
868 $rows = $wgUser->getIntOption( 'rows' );
869 $cols = $wgUser->getIntOption( 'cols' );
871 $ew = $wgUser->getOption( 'editwidth' );
872 if ( $ew ) $ew = " style=\"width:100%\"";
875 $q = 'action=submit';
876 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
877 $action = $this->mTitle
->escapeLocalURL( $q );
879 $summary = wfMsg('summary');
880 $subject = wfMsg('subject');
881 $minor = wfMsgExt('minoredit', array('parseinline'));
882 $watchthis = wfMsgExt('watchthis', array('parseinline'));
884 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
885 wfMsgExt('cancel', array('parseinline')) );
886 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
887 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
888 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
889 htmlspecialchars( wfMsg( 'newwindow' ) );
891 global $wgRightsText;
892 $copywarn = "<div id=\"editpage-copywarn\">\n" .
893 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
894 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
895 $wgRightsText ) . "\n</div>";
897 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
898 # prepare toolbar for edit buttons
899 $toolbar = $this->getEditToolbar();
904 // activate checkboxes if user wants them to be always active
905 if( !$this->preview
&& !$this->diff
) {
906 # Sort out the "watch" checkbox
907 if( $wgUser->getOption( 'watchdefault' ) ) {
909 $this->watchthis
= true;
910 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
912 $this->watchthis
= true;
913 } elseif( $this->mTitle
->userIsWatching() ) {
915 $this->watchthis
= true;
918 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
923 if ( $wgUser->isAllowed('minoredit') ) {
925 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?
" checked='checked'":"").
926 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />\n".
927 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>\n";
932 if ( $wgUser->isLoggedIn() ) {
933 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
934 ($this->watchthis?
" checked='checked'":"").
935 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />\n".
936 "<label for='wpWatchthis' title=\"" .
937 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>\n";
940 $checkboxhtml = $minoredithtml . $watchhtml;
942 if ( $wgUser->getOption( 'previewontop' ) ) {
944 if ( 'preview' == $this->formtype
) {
945 $this->showPreview();
947 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
950 if ( 'diff' == $this->formtype
) {
951 $wgOut->addHTML( $this->getDiff() );
956 # if this is a comment, show a subject line at the top, which is also the edit summary.
957 # Otherwise, show a summary field at the bottom
958 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
959 if( $this->section
== 'new' ) {
960 $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 />";
963 $commentsubject = '';
964 $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 />";
967 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
968 if( !$this->preview
&& !$this->diff
) {
969 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
971 $templates = $this->formatTemplates();
973 global $wgUseMetadataEdit ;
974 if ( $wgUseMetadataEdit ) {
975 $metadata = $this->mMetaData
;
976 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
977 $top = wfMsgWikiHtml( 'metadata_help' );
978 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
980 else $metadata = "" ;
984 if ($this->deletedSinceEdit
) {
985 if ( 'save' != $this->formtype
) {
986 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
988 // Hide the toolbar and edit area, use can click preview to get it back
989 // Add an confirmation checkbox and explanation.
991 $hidden = 'type="hidden" style="display:none;"';
992 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
994 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
995 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1004 'value' => wfMsg('savearticle'),
1005 'accesskey' => wfMsg('accesskey-save'),
1006 'title' => wfMsg('tooltip-save'),
1008 $buttons['save'] = wfElement('input', $temp, '');
1014 'value' => wfMsg('showdiff'),
1015 'accesskey' => wfMsg('accesskey-diff'),
1016 'title' => wfMsg('tooltip-diff'),
1018 $buttons['diff'] = wfElement('input', $temp, '');
1020 global $wgLivePreview;
1021 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1023 'id' => 'wpPreview',
1024 'name' => 'wpPreview',
1027 'value' => wfMsg('showpreview'),
1029 'title' => wfMsg('tooltip-preview'),
1030 'style' => 'display: none;',
1032 $buttons['preview'] = wfElement('input', $temp, '');
1034 'id' => 'wpLivePreview',
1035 'name' => 'wpLivePreview',
1038 'value' => wfMsg('showlivepreview'),
1039 'accesskey' => wfMsg('accesskey-preview'),
1041 'onclick' => $this->doLivePreviewScript(),
1043 $buttons['live'] = wfElement('input', $temp, '');
1046 'id' => 'wpPreview',
1047 'name' => 'wpPreview',
1050 'value' => wfMsg('showpreview'),
1051 'accesskey' => wfMsg('accesskey-preview'),
1052 'title' => wfMsg('tooltip-preview'),
1054 $buttons['preview'] = wfElement('input', $temp, '');
1055 $buttons['live'] = '';
1058 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1060 : "<input type='hidden' name=\"safemode\" value='1' />\n";
1062 $wgOut->addHTML( <<<END
1064 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1068 if( is_callable( $formCallback ) ) {
1069 call_user_func_array( $formCallback, array( &$wgOut ) );
1072 // Put these up at the top to ensure they aren't lost on early form submission
1074 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1075 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1076 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1077 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1079 $wgOut->addHTML( <<<END
1082 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1083 cols='{$cols}'{$ew} $hidden>
1085 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
1090 $wgOut->addWikiText( $copywarn );
1099 "<div class='editButtons'>
1101 {$buttons['preview']}
1104 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1105 </div><!-- editButtons -->
1106 </div><!-- editOptions -->");
1108 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1111 <div class='templatesUsed'>
1116 if ( $wgUser->isLoggedIn() ) {
1118 * To make it harder for someone to slip a user a page
1119 * which submits an edit form to the wiki without their
1120 * knowledge, a random token is associated with the login
1121 * session. If it's not passed back with the submission,
1122 * we won't save the page, or render user JavaScript and
1125 $token = htmlspecialchars( $wgUser->editToken() );
1126 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1129 # If a blank edit summary was previously provided, and the appropriate
1130 # user preference is active, pass a hidden tag here. This will stop the
1131 # user being bounced back more than once in the event that a summary
1133 if( $this->missingSummary
) {
1134 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1137 # For a bit more sophisticated detection of blank summaries, hash the
1138 # automatic one and pass that in a hidden field.
1139 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1140 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1142 if ( $this->isConflict
) {
1143 require_once( "DifferenceEngine.php" );
1144 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1146 $de = new DifferenceEngine( $this->mTitle
);
1147 $de->setText( $this->textbox2
, $this->textbox1
);
1148 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1150 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1151 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1152 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1154 $wgOut->addHTML( "</form>\n" );
1155 if ( !$wgUser->getOption( 'previewontop' ) ) {
1157 if ( $this->formtype
== 'preview') {
1158 $this->showPreview();
1160 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1163 if ( $this->formtype
== 'diff') {
1164 $wgOut->addHTML( $this->getDiff() );
1169 wfProfileOut( $fname );
1173 * Append preview output to $wgOut.
1174 * Includes category rendering if this is a category page.
1177 function showPreview() {
1179 $wgOut->addHTML( '<div id="wikiPreview">' );
1180 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1181 $this->mArticle
->openShowCategory();
1183 $previewOutput = $this->getPreviewText();
1184 $wgOut->addHTML( $previewOutput );
1185 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1186 $this->mArticle
->closeShowCategory();
1188 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
1189 $wgOut->addHTML( '</div>' );
1193 * Prepare a list of templates used by this page. Returns HTML.
1195 function formatTemplates() {
1198 $fname = 'EditPage::formatTemplates';
1199 wfProfileIn( $fname );
1201 $sk =& $wgUser->getSkin();
1204 $templates = $this->mArticle
->getUsedTemplates();
1205 if ( count( $templates ) > 0 ) {
1206 # Do a batch existence check
1207 $batch = new LinkBatch
;
1208 foreach( $templates as $title ) {
1209 $batch->addObj( $title );
1213 # Construct the HTML
1214 $outText = '<br />'. wfMsgExt( 'templatesused', array( 'parseinline' ) ) . '<ul>';
1215 foreach ( $templates as $titleObj ) {
1216 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
1218 $outText .= '</ul>';
1220 wfProfileOut( $fname );
1225 * Live Preview lets us fetch rendered preview page content and
1226 * add it to the page without refreshing the whole page.
1227 * If not supported by the browser it will fall through to the normal form
1228 * submission method.
1230 * This function outputs a script tag to support live preview, and
1231 * returns an onclick handler which should be added to the attributes
1232 * of the preview button
1234 function doLivePreviewScript() {
1235 global $wgStylePath, $wgJsMimeType, $wgOut, $wgTitle;
1236 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1237 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
1238 '"></script>' . "\n" );
1239 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1240 return "return !livePreview(" .
1241 "getElementById('wikiPreview')," .
1242 "editform.wpTextbox1.value," .
1243 '"' . $liveAction . '"' . ")";
1246 function getLastDelete() {
1247 $dbr =& wfGetDB( DB_SLAVE
);
1248 $fname = 'EditPage::getLastDelete';
1249 $res = $dbr->select(
1250 array( 'logging', 'user' ),
1260 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1261 'log_title' => $this->mTitle
->getDBkey(),
1262 'log_type' => 'delete',
1263 'log_action' => 'delete',
1264 'user_id=log_user' ),
1266 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1268 if($dbr->numRows($res) == 1) {
1269 while ( $x = $dbr->fetchObject ( $res ) )
1271 $dbr->freeResult ( $res ) ;
1281 function getPreviewText() {
1282 global $wgOut, $wgUser, $wgTitle, $wgParser;
1284 $fname = 'EditPage::getPreviewText';
1285 wfProfileIn( $fname );
1287 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1288 $msg = 'session_fail_preview';
1290 $msg = 'previewnote';
1292 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1293 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1294 if ( $this->isConflict
) {
1295 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1298 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1299 $parserOptions->setEditSection( false );
1302 if( $wgRawHtml && !$this->mTokenOk
) {
1303 // Could be an offsite preview attempt. This is very unsafe if
1304 // HTML is enabled, as it could be an attack.
1305 return $wgOut->parse( "<div class='previewnote'>" .
1306 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1309 # don't parse user css/js, show message about preview
1310 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1312 if ( $this->isCssJsSubpage
) {
1313 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1314 $previewtext = wfMsg('usercsspreview');
1315 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1316 $previewtext = wfMsg('userjspreview');
1318 $parserOptions->setTidy(true);
1319 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1320 $wgOut->addHTML( $parserOutput->mText
);
1321 wfProfileOut( $fname );
1322 return $previewhead;
1324 # if user want to see preview when he edit an article
1325 if( $wgUser->getOption('previewonfirst') and ($this->textbox1
== '')) {
1326 $this->textbox1
= $this->mArticle
->getContent();
1329 $toparse = $this->textbox1
;
1331 # If we're adding a comment, we need to show the
1332 # summary as the headline
1333 if($this->section
=="new" && $this->summary
!="") {
1334 $toparse="== {$this->summary} ==\n\n".$toparse;
1337 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1338 $parserOptions->setTidy(true);
1339 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1340 $wgTitle, $parserOptions );
1342 $previewHTML = $parserOutput->getText();
1343 $wgOut->addParserOutputNoText( $parserOutput );
1345 wfProfileOut( $fname );
1346 return $previewhead . $previewHTML;
1351 * Call the stock "user is blocked" page
1353 function blockedIPpage() {
1355 $wgOut->blockedPage();
1359 * Produce the stock "please login to edit pages" page
1361 function userNotLoggedInPage() {
1362 global $wgUser, $wgOut;
1363 $skin = $wgUser->getSkin();
1365 $loginTitle = Title
::makeTitle( NS_SPECIAL
, 'Userlogin' );
1366 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle
->getPrefixedUrl() );
1368 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1369 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1370 $wgOut->setArticleRelated( false );
1372 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1373 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1377 * Creates a basic error page which informs the user that
1378 * they have to validate their email address before being
1381 function userNotConfirmedPage() {
1384 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1385 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1386 $wgOut->setArticleRelated( false );
1388 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1389 $wgOut->returnToMain( false );
1393 * Produce the stock "your edit contains spam" page
1395 * @param $match Text which triggered one or more filters
1397 function spamPage( $match = false ) {
1400 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1401 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1402 $wgOut->setArticleRelated( false );
1404 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1406 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1408 $wgOut->returnToMain( false );
1415 function mergeChangesInto( &$editText ){
1416 $fname = 'EditPage::mergeChangesInto';
1417 wfProfileIn( $fname );
1419 $db =& wfGetDB( DB_MASTER
);
1421 // This is the revision the editor started from
1422 $baseRevision = Revision
::loadFromTimestamp(
1423 $db, $this->mArticle
->mTitle
, $this->edittime
);
1424 if( is_null( $baseRevision ) ) {
1425 wfProfileOut( $fname );
1428 $baseText = $baseRevision->getText();
1430 // The current state, we want to merge updates into it
1431 $currentRevision = Revision
::loadFromTitle(
1432 $db, $this->mArticle
->mTitle
);
1433 if( is_null( $currentRevision ) ) {
1434 wfProfileOut( $fname );
1437 $currentText = $currentRevision->getText();
1439 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1440 $editText = $result;
1441 wfProfileOut( $fname );
1444 wfProfileOut( $fname );
1450 * Check if the browser is on a blacklist of user-agents known to
1451 * mangle UTF-8 data on form submission. Returns true if Unicode
1452 * should make it through, false if it's known to be a problem.
1456 function checkUnicodeCompliantBrowser() {
1457 global $wgBrowserBlackList;
1458 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1459 // No User-Agent header sent? Trust it by default...
1462 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1463 foreach ( $wgBrowserBlackList as $browser ) {
1464 if ( preg_match($browser, $currentbrowser) ) {
1472 * Format an anchor fragment as it would appear for a given section name
1473 * @param string $text
1477 function sectionAnchor( $text ) {
1478 $headline = Sanitizer
::decodeCharReferences( $text );
1480 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1481 $headline = trim( $headline );
1482 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1483 $replacearray = array(
1488 array_keys( $replacearray ),
1489 array_values( $replacearray ),
1494 * Shows a bulletin board style toolbar for common editing functions.
1495 * It can be disabled in the user preferences.
1496 * The necessary JavaScript code can be found in style/wikibits.js.
1498 function getEditToolbar() {
1499 global $wgStylePath, $wgContLang, $wgJsMimeType;
1502 * toolarray an array of arrays which each include the filename of
1503 * the button image (without path), the opening tag, the closing tag,
1504 * and optionally a sample text that is inserted between the two when no
1505 * selection is highlighted.
1506 * The tip text is shown when the user moves the mouse over the button.
1508 * Already here are accesskeys (key), which are not used yet until someone
1509 * can figure out a way to make them work in IE. However, we should make
1510 * sure these keys are not defined on the edit page.
1513 array( 'image'=>'button_bold.png',
1515 'close' => "\'\'\'",
1516 'sample'=> wfMsg('bold_sample'),
1517 'tip' => wfMsg('bold_tip'),
1520 array( 'image'=>'button_italic.png',
1523 'sample'=> wfMsg('italic_sample'),
1524 'tip' => wfMsg('italic_tip'),
1527 array( 'image'=>'button_link.png',
1530 'sample'=> wfMsg('link_sample'),
1531 'tip' => wfMsg('link_tip'),
1534 array( 'image'=>'button_extlink.png',
1537 'sample'=> wfMsg('extlink_sample'),
1538 'tip' => wfMsg('extlink_tip'),
1541 array( 'image'=>'button_headline.png',
1543 'close' => " ==\\n",
1544 'sample'=> wfMsg('headline_sample'),
1545 'tip' => wfMsg('headline_tip'),
1548 array( 'image'=>'button_image.png',
1549 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).":",
1551 'sample'=> wfMsg('image_sample'),
1552 'tip' => wfMsg('image_tip'),
1555 array( 'image' =>'button_media.png',
1556 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1558 'sample'=> wfMsg('media_sample'),
1559 'tip' => wfMsg('media_tip'),
1562 array( 'image' =>'button_math.png',
1564 'close' => "<\\/math>",
1565 'sample'=> wfMsg('math_sample'),
1566 'tip' => wfMsg('math_tip'),
1569 array( 'image' =>'button_nowiki.png',
1570 'open' => "<nowiki>",
1571 'close' => "<\\/nowiki>",
1572 'sample'=> wfMsg('nowiki_sample'),
1573 'tip' => wfMsg('nowiki_tip'),
1576 array( 'image' =>'button_sig.png',
1580 'tip' => wfMsg('sig_tip'),
1583 array( 'image' =>'button_hr.png',
1584 'open' => "\\n----\\n",
1587 'tip' => wfMsg('hr_tip'),
1591 $toolbar = "<div id='toolbar'>\n";
1592 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1594 foreach($toolarray as $tool) {
1596 $image=$wgStylePath.'/common/images/'.$tool['image'];
1597 $open=$tool['open'];
1598 $close=$tool['close'];
1599 $sample = wfEscapeJsString( $tool['sample'] );
1601 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1602 // Older browsers show a "speedtip" type message only for ALT.
1603 // Ideally these should be different, realistically they
1604 // probably don't need to be.
1605 $tip = wfEscapeJsString( $tool['tip'] );
1607 #$key = $tool["key"];
1609 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1612 $toolbar.="/*]]>*/\n</script>";
1613 $toolbar.="\n</div>";
1618 * Output preview text only. This can be sucked into the edit page
1619 * via JavaScript, and saves the server time rendering the skin as
1620 * well as theoretically being more robust on the client (doesn't
1621 * disturb the edit box's undo history, won't eat your text on
1624 * @todo This doesn't include category or interlanguage links.
1625 * Would need to enhance it a bit, maybe wrap them in XML
1626 * or something... that might also require more skin
1627 * initialization, so check whether that's a problem.
1629 function livePreview() {
1632 header( 'Content-type: text/xml' );
1633 header( 'Cache-control: no-cache' );
1635 echo $this->getPreviewText( );
1636 /* To not shake screen up and down between preview and live-preview */
1637 echo "<br style=\"clear:both;\" />\n";
1642 * Get a diff between the current contents of the edit box and the
1643 * version of the page we're editing from.
1645 * If this is a section edit, we'll replace the section as for final
1646 * save and then make a comparison.
1648 * @return string HTML
1650 function getDiff() {
1651 require_once( 'DifferenceEngine.php' );
1652 $oldtext = $this->mArticle
->fetchContent();
1653 $newtext = $this->mArticle
->replaceSection(
1654 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1655 $newtext = $this->mArticle
->preSaveTransform( $newtext );
1656 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1657 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1658 if ( $oldtext !== false ||
$newtext != '' ) {
1659 $de = new DifferenceEngine( $this->mTitle
);
1660 $de->setText( $oldtext, $newtext );
1661 $difftext = $de->getDiff( $oldtitle, $newtitle );
1666 return '<div id="wikiDiff">' . $difftext . '</div>';
1670 * Filter an input field through a Unicode de-armoring process if it
1671 * came from an old browser with known broken Unicode editing issues.
1673 * @param WebRequest $request
1674 * @param string $field
1678 function safeUnicodeInput( $request, $field ) {
1679 $text = rtrim( $request->getText( $field ) );
1680 return $request->getBool( 'safemode' )
1681 ?
$this->unmakesafe( $text )
1686 * Filter an output field through a Unicode armoring process if it is
1687 * going to an old browser with known broken Unicode editing issues.
1689 * @param string $text
1693 function safeUnicodeOutput( $text ) {
1695 $codedText = $wgContLang->recodeForEdit( $text );
1696 return $this->checkUnicodeCompliantBrowser()
1698 : $this->makesafe( $codedText );
1702 * A number of web browsers are known to corrupt non-ASCII characters
1703 * in a UTF-8 text editing environment. To protect against this,
1704 * detected browsers will be served an armored version of the text,
1705 * with non-ASCII chars converted to numeric HTML character references.
1707 * Preexisting such character references will have a 0 added to them
1708 * to ensure that round-trips do not alter the original data.
1710 * @param string $invalue
1714 function makesafe( $invalue ) {
1715 // Armor existing references for reversability.
1716 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1721 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1722 $bytevalue = ord( $invalue{$i} );
1723 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1724 $result .= chr( $bytevalue );
1726 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1727 $working = $working << 6;
1728 $working +
= ($bytevalue & 0x3F);
1730 if( $bytesleft <= 0 ) {
1731 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1733 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1734 $working = $bytevalue & 0x1F;
1736 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1737 $working = $bytevalue & 0x0F;
1739 } else { //1111 0xxx
1740 $working = $bytevalue & 0x07;
1748 * Reverse the previously applied transliteration of non-ASCII characters
1749 * back to UTF-8. Used to protect data from corruption by broken web browsers
1750 * as listed in $wgBrowserBlackList.
1752 * @param string $invalue
1756 function unmakesafe( $invalue ) {
1758 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1759 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
1763 $hexstring .= $invalue{$i};
1765 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1767 // Do some sanity checks. These aren't needed for reversability,
1768 // but should help keep the breakage down if the editor
1769 // breaks one of the entities whilst editing.
1770 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1771 $codepoint = hexdec($hexstring);
1772 $result .= codepointToUtf8( $codepoint );
1774 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1777 $result .= substr( $invalue, $i, 1 );
1780 // reverse the transform that we made for reversability reasons.
1781 return strtr( $result, array( "�" => "&#x" ) );
1784 function noCreatePermission() {
1786 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1787 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );