Fix fatal error in eval.php
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * Contains the EditPage class
4 */
5
6 /**
7 * The edit page/HTML interface (split from Article)
8 * The actual database and text munging is still in Article,
9 * but it should get easier to call those from alternate
10 * interfaces.
11 *
12 * EditPage cares about two distinct titles:
13 * $wgTitle is the page that forms submit to, links point to,
14 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
15 * page in the database that is actually being edited. These are
16 * usually the same, but they are now allowed to be different.
17 */
18 class EditPage {
19 const AS_SUCCESS_UPDATE = 200;
20 const AS_SUCCESS_NEW_ARTICLE = 201;
21 const AS_HOOK_ERROR = 210;
22 const AS_FILTERING = 211;
23 const AS_HOOK_ERROR_EXPECTED = 212;
24 const AS_BLOCKED_PAGE_FOR_USER = 215;
25 const AS_CONTENT_TOO_BIG = 216;
26 const AS_USER_CANNOT_EDIT = 217;
27 const AS_READ_ONLY_PAGE_ANON = 218;
28 const AS_READ_ONLY_PAGE_LOGGED = 219;
29 const AS_READ_ONLY_PAGE = 220;
30 const AS_RATE_LIMITED = 221;
31 const AS_ARTICLE_WAS_DELETED = 222;
32 const AS_NO_CREATE_PERMISSION = 223;
33 const AS_BLANK_ARTICLE = 224;
34 const AS_CONFLICT_DETECTED = 225;
35 const AS_SUMMARY_NEEDED = 226;
36 const AS_TEXTBOX_EMPTY = 228;
37 const AS_MAX_ARTICLE_SIZE_EXCEDED = 229;
38 const AS_OK = 230;
39 const AS_END = 231;
40 const AS_SPAM_ERROR = 232;
41 const AS_IMAGE_REDIRECT_ANON = 233;
42 const AS_IMAGE_REDIRECT_LOGGED = 234;
43
44 var $mArticle;
45 var $mTitle;
46 var $mMetaData = '';
47 var $isConflict = false;
48 var $isCssJsSubpage = false;
49 var $deletedSinceEdit = false;
50 var $formtype;
51 var $firsttime;
52 var $lastDelete;
53 var $mTokenOk = false;
54 var $mTokenOkExceptSuffix = false;
55 var $mTriedSave = false;
56 var $tooBig = false;
57 var $kblength = false;
58 var $missingComment = false;
59 var $missingSummary = false;
60 var $allowBlankSummary = false;
61 var $autoSumm = '';
62 var $hookError = '';
63 var $mPreviewTemplates;
64
65 # Form values
66 var $save = false, $preview = false, $diff = false;
67 var $minoredit = false, $watchthis = false, $recreate = false;
68 var $textbox1 = '', $textbox2 = '', $summary = '';
69 var $edittime = '', $section = '', $starttime = '';
70 var $oldid = 0, $editintro = '', $scrolltop = null;
71
72 # Placeholders for text injection by hooks (must be HTML)
73 # extensions should take care to _append_ to the present value
74 public $editFormPageTop; // Before even the preview
75 public $editFormTextTop;
76 public $editFormTextBeforeContent;
77 public $editFormTextAfterWarn;
78 public $editFormTextAfterTools;
79 public $editFormTextBottom;
80
81 /* $didSave should be set to true whenever an article was succesfully altered. */
82 public $didSave = false;
83
84 public $suppressIntro = false;
85
86 /**
87 * @todo document
88 * @param $article
89 */
90 function EditPage( $article ) {
91 global $wgTitle;
92 $this->mArticle =& $article;
93 $this->mTitle = $article->getTitle();
94
95 # Placeholders for text injection by hooks (empty per default)
96 $this->editFormPageTop =
97 $this->editFormTextTop =
98 $this->editFormTextBeforeContent =
99 $this->editFormTextAfterWarn =
100 $this->editFormTextAfterTools =
101 $this->editFormTextBottom = "";
102 }
103
104 /**
105 * Fetch initial editing page content.
106 * @private
107 */
108 function getContent( $def_text = '' ) {
109 global $wgOut, $wgRequest, $wgParser;
110
111 # Get variables from query string :P
112 $section = $wgRequest->getVal( 'section' );
113 $preload = $wgRequest->getVal( 'preload' );
114 $undoafter = $wgRequest->getVal( 'undoafter' );
115 $undo = $wgRequest->getVal( 'undo' );
116
117 wfProfileIn( __METHOD__ );
118
119 $text = '';
120 if( !$this->mTitle->exists() ) {
121 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
122 # If this is a system message, get the default text.
123 $text = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
124 } else {
125 # If requested, preload some text.
126 $text = $this->getPreloadedText( $preload );
127 }
128 # We used to put MediaWiki:Newarticletext here if
129 # $text was empty at this point.
130 # This is now shown above the edit box instead.
131 } else {
132 // FIXME: may be better to use Revision class directly
133 // But don't mess with it just yet. Article knows how to
134 // fetch the page record from the high-priority server,
135 // which is needed to guarantee we don't pick up lagged
136 // information.
137
138 $text = $this->mArticle->getContent();
139
140 if ($undo > 0 && $undoafter > 0 && $undo < $undoafter) {
141 # If they got undoafter and undo round the wrong way, switch them
142 list( $undo, $undoafter ) = array( $undoafter, $undo );
143 }
144
145 if ( $undo > 0 && $undo > $undoafter ) {
146 # Undoing a specific edit overrides section editing; section-editing
147 # doesn't work with undoing.
148 if ( $undoafter ) {
149 $undorev = Revision::newFromId($undo);
150 $oldrev = Revision::newFromId($undoafter);
151 } else {
152 $undorev = Revision::newFromId($undo);
153 $oldrev = $undorev ? $undorev->getPrevious() : null;
154 }
155
156 #Sanity check, make sure it's the right page.
157 # Otherwise, $text will be left as-is.
158 if ( !is_null($undorev) && !is_null($oldrev) && $undorev->getPage()==$oldrev->getPage() && $undorev->getPage()==$this->mArticle->getID() ) {
159 $undorev_text = $undorev->getText();
160 $oldrev_text = $oldrev->getText();
161 $currev_text = $text;
162
163 #No use doing a merge if it's just a straight revert.
164 if ( $currev_text != $undorev_text ) {
165 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
166 } else {
167 $text = $oldrev_text;
168 $result = true;
169 }
170 } else {
171 // Failed basic sanity checks.
172 // Older revisions may have been removed since the link
173 // was created, or we may simply have got bogus input.
174 $result = false;
175 }
176
177 if( $result ) {
178 # Inform the user of our success and set an automatic edit summary
179 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
180 $firstrev = $oldrev->getNext();
181 # If we just undid one rev, use an autosummary
182 if ( $firstrev->mId == $undo ) {
183 $this->summary = wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
184 }
185 $this->formtype = 'diff';
186 } else {
187 # Warn the user that something went wrong
188 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
189 }
190 } else if( $section != '' ) {
191 if( $section == 'new' ) {
192 $text = $this->getPreloadedText( $preload );
193 } else {
194 $text = $wgParser->getSection( $text, $section, $def_text );
195 }
196 }
197 }
198
199 wfProfileOut( __METHOD__ );
200 return $text;
201 }
202
203 /**
204 * Get the contents of a page from its title and remove includeonly tags
205 *
206 * @param $preload String: the title of the page.
207 * @return string The contents of the page.
208 */
209 private function getPreloadedText($preload) {
210 if ( $preload === '' )
211 return '';
212 else {
213 $preloadTitle = Title::newFromText( $preload );
214 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
215 $rev=Revision::newFromTitle($preloadTitle);
216 if ( is_object( $rev ) ) {
217 $text = $rev->getText();
218 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
219 // its own mini-parser! -ævar
220 $text = preg_replace( '~</?includeonly>~', '', $text );
221 return $text;
222 } else
223 return '';
224 }
225 }
226 }
227
228 /**
229 * This is the function that extracts metadata from the article body on the first view.
230 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
231 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
232 */
233 function extractMetaDataFromArticle () {
234 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
235 $this->mMetaData = '' ;
236 if ( !$wgUseMetadataEdit ) return ;
237 if ( $wgMetadataWhitelist == '' ) return ;
238 $s = '' ;
239 $t = $this->getContent();
240
241 # MISSING : <nowiki> filtering
242
243 # Categories and language links
244 $t = explode ( "\n" , $t ) ;
245 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
246 $cat = $ll = array() ;
247 foreach ( $t AS $key => $x )
248 {
249 $y = trim ( strtolower ( $x ) ) ;
250 while ( substr ( $y , 0 , 2 ) == '[[' )
251 {
252 $y = explode ( ']]' , trim ( $x ) ) ;
253 $first = array_shift ( $y ) ;
254 $first = explode ( ':' , $first ) ;
255 $ns = array_shift ( $first ) ;
256 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
257 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
258 {
259 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
260 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
261 else $ll[] = $add ;
262 $x = implode ( ']]' , $y ) ;
263 $t[$key] = $x ;
264 $y = trim ( strtolower ( $x ) ) ;
265 }
266 }
267 }
268 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
269 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
270 $t = implode ( "\n" , $t ) ;
271
272 # Load whitelist
273 $sat = array () ; # stand-alone-templates; must be lowercase
274 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
275 $wl_article = new Article ( $wl_title ) ;
276 $wl = explode ( "\n" , $wl_article->getContent() ) ;
277 foreach ( $wl AS $x )
278 {
279 $isentry = false ;
280 $x = trim ( $x ) ;
281 while ( substr ( $x , 0 , 1 ) == '*' )
282 {
283 $isentry = true ;
284 $x = trim ( substr ( $x , 1 ) ) ;
285 }
286 if ( $isentry )
287 {
288 $sat[] = strtolower ( $x ) ;
289 }
290
291 }
292
293 # Templates, but only some
294 $t = explode ( '{{' , $t ) ;
295 $tl = array () ;
296 foreach ( $t AS $key => $x )
297 {
298 $y = explode ( '}}' , $x , 2 ) ;
299 if ( count ( $y ) == 2 )
300 {
301 $z = $y[0] ;
302 $z = explode ( '|' , $z ) ;
303 $tn = array_shift ( $z ) ;
304 if ( in_array ( strtolower ( $tn ) , $sat ) )
305 {
306 $tl[] = '{{' . $y[0] . '}}' ;
307 $t[$key] = $y[1] ;
308 $y = explode ( '}}' , $y[1] , 2 ) ;
309 }
310 else $t[$key] = '{{' . $x ;
311 }
312 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
313 else $t[$key] = $x ;
314 }
315 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
316 $t = implode ( '' , $t ) ;
317
318 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
319 $this->mArticle->mContent = $t ;
320 $this->mMetaData = $s ;
321 }
322
323 function submit() {
324 $this->edit();
325 }
326
327 /**
328 * This is the function that gets called for "action=edit". It
329 * sets up various member variables, then passes execution to
330 * another function, usually showEditForm()
331 *
332 * The edit form is self-submitting, so that when things like
333 * preview and edit conflicts occur, we get the same form back
334 * with the extra stuff added. Only when the final submission
335 * is made and all is well do we actually save and redirect to
336 * the newly-edited page.
337 */
338 function edit() {
339 global $wgOut, $wgUser, $wgRequest, $wgTitle;
340
341 if ( !wfRunHooks( 'AlternateEdit', array( &$this ) ) )
342 return;
343
344 wfProfileIn( __METHOD__ );
345 wfDebug( __METHOD__.": enter\n" );
346
347 // this is not an article
348 $wgOut->setArticleFlag(false);
349
350 $this->importFormData( $wgRequest );
351 $this->firsttime = false;
352
353 if( $this->live ) {
354 $this->livePreview();
355 wfProfileOut( __METHOD__ );
356 return;
357 }
358
359 if( wfReadOnly() ) {
360 $wgOut->readOnlyPage( $this->getContent() );
361 wfProfileOut( __METHOD__ );
362 return;
363 }
364
365 $permErrors = $this->mTitle->getUserPermissionsErrors('edit', $wgUser);
366 if( !$this->mTitle->exists() ) {
367 # We can't use array_diff here, because that considers ANY TWO
368 # ARRAYS TO BE EQUAL. Thanks, PHP.
369 $createErrors = $this->mTitle->getUserPermissionsErrors('create', $wgUser);
370 foreach( $createErrors as $error ) {
371 # in_array() actually *does* work as expected.
372 if( !in_array( $error, $permErrors ) ) {
373 $permErrors[] = $error;
374 }
375 }
376 }
377
378 # Ignore some permissions errors.
379 $remove = array();
380 foreach( $permErrors as $error ) {
381 if ($this->preview || $this->diff &&
382 ($error[0] == 'blockedtext' || $error[0] == 'autoblockedtext'))
383 {
384 // Don't worry about blocks when previewing/diffing
385 $remove[] = $error;
386 }
387
388 if ($error[0] == 'readonlytext')
389 {
390 if ($this->edit) {
391 $this->formtype = 'preview';
392 } elseif ($this->save || $this->preview || $this->diff) {
393 $remove[] = $error;
394 }
395 }
396 }
397 $permErrors = array_diff( $permErrors, $remove );
398
399 if ( !empty($permErrors) ) {
400 wfDebug( __METHOD__.": User can't edit\n" );
401 $wgOut->readOnlyPage( $this->getContent(), true, $permErrors );
402 wfProfileOut( __METHOD__ );
403 return;
404 } else {
405 if ( $this->save ) {
406 $this->formtype = 'save';
407 } else if ( $this->preview ) {
408 $this->formtype = 'preview';
409 } else if ( $this->diff ) {
410 $this->formtype = 'diff';
411 } else { # First time through
412 $this->firsttime = true;
413 if( $this->previewOnOpen() ) {
414 $this->formtype = 'preview';
415 } else {
416 $this->extractMetaDataFromArticle () ;
417 $this->formtype = 'initial';
418 }
419 }
420 }
421
422 wfProfileIn( __METHOD__."-business-end" );
423
424 $this->isConflict = false;
425 // css / js subpages of user pages get a special treatment
426 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
427 $this->isValidCssJsSubpage = $this->mTitle->isValidCssJsSubpage();
428
429 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
430 * no matter it's current state
431 */
432 $this->deletedSinceEdit = false;
433 if ( $this->edittime != '' ) {
434 /* Note that we rely on logging table, which hasn't been always there,
435 * but that doesn't matter, because this only applies to brand new
436 * deletes. This is done on every preview and save request. Move it further down
437 * to only perform it on saves
438 */
439 if ( $this->mTitle->isDeleted() ) {
440 $this->lastDelete = $this->getLastDelete();
441 if ( !is_null($this->lastDelete) ) {
442 $deletetime = $this->lastDelete->log_timestamp;
443 if ( ($deletetime - $this->starttime) > 0 ) {
444 $this->deletedSinceEdit = true;
445 }
446 }
447 }
448 }
449
450 # Show applicable editing introductions
451 if( $this->formtype == 'initial' || $this->firsttime )
452 $this->showIntro();
453
454 if( $this->mTitle->isTalkPage() ) {
455 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
456 }
457
458 # Attempt submission here. This will check for edit conflicts,
459 # and redundantly check for locked database, blocked IPs, etc.
460 # that edit() already checked just in case someone tries to sneak
461 # in the back door with a hand-edited submission URL.
462
463 if ( 'save' == $this->formtype ) {
464 if ( !$this->attemptSave() ) {
465 wfProfileOut( __METHOD__."-business-end" );
466 wfProfileOut( __METHOD__ );
467 return;
468 }
469 }
470
471 # First time through: get contents, set time for conflict
472 # checking, etc.
473 if ( 'initial' == $this->formtype || $this->firsttime ) {
474 if ($this->initialiseForm() === false) {
475 $this->noSuchSectionPage();
476 wfProfileOut( __METHOD__."-business-end" );
477 wfProfileOut( __METHOD__ );
478 return;
479 }
480 if( !$this->mTitle->getArticleId() )
481 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
482 }
483
484 $this->showEditForm();
485 wfProfileOut( __METHOD__."-business-end" );
486 wfProfileOut( __METHOD__ );
487 }
488
489 /**
490 * Should we show a preview when the edit form is first shown?
491 *
492 * @return bool
493 */
494 private function previewOnOpen() {
495 global $wgRequest, $wgUser;
496 if( $wgRequest->getVal( 'preview' ) == 'yes' ) {
497 // Explicit override from request
498 return true;
499 } elseif( $wgRequest->getVal( 'preview' ) == 'no' ) {
500 // Explicit override from request
501 return false;
502 } elseif( $this->section == 'new' ) {
503 // Nothing *to* preview for new sections
504 return false;
505 } elseif( ( $wgRequest->getVal( 'preload' ) !== '' || $this->mTitle->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
506 // Standard preference behaviour
507 return true;
508 } elseif( !$this->mTitle->exists() && $this->mTitle->getNamespace() == NS_CATEGORY ) {
509 // Categories are special
510 return true;
511 } else {
512 return false;
513 }
514 }
515
516 /**
517 * @todo document
518 * @param $request
519 */
520 function importFormData( &$request ) {
521 global $wgLang, $wgUser;
522 $fname = 'EditPage::importFormData';
523 wfProfileIn( $fname );
524
525 if( $request->wasPosted() ) {
526 # These fields need to be checked for encoding.
527 # Also remove trailing whitespace, but don't remove _initial_
528 # whitespace from the text boxes. This may be significant formatting.
529 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
530 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
531 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
532 # Truncate for whole multibyte characters. +5 bytes for ellipsis
533 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
534
535 $this->edittime = $request->getVal( 'wpEdittime' );
536 $this->starttime = $request->getVal( 'wpStarttime' );
537
538 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
539
540 if( is_null( $this->edittime ) ) {
541 # If the form is incomplete, force to preview.
542 wfDebug( "$fname: Form data appears to be incomplete\n" );
543 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
544 $this->preview = true;
545 } else {
546 /* Fallback for live preview */
547 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
548 $this->diff = $request->getCheck( 'wpDiff' );
549
550 // Remember whether a save was requested, so we can indicate
551 // if we forced preview due to session failure.
552 $this->mTriedSave = !$this->preview;
553
554 if ( $this->tokenOk( $request ) ) {
555 # Some browsers will not report any submit button
556 # if the user hits enter in the comment box.
557 # The unmarked state will be assumed to be a save,
558 # if the form seems otherwise complete.
559 wfDebug( "$fname: Passed token check.\n" );
560 } else if ( $this->diff ) {
561 # Failed token check, but only requested "Show Changes".
562 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
563 } else {
564 # Page might be a hack attempt posted from
565 # an external site. Preview instead of saving.
566 wfDebug( "$fname: Failed token check; forcing preview\n" );
567 $this->preview = true;
568 }
569 }
570 $this->save = ! ( $this->preview OR $this->diff );
571 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
572 $this->edittime = null;
573 }
574
575 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
576 $this->starttime = null;
577 }
578
579 $this->recreate = $request->getCheck( 'wpRecreate' );
580
581 $this->minoredit = $request->getCheck( 'wpMinoredit' );
582 $this->watchthis = $request->getCheck( 'wpWatchthis' );
583
584 # Don't force edit summaries when a user is editing their own user or talk page
585 if( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) && $this->mTitle->getText() == $wgUser->getName() ) {
586 $this->allowBlankSummary = true;
587 } else {
588 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' );
589 }
590
591 $this->autoSumm = $request->getText( 'wpAutoSummary' );
592 } else {
593 # Not a posted form? Start with nothing.
594 wfDebug( "$fname: Not a posted form.\n" );
595 $this->textbox1 = '';
596 $this->textbox2 = '';
597 $this->mMetaData = '';
598 $this->summary = '';
599 $this->edittime = '';
600 $this->starttime = wfTimestampNow();
601 $this->edit = false;
602 $this->preview = false;
603 $this->save = false;
604 $this->diff = false;
605 $this->minoredit = false;
606 $this->watchthis = false;
607 $this->recreate = false;
608 }
609
610 $this->oldid = $request->getInt( 'oldid' );
611
612 # Section edit can come from either the form or a link
613 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
614
615 $this->live = $request->getCheck( 'live' );
616 $this->editintro = $request->getText( 'editintro' );
617
618 wfProfileOut( $fname );
619 }
620
621 /**
622 * Make sure the form isn't faking a user's credentials.
623 *
624 * @param $request WebRequest
625 * @return bool
626 * @private
627 */
628 function tokenOk( &$request ) {
629 global $wgUser;
630 $token = $request->getVal( 'wpEditToken' );
631 $this->mTokenOk = $wgUser->matchEditToken( $token );
632 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
633 return $this->mTokenOk;
634 }
635
636 /**
637 * Show all applicable editing introductions
638 */
639 private function showIntro() {
640 global $wgOut, $wgUser;
641 if( $this->suppressIntro )
642 return;
643
644 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
645 if( $this->mTitle->getNamespace() == NS_USER || $this->mTitle->getNamespace() == NS_USER_TALK ) {
646 $parts = explode( '/', $this->mTitle->getText(), 2 );
647 $username = $parts[0];
648 $id = User::idFromName( $username );
649 $ip = User::isIP( $username );
650
651 if ( $id == 0 && !$ip ) {
652 $wgOut->addWikiText( '<div class="mw-userpage-userdoesnotexist error">' . wfMsg( 'userpage-userdoesnotexist', $username ) . '</div>' );
653 }
654 }
655
656 if( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
657 if( $wgUser->isLoggedIn() ) {
658 $wgOut->addWikiText( '<div class="mw-newarticletext">' . wfMsg( 'newarticletext' ) . '</div>' );
659 } else {
660 $wgOut->addWikiText( '<div class="mw-newarticletextanon">' . wfMsg( 'newarticletextanon' ) . '</div>' );
661 }
662 $this->showDeletionLog( $wgOut );
663 }
664 }
665
666 /**
667 * Attempt to show a custom editing introduction, if supplied
668 *
669 * @return bool
670 */
671 private function showCustomIntro() {
672 if( $this->editintro ) {
673 $title = Title::newFromText( $this->editintro );
674 if( $title instanceof Title && $title->exists() && $title->userCanRead() ) {
675 global $wgOut;
676 $revision = Revision::newFromTitle( $title );
677 $wgOut->addSecondaryWikiText( $revision->getText() );
678 return true;
679 } else {
680 return false;
681 }
682 } else {
683 return false;
684 }
685 }
686
687 /**
688 * Attempt submission (no UI)
689 * @return one of the constants describing the result
690 */
691 function internalAttemptSave( &$result, $bot = false ) {
692 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut, $wgParser;
693 global $wgMaxArticleSize, $wgTitle;
694
695 $fname = 'EditPage::attemptSave';
696 wfProfileIn( $fname );
697 wfProfileIn( "$fname-checks" );
698
699 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
700 {
701 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
702 return self::AS_HOOK_ERROR;
703 }
704
705 # Check image redirect
706 if ( $wgTitle->getNamespace() == NS_IMAGE &&
707 Title::newFromRedirect( $this->textbox1 ) instanceof Title &&
708 !$wgUser->isAllowed( 'upload' ) ) {
709 if( $wgUser->isAnon() ) {
710 return self::AS_IMAGE_REDIRECT_ANON;
711 } else {
712 return self::AS_IMAGE_REDIRECT_LOGGED;
713 }
714 }
715
716 # Reintegrate metadata
717 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
718 $this->mMetaData = '' ;
719
720 # Check for spam
721 $matches = array();
722 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
723 $result['spam'] = $matches[0];
724 wfProfileOut( "$fname-checks" );
725 wfProfileOut( $fname );
726 return self::AS_SPAM_ERROR;
727 }
728 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
729 # Error messages or other handling should be performed by the filter function
730 wfProfileOut( "$fname-checks" );
731 wfProfileOut( $fname );
732 return self::AS_FILTERING;
733 }
734 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError ) ) ) {
735 # Error messages etc. could be handled within the hook...
736 wfProfileOut( "$fname-checks" );
737 wfProfileOut( $fname );
738 return self::AS_HOOK_ERROR;
739 } elseif( $this->hookError != '' ) {
740 # ...or the hook could be expecting us to produce an error
741 wfProfileOut( "$fname-checks" );
742 wfProfileOut( $fname );
743 return self::AS_HOOK_ERROR_EXPECTED;
744 }
745 if ( $wgUser->isBlockedFrom( $wgTitle, false ) ) {
746 # Check block state against master, thus 'false'.
747 wfProfileOut( "$fname-checks" );
748 wfProfileOut( $fname );
749 return self::AS_BLOCKED_PAGE_FOR_USER;
750 }
751 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
752 if ( $this->kblength > $wgMaxArticleSize ) {
753 // Error will be displayed by showEditForm()
754 $this->tooBig = true;
755 wfProfileOut( "$fname-checks" );
756 wfProfileOut( $fname );
757 return self::AS_CONTENT_TOO_BIG;
758 }
759
760 if ( !$wgUser->isAllowed('edit') ) {
761 if ( $wgUser->isAnon() ) {
762 wfProfileOut( "$fname-checks" );
763 wfProfileOut( $fname );
764 return self::AS_READ_ONLY_PAGE_ANON;
765 }
766 else {
767 wfProfileOut( "$fname-checks" );
768 wfProfileOut( $fname );
769 return self::AS_READ_ONLY_PAGE_LOGGED;
770 }
771 }
772
773 if ( wfReadOnly() ) {
774 wfProfileOut( "$fname-checks" );
775 wfProfileOut( $fname );
776 return self::AS_READ_ONLY_PAGE;
777 }
778 if ( $wgUser->pingLimiter() ) {
779 wfProfileOut( "$fname-checks" );
780 wfProfileOut( $fname );
781 return self::AS_RATE_LIMITED;
782 }
783
784 # If the article has been deleted while editing, don't save it without
785 # confirmation
786 if ( $this->deletedSinceEdit && !$this->recreate ) {
787 wfProfileOut( "$fname-checks" );
788 wfProfileOut( $fname );
789 return self::AS_ARTICLE_WAS_DELETED;
790 }
791
792 wfProfileOut( "$fname-checks" );
793
794 # If article is new, insert it.
795 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
796 if ( 0 == $aid ) {
797
798 // Late check for create permission, just in case *PARANOIA*
799 if ( !$this->mTitle->userCan( 'create' ) ) {
800 wfDebug( "$fname: no create permission\n" );
801 wfProfileOut( $fname );
802 return self::AS_NO_CREATE_PERMISSION;
803 }
804
805 # Don't save a new article if it's blank.
806 if ( '' == $this->textbox1 ) {
807 wfProfileOut( $fname );
808 return self::AS_BLANK_ARTICLE;
809 }
810
811 // Run post-section-merge edit filter
812 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1, &$this->hookError ) ) ) {
813 # Error messages etc. could be handled within the hook...
814 wfProfileOut( $fname );
815 return false;
816 }
817
818 $isComment = ( $this->section == 'new' );
819
820 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
821 $this->minoredit, $this->watchthis, false, $isComment, $bot);
822
823 wfProfileOut( $fname );
824 return self::AS_SUCCESS_NEW_ARTICLE;
825 }
826
827 # Article exists. Check for edit conflict.
828
829 $this->mArticle->clear(); # Force reload of dates, etc.
830 $this->mArticle->forUpdate( true ); # Lock the article
831
832 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
833
834 if( $this->mArticle->getTimestamp() != $this->edittime ) {
835 $this->isConflict = true;
836 if( $this->section == 'new' ) {
837 if( $this->mArticle->getUserText() == $wgUser->getName() &&
838 $this->mArticle->getComment() == $this->summary ) {
839 // Probably a duplicate submission of a new comment.
840 // This can happen when squid resends a request after
841 // a timeout but the first one actually went through.
842 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
843 } else {
844 // New comment; suppress conflict.
845 $this->isConflict = false;
846 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
847 }
848 }
849 }
850 $userid = $wgUser->getID();
851
852 if ( $this->isConflict) {
853 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
854 $this->mArticle->getTimestamp() . "')\n" );
855 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
856 }
857 else {
858 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
859 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
860 }
861 if( is_null( $text ) ) {
862 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
863 $this->isConflict = true;
864 $text = $this->textbox1;
865 }
866
867 # Suppress edit conflict with self, except for section edits where merging is required.
868 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
869 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
870 $this->isConflict = false;
871 } else {
872 # switch from section editing to normal editing in edit conflict
873 if($this->isConflict) {
874 # Attempt merge
875 if( $this->mergeChangesInto( $text ) ){
876 // Successful merge! Maybe we should tell the user the good news?
877 $this->isConflict = false;
878 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
879 } else {
880 $this->section = '';
881 $this->textbox1 = $text;
882 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
883 }
884 }
885 }
886
887 if ( $this->isConflict ) {
888 wfProfileOut( $fname );
889 return self::AS_CONFLICT_DETECTED;
890 }
891
892 $oldtext = $this->mArticle->getContent();
893
894 // Run post-section-merge edit filter
895 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError ) ) ) {
896 # Error messages etc. could be handled within the hook...
897 wfProfileOut( $fname );
898 return false;
899 }
900
901 # Handle the user preference to force summaries here, but not for null edits
902 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary')
903 && 0 != strcmp($oldtext, $text) && !Article::getRedirectAutosummary( $text )) {
904 if( md5( $this->summary ) == $this->autoSumm ) {
905 $this->missingSummary = true;
906 wfProfileOut( $fname );
907 return self::AS_SUMMARY_NEEDED;
908 }
909 }
910
911 #And a similar thing for new sections
912 if( $this->section == 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
913 if (trim($this->summary) == '') {
914 $this->missingSummary = true;
915 wfProfileOut( $fname );
916 return self::AS_SUMMARY_NEEDED;
917 }
918 }
919
920 # All's well
921 wfProfileIn( "$fname-sectionanchor" );
922 $sectionanchor = '';
923 if( $this->section == 'new' ) {
924 if ( $this->textbox1 == '' ) {
925 $this->missingComment = true;
926 return self::AS_TEXTBOX_EMPTY;
927 }
928 if( $this->summary != '' ) {
929 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary );
930 # This is a new section, so create a link to the new section
931 # in the revision summary.
932 $cleanSummary = $wgParser->stripSectionName( $this->summary );
933 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
934 }
935 } elseif( $this->section != '' ) {
936 # Try to get a section anchor from the section source, redirect to edited section if header found
937 # XXX: might be better to integrate this into Article::replaceSection
938 # for duplicate heading checking and maybe parsing
939 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
940 # we can't deal with anchors, includes, html etc in the header for now,
941 # headline would need to be parsed to improve this
942 if($hasmatch and strlen($matches[2]) > 0) {
943 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
944 }
945 }
946 wfProfileOut( "$fname-sectionanchor" );
947
948 // Save errors may fall down to the edit form, but we've now
949 // merged the section into full text. Clear the section field
950 // so that later submission of conflict forms won't try to
951 // replace that into a duplicated mess.
952 $this->textbox1 = $text;
953 $this->section = '';
954
955 // Check for length errors again now that the section is merged in
956 $this->kblength = (int)(strlen( $text ) / 1024);
957 if ( $this->kblength > $wgMaxArticleSize ) {
958 $this->tooBig = true;
959 wfProfileOut( $fname );
960 return self::AS_MAX_ARTICLE_SIZE_EXCEDED;
961 }
962
963 # update the article here
964 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
965 $this->watchthis, $bot, $sectionanchor ) ) {
966 wfProfileOut( $fname );
967 return self::AS_SUCCESS_UPDATE;
968 } else {
969 $this->isConflict = true;
970 }
971 wfProfileOut( $fname );
972 return self::AS_END;
973 }
974
975 /**
976 * Initialise form fields in the object
977 * Called on the first invocation, e.g. when a user clicks an edit link
978 */
979 function initialiseForm() {
980 $this->edittime = $this->mArticle->getTimestamp();
981 $this->summary = '';
982 $this->textbox1 = $this->getContent(false);
983 if ($this->textbox1 === false) return false;
984
985 if ( !$this->mArticle->exists() && $this->mTitle->getNamespace() == NS_MEDIAWIKI )
986 $this->textbox1 = wfMsgWeirdKey( $this->mTitle->getText() );
987 wfProxyCheck();
988 return true;
989 }
990
991 /**
992 * Send the edit form and related headers to $wgOut
993 * @param $formCallback Optional callable that takes an OutputPage
994 * parameter; will be called during form output
995 * near the top, for captchas and the like.
996 */
997 function showEditForm( $formCallback=null ) {
998 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle;
999
1000 $fname = 'EditPage::showEditForm';
1001 wfProfileIn( $fname );
1002
1003 $sk = $wgUser->getSkin();
1004
1005 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
1006
1007 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1008
1009 # Enabled article-related sidebar, toplinks, etc.
1010 $wgOut->setArticleRelated( true );
1011
1012 if ( $this->formtype == 'preview' ) {
1013 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1014 }
1015
1016 if ( $this->isConflict ) {
1017 $s = wfMsg( 'editconflict', $wgTitle->getPrefixedText() );
1018 $wgOut->setPageTitle( $s );
1019 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
1020
1021 $this->textbox2 = $this->textbox1;
1022 $this->textbox1 = $this->getContent();
1023 $this->edittime = $this->mArticle->getTimestamp();
1024 } else {
1025 if( $this->section != '' ) {
1026 if( $this->section == 'new' ) {
1027 $s = wfMsg('editingcomment', $wgTitle->getPrefixedText() );
1028 } else {
1029 $s = wfMsg('editingsection', $wgTitle->getPrefixedText() );
1030 $matches = array();
1031 if( !$this->summary && !$this->preview && !$this->diff ) {
1032 preg_match( "/^(=+)(.+)\\1/mi",
1033 $this->textbox1,
1034 $matches );
1035 if( !empty( $matches[2] ) ) {
1036 global $wgParser;
1037 $this->summary = "/* " .
1038 $wgParser->stripSectionName(trim($matches[2])) .
1039 " */ ";
1040 }
1041 }
1042 }
1043 } else {
1044 $s = wfMsg( 'editing', $wgTitle->getPrefixedText() );
1045 }
1046 $wgOut->setPageTitle( $s );
1047
1048 if ( $this->missingComment ) {
1049 $wgOut->addWikiText( '<div id="mw-missingcommenttext">' . wfMsg( 'missingcommenttext' ) . '</div>' );
1050 }
1051
1052 if( $this->missingSummary && $this->section != 'new' ) {
1053 $wgOut->addWikiText( '<div id="mw-missingsummary">' . wfMsg( 'missingsummary' ) . '</div>' );
1054 }
1055
1056 if( $this->missingSummary && $this->section == 'new' ) {
1057 $wgOut->addWikiText( '<div id="mw-missingcommentheader">' . wfMsg( 'missingcommentheader' ) . '</div>' );
1058 }
1059
1060 if( $this->hookError !== '' ) {
1061 $wgOut->addWikiText( $this->hookError );
1062 }
1063
1064 if ( !$this->checkUnicodeCompliantBrowser() ) {
1065 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
1066 }
1067 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
1068 // Let sysop know that this will make private content public if saved
1069
1070 if( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1071 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
1072 } else if( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1073 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
1074 }
1075
1076 if( !$this->mArticle->mRevision->isCurrent() ) {
1077 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
1078 $wgOut->addWikiText( wfMsg( 'editingold' ) );
1079 }
1080 }
1081 }
1082
1083 if( wfReadOnly() ) {
1084 $wgOut->addHTML( '<div id="mw-read-only-warning">'.wfMsgWikiHTML( 'readonlywarning' ).'</div>' );
1085 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
1086 $wgOut->addHTML( '<div id="mw-anon-edit-warning">'.wfMsgWikiHTML( 'anoneditwarning' ).'</div>' );
1087 } else {
1088 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
1089 # Check the skin exists
1090 if( $this->isValidCssJsSubpage ) {
1091 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
1092 } else {
1093 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() ) );
1094 }
1095 }
1096 }
1097
1098 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1099 # Show a warning if editing an interface message
1100 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
1101 } elseif( $this->mTitle->isProtected( 'edit' ) ) {
1102 # Is the title semi-protected?
1103 if( $this->mTitle->isSemiProtected() ) {
1104 $notice = wfMsg( 'semiprotectedpagewarning' );
1105 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' )
1106 $notice = '';
1107 } else {
1108 # Then it must be protected based on static groups (regular)
1109 $notice = wfMsg( 'protectedpagewarning' );
1110 }
1111 $wgOut->addWikiText( $notice );
1112 }
1113 if ( $this->mTitle->isCascadeProtected() ) {
1114 # Is this page under cascading protection from some source pages?
1115 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1116 if ( count($cascadeSources) > 0 ) {
1117 # Explain, and list the titles responsible
1118 $notice = wfMsgExt( 'cascadeprotectedwarning', array('parsemag'), count($cascadeSources) ) . "\n";
1119 foreach( $cascadeSources as $page ) {
1120 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1121 }
1122 }
1123 $wgOut->addWikiText( $notice );
1124 }
1125 if( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) != array() ){
1126 $wgOut->addWikiText( wfMsg( 'titleprotectedwarning' ) );
1127 }
1128
1129 if ( $this->kblength === false ) {
1130 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
1131 }
1132 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1133 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
1134 } elseif( $this->kblength > 29 ) {
1135 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
1136 }
1137
1138 #need to parse the preview early so that we know which templates are used,
1139 #otherwise users with "show preview after edit box" will get a blank list
1140 if ( $this->formtype == 'preview' ) {
1141 $previewOutput = $this->getPreviewText();
1142 }
1143
1144 $rows = $wgUser->getIntOption( 'rows' );
1145 $cols = $wgUser->getIntOption( 'cols' );
1146
1147 $ew = $wgUser->getOption( 'editwidth' );
1148 if ( $ew ) $ew = " style=\"width:100%\"";
1149 else $ew = '';
1150
1151 $q = 'action=submit';
1152 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1153 $action = $wgTitle->escapeLocalURL( $q );
1154
1155 $summary = wfMsg('summary');
1156 $subject = wfMsg('subject');
1157
1158 $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedText(),
1159 wfMsgExt('cancel', array('parseinline')) );
1160 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1161 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1162 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1163 htmlspecialchars( wfMsg( 'newwindow' ) );
1164
1165 global $wgRightsText;
1166 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1167 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
1168 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1169 $wgRightsText ) . "\n</div>";
1170
1171 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
1172 # prepare toolbar for edit buttons
1173 $toolbar = $this->getEditToolbar();
1174 } else {
1175 $toolbar = '';
1176 }
1177
1178 // activate checkboxes if user wants them to be always active
1179 if( !$this->preview && !$this->diff ) {
1180 # Sort out the "watch" checkbox
1181 if( $wgUser->getOption( 'watchdefault' ) ) {
1182 # Watch all edits
1183 $this->watchthis = true;
1184 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1185 # Watch creations
1186 $this->watchthis = true;
1187 } elseif( $this->mTitle->userIsWatching() ) {
1188 # Already watched
1189 $this->watchthis = true;
1190 }
1191
1192 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1193 }
1194
1195 $wgOut->addHTML( $this->editFormPageTop );
1196
1197 if ( $wgUser->getOption( 'previewontop' ) ) {
1198
1199 if ( 'preview' == $this->formtype ) {
1200 $this->showPreview( $previewOutput );
1201 } else {
1202 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1203 }
1204
1205 if ( 'diff' == $this->formtype ) {
1206 $this->showDiff();
1207 }
1208 }
1209
1210
1211 $wgOut->addHTML( $this->editFormTextTop );
1212
1213 # if this is a comment, show a subject line at the top, which is also the edit summary.
1214 # Otherwise, show a summary field at the bottom
1215 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
1216 if( $this->section == 'new' ) {
1217 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span>\n<div class='editOptions'>\n<input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
1218 $editsummary = '';
1219 $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1220 $summarypreview = '';
1221 } else {
1222 $commentsubject = '';
1223 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span>\n<div class='editOptions'>\n<input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
1224 $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1225 $subjectpreview = '';
1226 }
1227
1228 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1229 if( !$this->preview && !$this->diff ) {
1230 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1231 }
1232 $templates = ($this->preview || $this->section != '') ? $this->mPreviewTemplates : $this->mArticle->getUsedTemplates();
1233 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1234
1235 global $wgUseMetadataEdit ;
1236 if ( $wgUseMetadataEdit ) {
1237 $metadata = $this->mMetaData ;
1238 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1239 $top = wfMsgWikiHtml( 'metadata_help' );
1240 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1241 }
1242 else $metadata = "" ;
1243
1244 $hidden = '';
1245 $recreate = '';
1246 if ($this->deletedSinceEdit) {
1247 if ( 'save' != $this->formtype ) {
1248 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1249 } else {
1250 // Hide the toolbar and edit area, use can click preview to get it back
1251 // Add an confirmation checkbox and explanation.
1252 $toolbar = '';
1253 $hidden = 'type="hidden" style="display:none;"';
1254 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
1255 $recreate .=
1256 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1257 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1258 }
1259 }
1260
1261 $tabindex = 2;
1262
1263 $checkboxes = self::getCheckboxes( $tabindex, $sk,
1264 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1265
1266 $checkboxhtml = implode( $checkboxes, "\n" );
1267
1268 $buttons = $this->getEditButtons( $tabindex );
1269 $buttonshtml = implode( $buttons, "\n" );
1270
1271 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1272 ? '' : Xml::hidden( 'safemode', '1' );
1273
1274 $wgOut->addHTML( <<<END
1275 {$toolbar}
1276 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1277 END
1278 );
1279
1280 if( is_callable( $formCallback ) ) {
1281 call_user_func_array( $formCallback, array( &$wgOut ) );
1282 }
1283
1284 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1285
1286 // Put these up at the top to ensure they aren't lost on early form submission
1287 $wgOut->addHTML( "
1288 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1289 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1290 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1291 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1292
1293 $wgOut->addHTML( <<<END
1294 $recreate
1295 {$commentsubject}
1296 {$subjectpreview}
1297 {$this->editFormTextBeforeContent}
1298 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1299 cols='{$cols}'{$ew} $hidden>
1300 END
1301 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1302 "
1303 </textarea>
1304 " );
1305
1306 $wgOut->addWikiText( $copywarn );
1307 $wgOut->addHTML( $this->editFormTextAfterWarn );
1308 $wgOut->addHTML( "
1309 {$metadata}
1310 {$editsummary}
1311 {$summarypreview}
1312 {$checkboxhtml}
1313 {$safemodehtml}
1314 ");
1315
1316 $wgOut->addHTML(
1317 "<div class='editButtons'>
1318 {$buttonshtml}
1319 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1320 </div><!-- editButtons -->
1321 </div><!-- editOptions -->");
1322
1323 $wgOut->addHtml( '<div class="mw-editTools">' );
1324 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1325 $wgOut->addHtml( '</div>' );
1326
1327 $wgOut->addHTML( $this->editFormTextAfterTools );
1328
1329 $wgOut->addHTML( "
1330 <div class='templatesUsed'>
1331 {$formattedtemplates}
1332 </div>
1333 " );
1334
1335 /**
1336 * To make it harder for someone to slip a user a page
1337 * which submits an edit form to the wiki without their
1338 * knowledge, a random token is associated with the login
1339 * session. If it's not passed back with the submission,
1340 * we won't save the page, or render user JavaScript and
1341 * CSS previews.
1342 *
1343 * For anon editors, who may not have a session, we just
1344 * include the constant suffix to prevent editing from
1345 * broken text-mangling proxies.
1346 */
1347 $token = htmlspecialchars( $wgUser->editToken() );
1348 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1349
1350
1351 # If a blank edit summary was previously provided, and the appropriate
1352 # user preference is active, pass a hidden tag here. This will stop the
1353 # user being bounced back more than once in the event that a summary
1354 # is not required.
1355 if( $this->missingSummary ) {
1356 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1357 }
1358
1359 # For a bit more sophisticated detection of blank summaries, hash the
1360 # automatic one and pass that in a hidden field.
1361 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1362 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1363
1364 if ( $this->isConflict ) {
1365 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1366
1367 $de = new DifferenceEngine( $this->mTitle );
1368 $de->setText( $this->textbox2, $this->textbox1 );
1369 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1370
1371 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1372 $wgOut->addHTML( "<textarea tabindex='6' id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}'>"
1373 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1374 }
1375 $wgOut->addHTML( $this->editFormTextBottom );
1376 $wgOut->addHTML( "</form>\n" );
1377 if ( !$wgUser->getOption( 'previewontop' ) ) {
1378
1379 if ( $this->formtype == 'preview') {
1380 $this->showPreview( $previewOutput );
1381 } else {
1382 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1383 }
1384
1385 if ( $this->formtype == 'diff') {
1386 $this->showDiff();
1387 }
1388
1389 }
1390
1391 wfProfileOut( $fname );
1392 }
1393
1394 /**
1395 * Append preview output to $wgOut.
1396 * Includes category rendering if this is a category page.
1397 *
1398 * @param string $text The HTML to be output for the preview.
1399 */
1400 private function showPreview( $text ) {
1401 global $wgOut;
1402
1403 $wgOut->addHTML( '<div id="wikiPreview">' );
1404 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1405 $this->mArticle->openShowCategory();
1406 }
1407 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1408 $wgOut->addHTML( $text );
1409 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1410 $this->mArticle->closeShowCategory();
1411 }
1412 $wgOut->addHTML( '</div>' );
1413 }
1414
1415 /**
1416 * Live Preview lets us fetch rendered preview page content and
1417 * add it to the page without refreshing the whole page.
1418 * If not supported by the browser it will fall through to the normal form
1419 * submission method.
1420 *
1421 * This function outputs a script tag to support live preview, and
1422 * returns an onclick handler which should be added to the attributes
1423 * of the preview button
1424 */
1425 function doLivePreviewScript() {
1426 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1427 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1428 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1429 '"></script>' . "\n" );
1430 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1431 return "return !lpDoPreview(" .
1432 "editform.wpTextbox1.value," .
1433 '"' . $liveAction . '"' . ")";
1434 }
1435
1436 function getLastDelete() {
1437 $dbr = wfGetDB( DB_SLAVE );
1438 $fname = 'EditPage::getLastDelete';
1439 $res = $dbr->select(
1440 array( 'logging', 'user' ),
1441 array( 'log_type',
1442 'log_action',
1443 'log_timestamp',
1444 'log_user',
1445 'log_namespace',
1446 'log_title',
1447 'log_comment',
1448 'log_params',
1449 'user_name', ),
1450 array( 'log_namespace' => $this->mTitle->getNamespace(),
1451 'log_title' => $this->mTitle->getDBkey(),
1452 'log_type' => 'delete',
1453 'log_action' => 'delete',
1454 'user_id=log_user' ),
1455 $fname,
1456 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1457
1458 if($dbr->numRows($res) == 1) {
1459 while ( $x = $dbr->fetchObject ( $res ) )
1460 $data = $x;
1461 $dbr->freeResult ( $res ) ;
1462 } else {
1463 $data = null;
1464 }
1465 return $data;
1466 }
1467
1468 /**
1469 * @todo document
1470 */
1471 function getPreviewText() {
1472 global $wgOut, $wgUser, $wgTitle, $wgParser;
1473
1474 $fname = 'EditPage::getPreviewText';
1475 wfProfileIn( $fname );
1476
1477 if ( $this->mTriedSave && !$this->mTokenOk ) {
1478 if ( $this->mTokenOkExceptSuffix ) {
1479 $note = wfMsg( 'token_suffix_mismatch' );
1480 } else {
1481 $note = wfMsg( 'session_fail_preview' );
1482 }
1483 } else {
1484 $note = wfMsg( 'previewnote' );
1485 }
1486
1487 $parserOptions = ParserOptions::newFromUser( $wgUser );
1488 $parserOptions->setEditSection( false );
1489
1490 global $wgRawHtml;
1491 if( $wgRawHtml && !$this->mTokenOk ) {
1492 // Could be an offsite preview attempt. This is very unsafe if
1493 // HTML is enabled, as it could be an attack.
1494 return $wgOut->parse( "<div class='previewnote'>" .
1495 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1496 }
1497
1498 # don't parse user css/js, show message about preview
1499 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1500
1501 if ( $this->isCssJsSubpage ) {
1502 if(preg_match("/\\.css$/", $this->mTitle->getText() ) ) {
1503 $previewtext = wfMsg('usercsspreview');
1504 } else if(preg_match("/\\.js$/", $this->mTitle->getText() ) ) {
1505 $previewtext = wfMsg('userjspreview');
1506 }
1507 $parserOptions->setTidy(true);
1508 $parserOutput = $wgParser->parse( $previewtext , $this->mTitle, $parserOptions );
1509 $wgOut->addHTML( $parserOutput->mText );
1510 $previewHTML = '';
1511 } else {
1512 $toparse = $this->textbox1;
1513
1514 # If we're adding a comment, we need to show the
1515 # summary as the headline
1516 if($this->section=="new" && $this->summary!="") {
1517 $toparse="== {$this->summary} ==\n\n".$toparse;
1518 }
1519
1520 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1521 $parserOptions->setTidy(true);
1522 $parserOptions->enableLimitReport();
1523 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1524 $this->mTitle, $parserOptions );
1525
1526 $previewHTML = $parserOutput->getText();
1527 $wgOut->addParserOutputNoText( $parserOutput );
1528
1529 # ParserOutput might have altered the page title, so reset it
1530 $wgOut->setPageTitle( wfMsg( 'editing', $wgTitle->getPrefixedText() ) );
1531
1532 foreach ( $parserOutput->getTemplates() as $ns => $template)
1533 foreach ( array_keys( $template ) as $dbk)
1534 $this->mPreviewTemplates[] = Title::makeTitle($ns, $dbk);
1535
1536 if ( count( $parserOutput->getWarnings() ) ) {
1537 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1538 }
1539 }
1540
1541 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1542 "<div class='previewnote'>" . $wgOut->parse( $note ) . "</div>\n";
1543 if ( $this->isConflict ) {
1544 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1545 }
1546
1547 wfProfileOut( $fname );
1548 return $previewhead . $previewHTML;
1549 }
1550
1551 /**
1552 * Call the stock "user is blocked" page
1553 */
1554 function blockedPage() {
1555 global $wgOut, $wgUser;
1556 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1557
1558 # If the user made changes, preserve them when showing the markup
1559 # (This happens when a user is blocked during edit, for instance)
1560 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1561 if( $first ) {
1562 $source = $this->mTitle->exists() ? $this->getContent() : false;
1563 } else {
1564 $source = $this->textbox1;
1565 }
1566
1567 # Spit out the source or the user's modified version
1568 if( $source !== false ) {
1569 $rows = $wgUser->getOption( 'rows' );
1570 $cols = $wgUser->getOption( 'cols' );
1571 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1572 $wgOut->addHtml( '<hr />' );
1573 $wgOut->addWikiText( wfMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() ) );
1574 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1575 }
1576 }
1577
1578 /**
1579 * Produce the stock "please login to edit pages" page
1580 */
1581 function userNotLoggedInPage() {
1582 global $wgUser, $wgOut, $wgTitle;
1583 $skin = $wgUser->getSkin();
1584
1585 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1586 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1587
1588 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1589 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1590 $wgOut->setArticleRelated( false );
1591
1592 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1593 $wgOut->returnToMain( false, $wgTitle );
1594 }
1595
1596 /**
1597 * Creates a basic error page which informs the user that
1598 * they have attempted to edit a nonexistant section.
1599 */
1600 function noSuchSectionPage() {
1601 global $wgOut, $wgTitle;
1602
1603 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1604 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1605 $wgOut->setArticleRelated( false );
1606
1607 $wgOut->addWikiText( wfMsg( 'nosuchsectiontext', $this->section ) );
1608 $wgOut->returnToMain( false, $wgTitle );
1609 }
1610
1611 /**
1612 * Produce the stock "your edit contains spam" page
1613 *
1614 * @param $match Text which triggered one or more filters
1615 */
1616 function spamPage( $match = false ) {
1617 global $wgOut, $wgTitle;
1618
1619 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1620 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1621 $wgOut->setArticleRelated( false );
1622
1623 $wgOut->addHtml( '<div id="spamprotected">' );
1624 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1625 if ( $match )
1626 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch',wfEscapeWikiText( $match ) ) );
1627 $wgOut->addHtml( '</div>' );
1628
1629 $wgOut->returnToMain( false, $wgTitle );
1630 }
1631
1632 /**
1633 * @private
1634 * @todo document
1635 */
1636 function mergeChangesInto( &$editText ){
1637 $fname = 'EditPage::mergeChangesInto';
1638 wfProfileIn( $fname );
1639
1640 $db = wfGetDB( DB_MASTER );
1641
1642 // This is the revision the editor started from
1643 $baseRevision = Revision::loadFromTimestamp(
1644 $db, $this->mTitle, $this->edittime );
1645 if( is_null( $baseRevision ) ) {
1646 wfProfileOut( $fname );
1647 return false;
1648 }
1649 $baseText = $baseRevision->getText();
1650
1651 // The current state, we want to merge updates into it
1652 $currentRevision = Revision::loadFromTitle(
1653 $db, $this->mTitle );
1654 if( is_null( $currentRevision ) ) {
1655 wfProfileOut( $fname );
1656 return false;
1657 }
1658 $currentText = $currentRevision->getText();
1659
1660 $result = '';
1661 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1662 $editText = $result;
1663 wfProfileOut( $fname );
1664 return true;
1665 } else {
1666 wfProfileOut( $fname );
1667 return false;
1668 }
1669 }
1670
1671 /**
1672 * Check if the browser is on a blacklist of user-agents known to
1673 * mangle UTF-8 data on form submission. Returns true if Unicode
1674 * should make it through, false if it's known to be a problem.
1675 * @return bool
1676 * @private
1677 */
1678 function checkUnicodeCompliantBrowser() {
1679 global $wgBrowserBlackList;
1680 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1681 // No User-Agent header sent? Trust it by default...
1682 return true;
1683 }
1684 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1685 foreach ( $wgBrowserBlackList as $browser ) {
1686 if ( preg_match($browser, $currentbrowser) ) {
1687 return false;
1688 }
1689 }
1690 return true;
1691 }
1692
1693 /**
1694 * @deprecated use $wgParser->stripSectionName()
1695 */
1696 function pseudoParseSectionAnchor( $text ) {
1697 global $wgParser;
1698 return $wgParser->stripSectionName( $text );
1699 }
1700
1701 /**
1702 * Format an anchor fragment as it would appear for a given section name
1703 * @param string $text
1704 * @return string
1705 * @private
1706 */
1707 function sectionAnchor( $text ) {
1708 global $wgParser;
1709 return $wgParser->guessSectionNameFromWikiText( $text );
1710 }
1711
1712 /**
1713 * Shows a bulletin board style toolbar for common editing functions.
1714 * It can be disabled in the user preferences.
1715 * The necessary JavaScript code can be found in style/wikibits.js.
1716 */
1717 function getEditToolbar() {
1718 global $wgStylePath, $wgContLang, $wgJsMimeType;
1719
1720 /**
1721 * toolarray an array of arrays which each include the filename of
1722 * the button image (without path), the opening tag, the closing tag,
1723 * and optionally a sample text that is inserted between the two when no
1724 * selection is highlighted.
1725 * The tip text is shown when the user moves the mouse over the button.
1726 *
1727 * Already here are accesskeys (key), which are not used yet until someone
1728 * can figure out a way to make them work in IE. However, we should make
1729 * sure these keys are not defined on the edit page.
1730 */
1731 $toolarray = array(
1732 array( 'image' => 'button_bold.png',
1733 'id' => 'mw-editbutton-bold',
1734 'open' => '\\\'\\\'\\\'',
1735 'close' => '\\\'\\\'\\\'',
1736 'sample'=> wfMsg('bold_sample'),
1737 'tip' => wfMsg('bold_tip'),
1738 'key' => 'B'
1739 ),
1740 array( 'image' => 'button_italic.png',
1741 'id' => 'mw-editbutton-italic',
1742 'open' => '\\\'\\\'',
1743 'close' => '\\\'\\\'',
1744 'sample'=> wfMsg('italic_sample'),
1745 'tip' => wfMsg('italic_tip'),
1746 'key' => 'I'
1747 ),
1748 array( 'image' => 'button_link.png',
1749 'id' => 'mw-editbutton-link',
1750 'open' => '[[',
1751 'close' => ']]',
1752 'sample'=> wfMsg('link_sample'),
1753 'tip' => wfMsg('link_tip'),
1754 'key' => 'L'
1755 ),
1756 array( 'image' => 'button_extlink.png',
1757 'id' => 'mw-editbutton-extlink',
1758 'open' => '[',
1759 'close' => ']',
1760 'sample'=> wfMsg('extlink_sample'),
1761 'tip' => wfMsg('extlink_tip'),
1762 'key' => 'X'
1763 ),
1764 array( 'image' => 'button_headline.png',
1765 'id' => 'mw-editbutton-headline',
1766 'open' => "\\n== ",
1767 'close' => " ==\\n",
1768 'sample'=> wfMsg('headline_sample'),
1769 'tip' => wfMsg('headline_tip'),
1770 'key' => 'H'
1771 ),
1772 array( 'image' => 'button_image.png',
1773 'id' => 'mw-editbutton-image',
1774 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1775 'close' => ']]',
1776 'sample'=> wfMsg('image_sample'),
1777 'tip' => wfMsg('image_tip'),
1778 'key' => 'D'
1779 ),
1780 array( 'image' => 'button_media.png',
1781 'id' => 'mw-editbutton-media',
1782 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1783 'close' => ']]',
1784 'sample'=> wfMsg('media_sample'),
1785 'tip' => wfMsg('media_tip'),
1786 'key' => 'M'
1787 ),
1788 array( 'image' => 'button_math.png',
1789 'id' => 'mw-editbutton-math',
1790 'open' => "<math>",
1791 'close' => "<\\/math>",
1792 'sample'=> wfMsg('math_sample'),
1793 'tip' => wfMsg('math_tip'),
1794 'key' => 'C'
1795 ),
1796 array( 'image' => 'button_nowiki.png',
1797 'id' => 'mw-editbutton-nowiki',
1798 'open' => "<nowiki>",
1799 'close' => "<\\/nowiki>",
1800 'sample'=> wfMsg('nowiki_sample'),
1801 'tip' => wfMsg('nowiki_tip'),
1802 'key' => 'N'
1803 ),
1804 array( 'image' => 'button_sig.png',
1805 'id' => 'mw-editbutton-signature',
1806 'open' => '--~~~~',
1807 'close' => '',
1808 'sample'=> '',
1809 'tip' => wfMsg('sig_tip'),
1810 'key' => 'Y'
1811 ),
1812 array( 'image' => 'button_hr.png',
1813 'id' => 'mw-editbutton-hr',
1814 'open' => "\\n----\\n",
1815 'close' => '',
1816 'sample'=> '',
1817 'tip' => wfMsg('hr_tip'),
1818 'key' => 'R'
1819 )
1820 );
1821 $toolbar = "<div id='toolbar'>\n";
1822 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1823
1824 foreach($toolarray as $tool) {
1825
1826 $cssId = $tool['id'];
1827 $image=$wgStylePath.'/common/images/'.$tool['image'];
1828 $open=$tool['open'];
1829 $close=$tool['close'];
1830 $sample = wfEscapeJsString( $tool['sample'] );
1831
1832 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1833 // Older browsers show a "speedtip" type message only for ALT.
1834 // Ideally these should be different, realistically they
1835 // probably don't need to be.
1836 $tip = wfEscapeJsString( $tool['tip'] );
1837
1838 #$key = $tool["key"];
1839
1840 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1841 }
1842
1843 $toolbar.="/*]]>*/\n</script>";
1844 $toolbar.="\n</div>";
1845 return $toolbar;
1846 }
1847
1848 /**
1849 * Returns an array of html code of the following checkboxes:
1850 * minor and watch
1851 *
1852 * @param $tabindex Current tabindex
1853 * @param $skin Skin object
1854 * @param $checked Array of checkbox => bool, where bool indicates the checked
1855 * status of the checkbox
1856 *
1857 * @return array
1858 */
1859 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1860 global $wgUser;
1861
1862 $checkboxes = array();
1863
1864 $checkboxes['minor'] = '';
1865 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1866 if ( $wgUser->isAllowed('minoredit') ) {
1867 $attribs = array(
1868 'tabindex' => ++$tabindex,
1869 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1870 'id' => 'wpMinoredit',
1871 );
1872 $checkboxes['minor'] =
1873 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1874 "&nbsp;<label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1875 }
1876
1877 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1878 $checkboxes['watch'] = '';
1879 if ( $wgUser->isLoggedIn() ) {
1880 $attribs = array(
1881 'tabindex' => ++$tabindex,
1882 'accesskey' => wfMsg( 'accesskey-watch' ),
1883 'id' => 'wpWatchthis',
1884 );
1885 $checkboxes['watch'] =
1886 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1887 "&nbsp;<label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1888 }
1889 return $checkboxes;
1890 }
1891
1892 /**
1893 * Returns an array of html code of the following buttons:
1894 * save, diff, preview and live
1895 *
1896 * @param $tabindex Current tabindex
1897 *
1898 * @return array
1899 */
1900 public function getEditButtons(&$tabindex) {
1901 global $wgLivePreview, $wgUser;
1902
1903 $buttons = array();
1904
1905 $temp = array(
1906 'id' => 'wpSave',
1907 'name' => 'wpSave',
1908 'type' => 'submit',
1909 'tabindex' => ++$tabindex,
1910 'value' => wfMsg('savearticle'),
1911 'accesskey' => wfMsg('accesskey-save'),
1912 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1913 );
1914 $buttons['save'] = wfElement('input', $temp, '');
1915
1916 ++$tabindex; // use the same for preview and live preview
1917 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1918 $temp = array(
1919 'id' => 'wpPreview',
1920 'name' => 'wpPreview',
1921 'type' => 'submit',
1922 'tabindex' => $tabindex,
1923 'value' => wfMsg('showpreview'),
1924 'accesskey' => '',
1925 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1926 'style' => 'display: none;',
1927 );
1928 $buttons['preview'] = wfElement('input', $temp, '');
1929
1930 $temp = array(
1931 'id' => 'wpLivePreview',
1932 'name' => 'wpLivePreview',
1933 'type' => 'submit',
1934 'tabindex' => $tabindex,
1935 'value' => wfMsg('showlivepreview'),
1936 'accesskey' => wfMsg('accesskey-preview'),
1937 'title' => '',
1938 'onclick' => $this->doLivePreviewScript(),
1939 );
1940 $buttons['live'] = wfElement('input', $temp, '');
1941 } else {
1942 $temp = array(
1943 'id' => 'wpPreview',
1944 'name' => 'wpPreview',
1945 'type' => 'submit',
1946 'tabindex' => $tabindex,
1947 'value' => wfMsg('showpreview'),
1948 'accesskey' => wfMsg('accesskey-preview'),
1949 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1950 );
1951 $buttons['preview'] = wfElement('input', $temp, '');
1952 $buttons['live'] = '';
1953 }
1954
1955 $temp = array(
1956 'id' => 'wpDiff',
1957 'name' => 'wpDiff',
1958 'type' => 'submit',
1959 'tabindex' => ++$tabindex,
1960 'value' => wfMsg('showdiff'),
1961 'accesskey' => wfMsg('accesskey-diff'),
1962 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1963 );
1964 $buttons['diff'] = wfElement('input', $temp, '');
1965
1966 return $buttons;
1967 }
1968
1969 /**
1970 * Output preview text only. This can be sucked into the edit page
1971 * via JavaScript, and saves the server time rendering the skin as
1972 * well as theoretically being more robust on the client (doesn't
1973 * disturb the edit box's undo history, won't eat your text on
1974 * failure, etc).
1975 *
1976 * @todo This doesn't include category or interlanguage links.
1977 * Would need to enhance it a bit, <s>maybe wrap them in XML
1978 * or something...</s> that might also require more skin
1979 * initialization, so check whether that's a problem.
1980 */
1981 function livePreview() {
1982 global $wgOut;
1983 $wgOut->disable();
1984 header( 'Content-type: text/xml; charset=utf-8' );
1985 header( 'Cache-control: no-cache' );
1986
1987 $previewText = $this->getPreviewText();
1988 #$categories = $skin->getCategoryLinks();
1989
1990 $s =
1991 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1992 Xml::tags( 'livepreview', null,
1993 Xml::element( 'preview', null, $previewText )
1994 #. Xml::element( 'category', null, $categories )
1995 );
1996 echo $s;
1997 }
1998
1999
2000 /**
2001 * Get a diff between the current contents of the edit box and the
2002 * version of the page we're editing from.
2003 *
2004 * If this is a section edit, we'll replace the section as for final
2005 * save and then make a comparison.
2006 */
2007 function showDiff() {
2008 $oldtext = $this->mArticle->fetchContent();
2009 $newtext = $this->mArticle->replaceSection(
2010 $this->section, $this->textbox1, $this->summary, $this->edittime );
2011 $newtext = $this->mArticle->preSaveTransform( $newtext );
2012 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2013 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2014 if ( $oldtext !== false || $newtext != '' ) {
2015 $de = new DifferenceEngine( $this->mTitle );
2016 $de->setText( $oldtext, $newtext );
2017 $difftext = $de->getDiff( $oldtitle, $newtitle );
2018 $de->showDiffStyle();
2019 } else {
2020 $difftext = '';
2021 }
2022
2023 global $wgOut;
2024 $wgOut->addHtml( '<div id="wikiDiff">' . $difftext . '</div>' );
2025 }
2026
2027 /**
2028 * Filter an input field through a Unicode de-armoring process if it
2029 * came from an old browser with known broken Unicode editing issues.
2030 *
2031 * @param WebRequest $request
2032 * @param string $field
2033 * @return string
2034 * @private
2035 */
2036 function safeUnicodeInput( $request, $field ) {
2037 $text = rtrim( $request->getText( $field ) );
2038 return $request->getBool( 'safemode' )
2039 ? $this->unmakesafe( $text )
2040 : $text;
2041 }
2042
2043 /**
2044 * Filter an output field through a Unicode armoring process if it is
2045 * going to an old browser with known broken Unicode editing issues.
2046 *
2047 * @param string $text
2048 * @return string
2049 * @private
2050 */
2051 function safeUnicodeOutput( $text ) {
2052 global $wgContLang;
2053 $codedText = $wgContLang->recodeForEdit( $text );
2054 return $this->checkUnicodeCompliantBrowser()
2055 ? $codedText
2056 : $this->makesafe( $codedText );
2057 }
2058
2059 /**
2060 * A number of web browsers are known to corrupt non-ASCII characters
2061 * in a UTF-8 text editing environment. To protect against this,
2062 * detected browsers will be served an armored version of the text,
2063 * with non-ASCII chars converted to numeric HTML character references.
2064 *
2065 * Preexisting such character references will have a 0 added to them
2066 * to ensure that round-trips do not alter the original data.
2067 *
2068 * @param string $invalue
2069 * @return string
2070 * @private
2071 */
2072 function makesafe( $invalue ) {
2073 // Armor existing references for reversability.
2074 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
2075
2076 $bytesleft = 0;
2077 $result = "";
2078 $working = 0;
2079 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2080 $bytevalue = ord( $invalue{$i} );
2081 if( $bytevalue <= 0x7F ) { //0xxx xxxx
2082 $result .= chr( $bytevalue );
2083 $bytesleft = 0;
2084 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
2085 $working = $working << 6;
2086 $working += ($bytevalue & 0x3F);
2087 $bytesleft--;
2088 if( $bytesleft <= 0 ) {
2089 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2090 }
2091 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
2092 $working = $bytevalue & 0x1F;
2093 $bytesleft = 1;
2094 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
2095 $working = $bytevalue & 0x0F;
2096 $bytesleft = 2;
2097 } else { //1111 0xxx
2098 $working = $bytevalue & 0x07;
2099 $bytesleft = 3;
2100 }
2101 }
2102 return $result;
2103 }
2104
2105 /**
2106 * Reverse the previously applied transliteration of non-ASCII characters
2107 * back to UTF-8. Used to protect data from corruption by broken web browsers
2108 * as listed in $wgBrowserBlackList.
2109 *
2110 * @param string $invalue
2111 * @return string
2112 * @private
2113 */
2114 function unmakesafe( $invalue ) {
2115 $result = "";
2116 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2117 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
2118 $i += 3;
2119 $hexstring = "";
2120 do {
2121 $hexstring .= $invalue{$i};
2122 $i++;
2123 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2124
2125 // Do some sanity checks. These aren't needed for reversability,
2126 // but should help keep the breakage down if the editor
2127 // breaks one of the entities whilst editing.
2128 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2129 $codepoint = hexdec($hexstring);
2130 $result .= codepointToUtf8( $codepoint );
2131 } else {
2132 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2133 }
2134 } else {
2135 $result .= substr( $invalue, $i, 1 );
2136 }
2137 }
2138 // reverse the transform that we made for reversability reasons.
2139 return strtr( $result, array( "&#x0" => "&#x" ) );
2140 }
2141
2142 function noCreatePermission() {
2143 global $wgOut;
2144 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2145 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
2146 }
2147
2148 /**
2149 * If there are rows in the deletion log for this page, show them,
2150 * along with a nice little note for the user
2151 *
2152 * @param OutputPage $out
2153 */
2154 private function showDeletionLog( $out ) {
2155 $title = $this->mTitle;
2156 $reader = new LogReader(
2157 new FauxRequest(
2158 array(
2159 'page' => $title->getPrefixedText(),
2160 'type' => 'delete',
2161 )
2162 )
2163 );
2164 if( $reader->hasRows() ) {
2165 $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
2166 $out->addWikiText( wfMsg( 'recreate-deleted-warn' ) );
2167 $viewer = new LogViewer( $reader );
2168 $viewer->showList( $out );
2169 $out->addHtml( '</div>' );
2170 }
2171 }
2172
2173 /**
2174 * Attempt submission
2175 * @return bool false if output is done, true if the rest of the form should be displayed
2176 */
2177 function attemptSave() {
2178 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2179
2180 $resultDetails = false;
2181 $value = $this->internalAttemptSave( $resultDetails, $wgUser->isAllowed('bot') && $wgRequest->getBool('bot', true) );
2182
2183 if( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) {
2184 $this->didSave = true;
2185 }
2186
2187 switch ($value) {
2188 case self::AS_HOOK_ERROR_EXPECTED:
2189 case self::AS_CONTENT_TOO_BIG:
2190 case self::AS_ARTICLE_WAS_DELETED:
2191 case self::AS_CONFLICT_DETECTED:
2192 case self::AS_SUMMARY_NEEDED:
2193 case self::AS_TEXTBOX_EMPTY:
2194 case self::AS_MAX_ARTICLE_SIZE_EXCEDED:
2195 case self::AS_END:
2196 return true;
2197
2198 case self::AS_HOOK_ERROR:
2199 case self::AS_FILTERING:
2200 case self::AS_SUCCESS_NEW_ARTICLE:
2201 case self::AS_SUCCESS_UPDATE:
2202 return false;
2203
2204 case self::AS_SPAM_ERROR:
2205 $this->spamPage ( $resultDetails['spam'] );
2206 return false;
2207
2208 case self::AS_BLOCKED_PAGE_FOR_USER:
2209 $this->blockedPage();
2210 return false;
2211
2212 case self::AS_IMAGE_REDIRECT_ANON:
2213 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2214 return false;
2215
2216 case self::AS_READ_ONLY_PAGE_ANON:
2217 $this->userNotLoggedInPage();
2218 return false;
2219
2220 case self::AS_READ_ONLY_PAGE_LOGGED:
2221 case self::AS_READ_ONLY_PAGE:
2222 $wgOut->readOnlyPage();
2223 return false;
2224
2225 case self::AS_RATE_LIMITED:
2226 $wgOut->rateLimited();
2227 return false;
2228
2229 case self::AS_NO_CREATE_PERMISSION;
2230 $this->noCreatePermission();
2231 return;
2232
2233 case self::AS_BLANK_ARTICLE:
2234 $wgOut->redirect( $wgTitle->getFullURL() );
2235 return false;
2236
2237 case self::AS_IMAGE_REDIRECT_LOGGED:
2238 $wgOut->permissionRequired( 'upload' );
2239 return false;
2240 }
2241 }
2242 }