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