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