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