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