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