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