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