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