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