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