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