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