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