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