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