* (bug 6484) Don't do message transformations when preloading messages for editing
[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 $this->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->blockedPage();
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 if( wfReadOnly() ) {
818 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
819 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
820 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
821 } else {
822 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
823 # Check the skin exists
824 if( $this->isValidCssJsSubpage ) {
825 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
826 } else {
827 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
828 }
829 }
830 }
831
832 if( $this->mTitle->isProtected( 'edit' ) ) {
833 # Is the protection due to the namespace, e.g. interface text?
834 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
835 # Yes; remind the user
836 $notice = wfMsg( 'editinginterface' );
837 } elseif( $this->mTitle->isSemiProtected() ) {
838 # No; semi protected
839 $notice = wfMsg( 'semiprotectedpagewarning' );
840 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' ) {
841 $notice = '';
842 }
843 } else {
844 # No; regular protection
845 $notice = wfMsg( 'protectedpagewarning' );
846 }
847 $wgOut->addWikiText( $notice );
848 }
849
850 if ( $this->kblength === false ) {
851 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
852 }
853 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
854 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
855 } elseif( $this->kblength > 29 ) {
856 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
857 }
858
859 $rows = $wgUser->getIntOption( 'rows' );
860 $cols = $wgUser->getIntOption( 'cols' );
861
862 $ew = $wgUser->getOption( 'editwidth' );
863 if ( $ew ) $ew = " style=\"width:100%\"";
864 else $ew = '';
865
866 $q = 'action=submit';
867 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
868 $action = $this->mTitle->escapeLocalURL( $q );
869
870 $summary = wfMsg('summary');
871 $subject = wfMsg('subject');
872 $minor = wfMsgExt('minoredit', array('parseinline'));
873 $watchthis = wfMsgExt('watchthis', array('parseinline'));
874
875 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
876 wfMsgExt('cancel', array('parseinline')) );
877 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
878 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
879 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
880 htmlspecialchars( wfMsg( 'newwindow' ) );
881
882 global $wgRightsText;
883 $copywarn = "<div id=\"editpage-copywarn\">\n" .
884 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
885 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
886 $wgRightsText ) . "\n</div>";
887
888 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
889 # prepare toolbar for edit buttons
890 $toolbar = $this->getEditToolbar();
891 } else {
892 $toolbar = '';
893 }
894
895 // activate checkboxes if user wants them to be always active
896 if( !$this->preview && !$this->diff ) {
897 # Sort out the "watch" checkbox
898 if( $wgUser->getOption( 'watchdefault' ) ) {
899 # Watch all edits
900 $this->watchthis = true;
901 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
902 # Watch creations
903 $this->watchthis = true;
904 } elseif( $this->mTitle->userIsWatching() ) {
905 # Already watched
906 $this->watchthis = true;
907 }
908
909 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
910 }
911
912 $minoredithtml = '';
913
914 if ( $wgUser->isAllowed('minoredit') ) {
915 $minoredithtml =
916 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
917 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />\n".
918 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>\n";
919 }
920
921 $watchhtml = '';
922
923 if ( $wgUser->isLoggedIn() ) {
924 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
925 ($this->watchthis?" checked='checked'":"").
926 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />\n".
927 "<label for='wpWatchthis' title=\"" .
928 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>\n";
929 }
930
931 $checkboxhtml = $minoredithtml . $watchhtml;
932
933 if ( $wgUser->getOption( 'previewontop' ) ) {
934
935 if ( 'preview' == $this->formtype ) {
936 $this->showPreview();
937 } else {
938 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
939 }
940
941 if ( 'diff' == $this->formtype ) {
942 $wgOut->addHTML( $this->getDiff() );
943 }
944 }
945
946
947 # if this is a comment, show a subject line at the top, which is also the edit summary.
948 # Otherwise, show a summary field at the bottom
949 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
950 if( $this->section == 'new' ) {
951 $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 />";
952 $editsummary = '';
953 } else {
954 $commentsubject = '';
955 $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 />";
956 }
957
958 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
959 if( !$this->preview && !$this->diff ) {
960 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
961 }
962 $templates = $this->formatTemplates();
963
964 global $wgUseMetadataEdit ;
965 if ( $wgUseMetadataEdit ) {
966 $metadata = $this->mMetaData ;
967 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
968 $top = wfMsgWikiHtml( 'metadata_help' );
969 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
970 }
971 else $metadata = "" ;
972
973 $hidden = '';
974 $recreate = '';
975 if ($this->deletedSinceEdit) {
976 if ( 'save' != $this->formtype ) {
977 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
978 } else {
979 // Hide the toolbar and edit area, use can click preview to get it back
980 // Add an confirmation checkbox and explanation.
981 $toolbar = '';
982 $hidden = 'type="hidden" style="display:none;"';
983 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
984 $recreate .=
985 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
986 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
987 }
988 }
989
990 $temp = array(
991 'id' => 'wpSave',
992 'name' => 'wpSave',
993 'type' => 'submit',
994 'tabindex' => '5',
995 'value' => wfMsg('savearticle'),
996 'accesskey' => wfMsg('accesskey-save'),
997 'title' => wfMsg('tooltip-save'),
998 );
999 $buttons['save'] = wfElement('input', $temp, '');
1000 $temp = array(
1001 'id' => 'wpDiff',
1002 'name' => 'wpDiff',
1003 'type' => 'submit',
1004 'tabindex' => '7',
1005 'value' => wfMsg('showdiff'),
1006 'accesskey' => wfMsg('accesskey-diff'),
1007 'title' => wfMsg('tooltip-diff'),
1008 );
1009 $buttons['diff'] = wfElement('input', $temp, '');
1010
1011 global $wgLivePreview;
1012 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1013 $temp = array(
1014 'id' => 'wpPreview',
1015 'name' => 'wpPreview',
1016 'type' => 'submit',
1017 'tabindex' => '6',
1018 'value' => wfMsg('showpreview'),
1019 'accesskey' => '',
1020 'title' => wfMsg('tooltip-preview'),
1021 'style' => 'display: none;',
1022 );
1023 $buttons['preview'] = wfElement('input', $temp, '');
1024 $temp = array(
1025 'id' => 'wpLivePreview',
1026 'name' => 'wpLivePreview',
1027 'type' => 'submit',
1028 'tabindex' => '6',
1029 'value' => wfMsg('showlivepreview'),
1030 'accesskey' => wfMsg('accesskey-preview'),
1031 'title' => '',
1032 'onclick' => $this->doLivePreviewScript(),
1033 );
1034 $buttons['live'] = wfElement('input', $temp, '');
1035 } else {
1036 $temp = array(
1037 'id' => 'wpPreview',
1038 'name' => 'wpPreview',
1039 'type' => 'submit',
1040 'tabindex' => '6',
1041 'value' => wfMsg('showpreview'),
1042 'accesskey' => wfMsg('accesskey-preview'),
1043 'title' => wfMsg('tooltip-preview'),
1044 );
1045 $buttons['preview'] = wfElement('input', $temp, '');
1046 $buttons['live'] = '';
1047 }
1048
1049 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1050 ? ""
1051 : "<input type='hidden' name=\"safemode\" value='1' />\n";
1052
1053 $wgOut->addHTML( <<<END
1054 {$toolbar}
1055 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1056 END
1057 );
1058
1059 if( is_callable( $formCallback ) ) {
1060 call_user_func_array( $formCallback, array( &$wgOut ) );
1061 }
1062
1063 // Put these up at the top to ensure they aren't lost on early form submission
1064 $wgOut->addHTML( "
1065 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1066 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1067 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1068 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1069
1070 $wgOut->addHTML( <<<END
1071 $recreate
1072 {$commentsubject}
1073 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1074 cols='{$cols}'{$ew} $hidden>
1075 END
1076 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1077 "
1078 </textarea>
1079 " );
1080
1081 $wgOut->addWikiText( $copywarn );
1082 $wgOut->addHTML( "
1083 {$metadata}
1084 {$editsummary}
1085 {$checkboxhtml}
1086 {$safemodehtml}
1087 ");
1088
1089 $wgOut->addHTML(
1090 "<div class='editButtons'>
1091 {$buttons['save']}
1092 {$buttons['preview']}
1093 {$buttons['live']}
1094 {$buttons['diff']}
1095 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1096 </div><!-- editButtons -->
1097 </div><!-- editOptions -->");
1098
1099 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1100
1101 $wgOut->addHTML( "
1102 <div class='templatesUsed'>
1103 {$templates}
1104 </div>
1105 " );
1106
1107 if ( $wgUser->isLoggedIn() ) {
1108 /**
1109 * To make it harder for someone to slip a user a page
1110 * which submits an edit form to the wiki without their
1111 * knowledge, a random token is associated with the login
1112 * session. If it's not passed back with the submission,
1113 * we won't save the page, or render user JavaScript and
1114 * CSS previews.
1115 */
1116 $token = htmlspecialchars( $wgUser->editToken() );
1117 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1118 }
1119
1120 # If a blank edit summary was previously provided, and the appropriate
1121 # user preference is active, pass a hidden tag here. This will stop the
1122 # user being bounced back more than once in the event that a summary
1123 # is not required.
1124 if( $this->missingSummary ) {
1125 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1126 }
1127
1128 # For a bit more sophisticated detection of blank summaries, hash the
1129 # automatic one and pass that in a hidden field.
1130 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1131 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1132
1133 if ( $this->isConflict ) {
1134 require_once( "DifferenceEngine.php" );
1135 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1136
1137 $de = new DifferenceEngine( $this->mTitle );
1138 $de->setText( $this->textbox2, $this->textbox1 );
1139 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1140
1141 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1142 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1143 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1144 }
1145 $wgOut->addHTML( "</form>\n" );
1146 if ( !$wgUser->getOption( 'previewontop' ) ) {
1147
1148 if ( $this->formtype == 'preview') {
1149 $this->showPreview();
1150 } else {
1151 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1152 }
1153
1154 if ( $this->formtype == 'diff') {
1155 $wgOut->addHTML( $this->getDiff() );
1156 }
1157
1158 }
1159
1160 wfProfileOut( $fname );
1161 }
1162
1163 /**
1164 * Append preview output to $wgOut.
1165 * Includes category rendering if this is a category page.
1166 * @private
1167 */
1168 function showPreview() {
1169 global $wgOut;
1170 $wgOut->addHTML( '<div id="wikiPreview">' );
1171 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1172 $this->mArticle->openShowCategory();
1173 }
1174 $previewOutput = $this->getPreviewText();
1175 $wgOut->addHTML( $previewOutput );
1176 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1177 $this->mArticle->closeShowCategory();
1178 }
1179 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
1180 $wgOut->addHTML( '</div>' );
1181 }
1182
1183 /**
1184 * Prepare a list of templates used by this page. Returns HTML.
1185 */
1186 function formatTemplates() {
1187 global $wgUser;
1188
1189 $fname = 'EditPage::formatTemplates';
1190 wfProfileIn( $fname );
1191
1192 $sk =& $wgUser->getSkin();
1193
1194 $outText = '';
1195 $templates = $this->mArticle->getUsedTemplates();
1196 if ( count( $templates ) > 0 ) {
1197 # Do a batch existence check
1198 $batch = new LinkBatch;
1199 foreach( $templates as $title ) {
1200 $batch->addObj( $title );
1201 }
1202 $batch->execute();
1203
1204 # Construct the HTML
1205 $outText = '<br />'. wfMsgExt( 'templatesused', array( 'parseinline' ) ) . '<ul>';
1206 foreach ( $templates as $titleObj ) {
1207 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
1208 }
1209 $outText .= '</ul>';
1210 }
1211 wfProfileOut( $fname );
1212 return $outText;
1213 }
1214
1215 /**
1216 * Live Preview lets us fetch rendered preview page content and
1217 * add it to the page without refreshing the whole page.
1218 * If not supported by the browser it will fall through to the normal form
1219 * submission method.
1220 *
1221 * This function outputs a script tag to support live preview, and
1222 * returns an onclick handler which should be added to the attributes
1223 * of the preview button
1224 */
1225 function doLivePreviewScript() {
1226 global $wgStylePath, $wgJsMimeType, $wgOut, $wgTitle;
1227 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1228 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
1229 '"></script>' . "\n" );
1230 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1231 return "return !livePreview(" .
1232 "getElementById('wikiPreview')," .
1233 "editform.wpTextbox1.value," .
1234 '"' . $liveAction . '"' . ")";
1235 }
1236
1237 function getLastDelete() {
1238 $dbr =& wfGetDB( DB_SLAVE );
1239 $fname = 'EditPage::getLastDelete';
1240 $res = $dbr->select(
1241 array( 'logging', 'user' ),
1242 array( 'log_type',
1243 'log_action',
1244 'log_timestamp',
1245 'log_user',
1246 'log_namespace',
1247 'log_title',
1248 'log_comment',
1249 'log_params',
1250 'user_name', ),
1251 array( 'log_namespace' => $this->mTitle->getNamespace(),
1252 'log_title' => $this->mTitle->getDBkey(),
1253 'log_type' => 'delete',
1254 'log_action' => 'delete',
1255 'user_id=log_user' ),
1256 $fname,
1257 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1258
1259 if($dbr->numRows($res) == 1) {
1260 while ( $x = $dbr->fetchObject ( $res ) )
1261 $data = $x;
1262 $dbr->freeResult ( $res ) ;
1263 } else {
1264 $data = null;
1265 }
1266 return $data;
1267 }
1268
1269 /**
1270 * @todo document
1271 */
1272 function getPreviewText() {
1273 global $wgOut, $wgUser, $wgTitle, $wgParser;
1274
1275 $fname = 'EditPage::getPreviewText';
1276 wfProfileIn( $fname );
1277
1278 if ( $this->mTriedSave && !$this->mTokenOk ) {
1279 $msg = 'session_fail_preview';
1280 } else {
1281 $msg = 'previewnote';
1282 }
1283 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1284 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1285 if ( $this->isConflict ) {
1286 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1287 }
1288
1289 $parserOptions = ParserOptions::newFromUser( $wgUser );
1290 $parserOptions->setEditSection( false );
1291
1292 global $wgRawHtml;
1293 if( $wgRawHtml && !$this->mTokenOk ) {
1294 // Could be an offsite preview attempt. This is very unsafe if
1295 // HTML is enabled, as it could be an attack.
1296 return $wgOut->parse( "<div class='previewnote'>" .
1297 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1298 }
1299
1300 # don't parse user css/js, show message about preview
1301 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1302
1303 if ( $this->isCssJsSubpage ) {
1304 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1305 $previewtext = wfMsg('usercsspreview');
1306 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1307 $previewtext = wfMsg('userjspreview');
1308 }
1309 $parserOptions->setTidy(true);
1310 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1311 $wgOut->addHTML( $parserOutput->mText );
1312 wfProfileOut( $fname );
1313 return $previewhead;
1314 } else {
1315 # if user want to see preview when he edit an article
1316 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
1317 $this->textbox1 = $this->mArticle->getContent();
1318 }
1319
1320 $toparse = $this->textbox1;
1321
1322 # If we're adding a comment, we need to show the
1323 # summary as the headline
1324 if($this->section=="new" && $this->summary!="") {
1325 $toparse="== {$this->summary} ==\n\n".$toparse;
1326 }
1327
1328 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1329 $parserOptions->setTidy(true);
1330 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1331 $wgTitle, $parserOptions );
1332
1333 $previewHTML = $parserOutput->getText();
1334 $wgOut->addParserOutputNoText( $parserOutput );
1335
1336 wfProfileOut( $fname );
1337 return $previewhead . $previewHTML;
1338 }
1339 }
1340
1341 /**
1342 * Call the stock "user is blocked" page
1343 */
1344 function blockedPage() {
1345 global $wgOut, $wgUser;
1346 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1347
1348 # If the user made changes, preserve them when showing the markup
1349 # (This happens when a user is blocked during edit, for instance)
1350 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1351 $source = $first ? $this->mArticle->getContent() : $this->textbox1;
1352
1353 # Spit out the source or the user's modified version
1354 $rows = $wgUser->getOption( 'rows' );
1355 $cols = $wgUser->getOption( 'cols' );
1356 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1357 $wgOut->addHtml( '<hr />' );
1358 $wgOut->addWikiText( wfMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() ) );
1359 $wgOut->addHtml( wfElement( 'textarea', $attribs, $source ) );
1360 }
1361
1362 /**
1363 * Produce the stock "please login to edit pages" page
1364 */
1365 function userNotLoggedInPage() {
1366 global $wgUser, $wgOut;
1367 $skin = $wgUser->getSkin();
1368
1369 $loginTitle = Title::makeTitle( NS_SPECIAL, 'Userlogin' );
1370 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle->getPrefixedUrl() );
1371
1372 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1373 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1374 $wgOut->setArticleRelated( false );
1375
1376 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1377 $wgOut->returnToMain( false, $this->mTitle->getPrefixedUrl() );
1378 }
1379
1380 /**
1381 * Creates a basic error page which informs the user that
1382 * they have to validate their email address before being
1383 * allowed to edit.
1384 */
1385 function userNotConfirmedPage() {
1386 global $wgOut;
1387
1388 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1389 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1390 $wgOut->setArticleRelated( false );
1391
1392 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1393 $wgOut->returnToMain( false );
1394 }
1395
1396 /**
1397 * Produce the stock "your edit contains spam" page
1398 *
1399 * @param $match Text which triggered one or more filters
1400 */
1401 function spamPage( $match = false ) {
1402 global $wgOut;
1403
1404 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1405 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1406 $wgOut->setArticleRelated( false );
1407
1408 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1409 if ( $match )
1410 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1411
1412 $wgOut->returnToMain( false );
1413 }
1414
1415 /**
1416 * @private
1417 * @todo document
1418 */
1419 function mergeChangesInto( &$editText ){
1420 $fname = 'EditPage::mergeChangesInto';
1421 wfProfileIn( $fname );
1422
1423 $db =& wfGetDB( DB_MASTER );
1424
1425 // This is the revision the editor started from
1426 $baseRevision = Revision::loadFromTimestamp(
1427 $db, $this->mArticle->mTitle, $this->edittime );
1428 if( is_null( $baseRevision ) ) {
1429 wfProfileOut( $fname );
1430 return false;
1431 }
1432 $baseText = $baseRevision->getText();
1433
1434 // The current state, we want to merge updates into it
1435 $currentRevision = Revision::loadFromTitle(
1436 $db, $this->mArticle->mTitle );
1437 if( is_null( $currentRevision ) ) {
1438 wfProfileOut( $fname );
1439 return false;
1440 }
1441 $currentText = $currentRevision->getText();
1442
1443 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1444 $editText = $result;
1445 wfProfileOut( $fname );
1446 return true;
1447 } else {
1448 wfProfileOut( $fname );
1449 return false;
1450 }
1451 }
1452
1453 /**
1454 * Check if the browser is on a blacklist of user-agents known to
1455 * mangle UTF-8 data on form submission. Returns true if Unicode
1456 * should make it through, false if it's known to be a problem.
1457 * @return bool
1458 * @private
1459 */
1460 function checkUnicodeCompliantBrowser() {
1461 global $wgBrowserBlackList;
1462 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1463 // No User-Agent header sent? Trust it by default...
1464 return true;
1465 }
1466 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1467 foreach ( $wgBrowserBlackList as $browser ) {
1468 if ( preg_match($browser, $currentbrowser) ) {
1469 return false;
1470 }
1471 }
1472 return true;
1473 }
1474
1475 /**
1476 * Format an anchor fragment as it would appear for a given section name
1477 * @param string $text
1478 * @return string
1479 * @private
1480 */
1481 function sectionAnchor( $text ) {
1482 $headline = Sanitizer::decodeCharReferences( $text );
1483 # strip out HTML
1484 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1485 $headline = trim( $headline );
1486 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1487 $replacearray = array(
1488 '%3A' => ':',
1489 '%' => '.'
1490 );
1491 return str_replace(
1492 array_keys( $replacearray ),
1493 array_values( $replacearray ),
1494 $sectionanchor );
1495 }
1496
1497 /**
1498 * Shows a bulletin board style toolbar for common editing functions.
1499 * It can be disabled in the user preferences.
1500 * The necessary JavaScript code can be found in style/wikibits.js.
1501 */
1502 function getEditToolbar() {
1503 global $wgStylePath, $wgContLang, $wgJsMimeType;
1504
1505 /**
1506 * toolarray an array of arrays which each include the filename of
1507 * the button image (without path), the opening tag, the closing tag,
1508 * and optionally a sample text that is inserted between the two when no
1509 * selection is highlighted.
1510 * The tip text is shown when the user moves the mouse over the button.
1511 *
1512 * Already here are accesskeys (key), which are not used yet until someone
1513 * can figure out a way to make them work in IE. However, we should make
1514 * sure these keys are not defined on the edit page.
1515 */
1516 $toolarray=array(
1517 array( 'image'=>'button_bold.png',
1518 'open' => "\'\'\'",
1519 'close' => "\'\'\'",
1520 'sample'=> wfMsg('bold_sample'),
1521 'tip' => wfMsg('bold_tip'),
1522 'key' => 'B'
1523 ),
1524 array( 'image'=>'button_italic.png',
1525 'open' => "\'\'",
1526 'close' => "\'\'",
1527 'sample'=> wfMsg('italic_sample'),
1528 'tip' => wfMsg('italic_tip'),
1529 'key' => 'I'
1530 ),
1531 array( 'image'=>'button_link.png',
1532 'open' => '[[',
1533 'close' => ']]',
1534 'sample'=> wfMsg('link_sample'),
1535 'tip' => wfMsg('link_tip'),
1536 'key' => 'L'
1537 ),
1538 array( 'image'=>'button_extlink.png',
1539 'open' => '[',
1540 'close' => ']',
1541 'sample'=> wfMsg('extlink_sample'),
1542 'tip' => wfMsg('extlink_tip'),
1543 'key' => 'X'
1544 ),
1545 array( 'image'=>'button_headline.png',
1546 'open' => "\\n== ",
1547 'close' => " ==\\n",
1548 'sample'=> wfMsg('headline_sample'),
1549 'tip' => wfMsg('headline_tip'),
1550 'key' => 'H'
1551 ),
1552 array( 'image'=>'button_image.png',
1553 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1554 'close' => ']]',
1555 'sample'=> wfMsg('image_sample'),
1556 'tip' => wfMsg('image_tip'),
1557 'key' => 'D'
1558 ),
1559 array( 'image' =>'button_media.png',
1560 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1561 'close' => ']]',
1562 'sample'=> wfMsg('media_sample'),
1563 'tip' => wfMsg('media_tip'),
1564 'key' => 'M'
1565 ),
1566 array( 'image' =>'button_math.png',
1567 'open' => "<math>",
1568 'close' => "<\\/math>",
1569 'sample'=> wfMsg('math_sample'),
1570 'tip' => wfMsg('math_tip'),
1571 'key' => 'C'
1572 ),
1573 array( 'image' =>'button_nowiki.png',
1574 'open' => "<nowiki>",
1575 'close' => "<\\/nowiki>",
1576 'sample'=> wfMsg('nowiki_sample'),
1577 'tip' => wfMsg('nowiki_tip'),
1578 'key' => 'N'
1579 ),
1580 array( 'image' =>'button_sig.png',
1581 'open' => '--~~~~',
1582 'close' => '',
1583 'sample'=> '',
1584 'tip' => wfMsg('sig_tip'),
1585 'key' => 'Y'
1586 ),
1587 array( 'image' =>'button_hr.png',
1588 'open' => "\\n----\\n",
1589 'close' => '',
1590 'sample'=> '',
1591 'tip' => wfMsg('hr_tip'),
1592 'key' => 'R'
1593 )
1594 );
1595 $toolbar = "<div id='toolbar'>\n";
1596 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1597
1598 foreach($toolarray as $tool) {
1599
1600 $image=$wgStylePath.'/common/images/'.$tool['image'];
1601 $open=$tool['open'];
1602 $close=$tool['close'];
1603 $sample = wfEscapeJsString( $tool['sample'] );
1604
1605 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1606 // Older browsers show a "speedtip" type message only for ALT.
1607 // Ideally these should be different, realistically they
1608 // probably don't need to be.
1609 $tip = wfEscapeJsString( $tool['tip'] );
1610
1611 #$key = $tool["key"];
1612
1613 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1614 }
1615
1616 $toolbar.="/*]]>*/\n</script>";
1617 $toolbar.="\n</div>";
1618 return $toolbar;
1619 }
1620
1621 /**
1622 * Output preview text only. This can be sucked into the edit page
1623 * via JavaScript, and saves the server time rendering the skin as
1624 * well as theoretically being more robust on the client (doesn't
1625 * disturb the edit box's undo history, won't eat your text on
1626 * failure, etc).
1627 *
1628 * @todo This doesn't include category or interlanguage links.
1629 * Would need to enhance it a bit, maybe wrap them in XML
1630 * or something... that might also require more skin
1631 * initialization, so check whether that's a problem.
1632 */
1633 function livePreview() {
1634 global $wgOut;
1635 $wgOut->disable();
1636 header( 'Content-type: text/xml' );
1637 header( 'Cache-control: no-cache' );
1638 # FIXME
1639 echo $this->getPreviewText( );
1640 /* To not shake screen up and down between preview and live-preview */
1641 echo "<br style=\"clear:both;\" />\n";
1642 }
1643
1644
1645 /**
1646 * Get a diff between the current contents of the edit box and the
1647 * version of the page we're editing from.
1648 *
1649 * If this is a section edit, we'll replace the section as for final
1650 * save and then make a comparison.
1651 *
1652 * @return string HTML
1653 */
1654 function getDiff() {
1655 require_once( 'DifferenceEngine.php' );
1656 $oldtext = $this->mArticle->fetchContent();
1657 $newtext = $this->mArticle->replaceSection(
1658 $this->section, $this->textbox1, $this->summary, $this->edittime );
1659 $newtext = $this->mArticle->preSaveTransform( $newtext );
1660 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1661 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1662 if ( $oldtext !== false || $newtext != '' ) {
1663 $de = new DifferenceEngine( $this->mTitle );
1664 $de->setText( $oldtext, $newtext );
1665 $difftext = $de->getDiff( $oldtitle, $newtitle );
1666 } else {
1667 $difftext = '';
1668 }
1669
1670 return '<div id="wikiDiff">' . $difftext . '</div>';
1671 }
1672
1673 /**
1674 * Filter an input field through a Unicode de-armoring process if it
1675 * came from an old browser with known broken Unicode editing issues.
1676 *
1677 * @param WebRequest $request
1678 * @param string $field
1679 * @return string
1680 * @private
1681 */
1682 function safeUnicodeInput( $request, $field ) {
1683 $text = rtrim( $request->getText( $field ) );
1684 return $request->getBool( 'safemode' )
1685 ? $this->unmakesafe( $text )
1686 : $text;
1687 }
1688
1689 /**
1690 * Filter an output field through a Unicode armoring process if it is
1691 * going to an old browser with known broken Unicode editing issues.
1692 *
1693 * @param string $text
1694 * @return string
1695 * @private
1696 */
1697 function safeUnicodeOutput( $text ) {
1698 global $wgContLang;
1699 $codedText = $wgContLang->recodeForEdit( $text );
1700 return $this->checkUnicodeCompliantBrowser()
1701 ? $codedText
1702 : $this->makesafe( $codedText );
1703 }
1704
1705 /**
1706 * A number of web browsers are known to corrupt non-ASCII characters
1707 * in a UTF-8 text editing environment. To protect against this,
1708 * detected browsers will be served an armored version of the text,
1709 * with non-ASCII chars converted to numeric HTML character references.
1710 *
1711 * Preexisting such character references will have a 0 added to them
1712 * to ensure that round-trips do not alter the original data.
1713 *
1714 * @param string $invalue
1715 * @return string
1716 * @private
1717 */
1718 function makesafe( $invalue ) {
1719 // Armor existing references for reversability.
1720 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1721
1722 $bytesleft = 0;
1723 $result = "";
1724 $working = 0;
1725 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1726 $bytevalue = ord( $invalue{$i} );
1727 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1728 $result .= chr( $bytevalue );
1729 $bytesleft = 0;
1730 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1731 $working = $working << 6;
1732 $working += ($bytevalue & 0x3F);
1733 $bytesleft--;
1734 if( $bytesleft <= 0 ) {
1735 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1736 }
1737 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1738 $working = $bytevalue & 0x1F;
1739 $bytesleft = 1;
1740 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1741 $working = $bytevalue & 0x0F;
1742 $bytesleft = 2;
1743 } else { //1111 0xxx
1744 $working = $bytevalue & 0x07;
1745 $bytesleft = 3;
1746 }
1747 }
1748 return $result;
1749 }
1750
1751 /**
1752 * Reverse the previously applied transliteration of non-ASCII characters
1753 * back to UTF-8. Used to protect data from corruption by broken web browsers
1754 * as listed in $wgBrowserBlackList.
1755 *
1756 * @param string $invalue
1757 * @return string
1758 * @private
1759 */
1760 function unmakesafe( $invalue ) {
1761 $result = "";
1762 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1763 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1764 $i += 3;
1765 $hexstring = "";
1766 do {
1767 $hexstring .= $invalue{$i};
1768 $i++;
1769 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1770
1771 // Do some sanity checks. These aren't needed for reversability,
1772 // but should help keep the breakage down if the editor
1773 // breaks one of the entities whilst editing.
1774 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1775 $codepoint = hexdec($hexstring);
1776 $result .= codepointToUtf8( $codepoint );
1777 } else {
1778 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1779 }
1780 } else {
1781 $result .= substr( $invalue, $i, 1 );
1782 }
1783 }
1784 // reverse the transform that we made for reversability reasons.
1785 return strtr( $result, array( "&#x0" => "&#x" ) );
1786 }
1787
1788 function noCreatePermission() {
1789 global $wgOut;
1790 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1791 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
1792 }
1793
1794 }
1795
1796 ?>