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