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