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