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