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