Revert r38221, 38238 -- "Add new parser function {{apiurl}}. Also, add new global...
[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 # 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 protected 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 protected 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 protected 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->addHTML( "<div id='mw-edit-$noticeMsg'>\n" );
1148 $wgOut->addWikiMsg( $noticeMsg );
1149 $wgOut->addHTML( "</div>\n" );
1150 }
1151 if ( $this->mTitle->isCascadeProtected() ) {
1152 # Is this page under cascading protection from some source pages?
1153 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1154 $notice = "$1\n";
1155 if ( count($cascadeSources) > 0 ) {
1156 # Explain, and list the titles responsible
1157 foreach( $cascadeSources as $page ) {
1158 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1159 }
1160 }
1161 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', count($cascadeSources) ) );
1162 }
1163 if( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) != array() ){
1164 $wgOut->addWikiMsg( 'titleprotectedwarning' );
1165 }
1166
1167 if ( $this->kblength === false ) {
1168 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
1169 }
1170 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1171 $wgOut->addHTML( "<div id='mw-edit-longpageerror'>\n" );
1172 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) );
1173 $wgOut->addHTML( "</div>\n" );
1174 } elseif( $this->kblength > 29 ) {
1175 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1176 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) );
1177 $wgOut->addHTML( "</div>\n" );
1178 }
1179
1180 #need to parse the preview early so that we know which templates are used,
1181 #otherwise users with "show preview after edit box" will get a blank list
1182 if ( $this->formtype == 'preview' ) {
1183 $previewOutput = $this->getPreviewText();
1184 }
1185
1186 $rows = $wgUser->getIntOption( 'rows' );
1187 $cols = $wgUser->getIntOption( 'cols' );
1188
1189 $ew = $wgUser->getOption( 'editwidth' );
1190 if ( $ew ) $ew = " style=\"width:100%\"";
1191 else $ew = '';
1192
1193 $q = 'action=submit';
1194 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1195 $action = $wgTitle->escapeLocalURL( $q );
1196
1197 $summary = wfMsg('summary');
1198 $subject = wfMsg('subject');
1199
1200 $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedText(),
1201 wfMsgExt('cancel', array('parseinline')) );
1202 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1203 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1204 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1205 htmlspecialchars( wfMsg( 'newwindow' ) );
1206
1207 global $wgRightsText;
1208 if ( $wgRightsText ) {
1209 $copywarnMsg = array( 'copyrightwarning',
1210 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1211 $wgRightsText );
1212 } else {
1213 $copywarnMsg = array( 'copyrightwarning2',
1214 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1215 }
1216
1217 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
1218 # prepare toolbar for edit buttons
1219 $toolbar = EditPage::getEditToolbar();
1220 } else {
1221 $toolbar = '';
1222 }
1223
1224 // activate checkboxes if user wants them to be always active
1225 if( !$this->preview && !$this->diff ) {
1226 # Sort out the "watch" checkbox
1227 if( $wgUser->getOption( 'watchdefault' ) ) {
1228 # Watch all edits
1229 $this->watchthis = true;
1230 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1231 # Watch creations
1232 $this->watchthis = true;
1233 } elseif( $this->mTitle->userIsWatching() ) {
1234 # Already watched
1235 $this->watchthis = true;
1236 }
1237
1238 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1239 }
1240
1241 $wgOut->addHTML( $this->editFormPageTop );
1242
1243 if ( $wgUser->getOption( 'previewontop' ) ) {
1244
1245 if ( 'preview' == $this->formtype ) {
1246 $this->showPreview( $previewOutput );
1247 } else {
1248 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1249 }
1250
1251 if ( 'diff' == $this->formtype ) {
1252 $this->showDiff();
1253 }
1254 }
1255
1256
1257 $wgOut->addHTML( $this->editFormTextTop );
1258
1259 # if this is a comment, show a subject line at the top, which is also the edit summary.
1260 # Otherwise, show a summary field at the bottom
1261 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
1262
1263 # If a blank edit summary was previously provided, and the appropriate
1264 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1265 # user being bounced back more than once in the event that a summary
1266 # is not required.
1267 #####
1268 # For a bit more sophisticated detection of blank summaries, hash the
1269 # automatic one and pass that in the hidden field wpAutoSummary.
1270 $summaryhiddens = '';
1271 if( $this->missingSummary ) $summaryhiddens .= Xml::hidden( 'wpIgnoreBlankSummary', true );
1272 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1273 $summaryhiddens .= Xml::hidden( 'wpAutoSummary', $autosumm );
1274 if( $this->section == 'new' ) {
1275 $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 />";
1276 $editsummary = "<div class='editOptions'>\n";
1277 global $wgParser;
1278 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary ) );
1279 $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $formattedSummary, $this->mTitle, true )."</div>\n" : '';
1280 $summarypreview = '';
1281 } else {
1282 $commentsubject = '';
1283 $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 />";
1284 $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1285 $subjectpreview = '';
1286 }
1287
1288 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1289 if( !$this->preview && !$this->diff ) {
1290 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1291 }
1292 $templates = ($this->preview || $this->section != '') ? $this->mPreviewTemplates : $this->mArticle->getUsedTemplates();
1293 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1294
1295 $hiddencats = $this->mArticle->getHiddenCategories();
1296 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1297
1298 global $wgUseMetadataEdit ;
1299 if ( $wgUseMetadataEdit ) {
1300 $metadata = $this->mMetaData ;
1301 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1302 $top = wfMsgWikiHtml( 'metadata_help' );
1303 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1304 }
1305 else $metadata = "" ;
1306
1307 $hidden = '';
1308 $recreate = '';
1309 if ($this->wasDeletedSinceLastEdit()) {
1310 if ( 'save' != $this->formtype ) {
1311 $wgOut->addWikiMsg('deletedwhileediting');
1312 } else {
1313 // Hide the toolbar and edit area, use can click preview to get it back
1314 // Add an confirmation checkbox and explanation.
1315 $toolbar = '';
1316 $hidden = 'type="hidden" style="display:none;"';
1317 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
1318 $recreate .=
1319 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1320 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1321 }
1322 }
1323
1324 $tabindex = 2;
1325
1326 $checkboxes = self::getCheckboxes( $tabindex, $sk,
1327 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1328
1329 $checkboxhtml = implode( $checkboxes, "\n" );
1330
1331 $buttons = $this->getEditButtons( $tabindex );
1332 $buttonshtml = implode( $buttons, "\n" );
1333
1334 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1335 ? '' : Xml::hidden( 'safemode', '1' );
1336
1337 $wgOut->addHTML( <<<END
1338 {$toolbar}
1339 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1340 END
1341 );
1342
1343 if( is_callable( $formCallback ) ) {
1344 call_user_func_array( $formCallback, array( &$wgOut ) );
1345 }
1346
1347 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1348
1349 // Put these up at the top to ensure they aren't lost on early form submission
1350 $wgOut->addHTML( "
1351 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1352 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1353 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1354 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1355
1356 $encodedtext = htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) );
1357 if( $encodedtext !== '' ) {
1358 // Ensure there's a newline at the end, otherwise adding lines
1359 // is awkward.
1360 // But don't add a newline if the ext is empty, or Firefox in XHTML
1361 // mode will show an extra newline. A bit annoying.
1362 $encodedtext .= "\n";
1363 }
1364
1365 $wgOut->addHTML( <<<END
1366 $recreate
1367 {$commentsubject}
1368 {$subjectpreview}
1369 {$this->editFormTextBeforeContent}
1370 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1371 cols='{$cols}'{$ew} $hidden>{$encodedtext}</textarea>
1372 END
1373 );
1374
1375 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1376 $wgOut->addHTML( $this->editFormTextAfterWarn );
1377 $wgOut->addHTML( "
1378 {$metadata}
1379 {$editsummary}
1380 {$summarypreview}
1381 {$checkboxhtml}
1382 {$safemodehtml}
1383 ");
1384
1385 $wgOut->addHTML(
1386 "<div class='editButtons'>
1387 {$buttonshtml}
1388 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1389 </div><!-- editButtons -->
1390 </div><!-- editOptions -->");
1391
1392 /**
1393 * To make it harder for someone to slip a user a page
1394 * which submits an edit form to the wiki without their
1395 * knowledge, a random token is associated with the login
1396 * session. If it's not passed back with the submission,
1397 * we won't save the page, or render user JavaScript and
1398 * CSS previews.
1399 *
1400 * For anon editors, who may not have a session, we just
1401 * include the constant suffix to prevent editing from
1402 * broken text-mangling proxies.
1403 */
1404 $token = htmlspecialchars( $wgUser->editToken() );
1405 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1406
1407 $wgOut->addHtml( '<div class="mw-editTools">' );
1408 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1409 $wgOut->addHtml( '</div>' );
1410
1411 $wgOut->addHTML( $this->editFormTextAfterTools );
1412
1413 $wgOut->addHTML( "
1414 <div class='templatesUsed'>
1415 {$formattedtemplates}
1416 </div>
1417 <div class='hiddencats'>
1418 {$formattedhiddencats}
1419 </div>
1420 ");
1421
1422 if ( $this->isConflict && wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1423 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1424
1425 $de = new DifferenceEngine( $this->mTitle );
1426 $de->setText( $this->textbox2, $this->textbox1 );
1427 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1428
1429 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1430 $wgOut->addHTML( "<textarea tabindex='6' id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}'>"
1431 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1432 }
1433 $wgOut->addHTML( $this->editFormTextBottom );
1434 $wgOut->addHTML( "</form>\n" );
1435 if ( !$wgUser->getOption( 'previewontop' ) ) {
1436
1437 if ( $this->formtype == 'preview') {
1438 $this->showPreview( $previewOutput );
1439 } else {
1440 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1441 }
1442
1443 if ( $this->formtype == 'diff') {
1444 $this->showDiff();
1445 }
1446
1447 }
1448
1449 wfProfileOut( $fname );
1450 }
1451
1452 /**
1453 * Append preview output to $wgOut.
1454 * Includes category rendering if this is a category page.
1455 *
1456 * @param string $text The HTML to be output for the preview.
1457 */
1458 protected function showPreview( $text ) {
1459 global $wgOut;
1460
1461 $wgOut->addHTML( '<div id="wikiPreview">' );
1462 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1463 $this->mArticle->openShowCategory();
1464 }
1465 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1466 $wgOut->addHTML( $text );
1467 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1468 $this->mArticle->closeShowCategory();
1469 }
1470 $wgOut->addHTML( '</div>' );
1471 }
1472
1473 /**
1474 * Live Preview lets us fetch rendered preview page content and
1475 * add it to the page without refreshing the whole page.
1476 * If not supported by the browser it will fall through to the normal form
1477 * submission method.
1478 *
1479 * This function outputs a script tag to support live preview, and
1480 * returns an onclick handler which should be added to the attributes
1481 * of the preview button
1482 */
1483 function doLivePreviewScript() {
1484 global $wgOut, $wgTitle;
1485 $wgOut->addScriptFile( 'preview.js' );
1486 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1487 return "return !lpDoPreview(" .
1488 "editform.wpTextbox1.value," .
1489 '"' . $liveAction . '"' . ")";
1490 }
1491
1492 function getLastDelete() {
1493 $dbr = wfGetDB( DB_SLAVE );
1494 $fname = 'EditPage::getLastDelete';
1495 $res = $dbr->select(
1496 array( 'logging', 'user' ),
1497 array( 'log_type',
1498 'log_action',
1499 'log_timestamp',
1500 'log_user',
1501 'log_namespace',
1502 'log_title',
1503 'log_comment',
1504 'log_params',
1505 'user_name', ),
1506 array( 'log_namespace' => $this->mTitle->getNamespace(),
1507 'log_title' => $this->mTitle->getDBkey(),
1508 'log_type' => 'delete',
1509 'log_action' => 'delete',
1510 'user_id=log_user' ),
1511 $fname,
1512 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1513
1514 if($dbr->numRows($res) == 1) {
1515 while ( $x = $dbr->fetchObject ( $res ) )
1516 $data = $x;
1517 $dbr->freeResult ( $res ) ;
1518 } else {
1519 $data = null;
1520 }
1521 return $data;
1522 }
1523
1524 /**
1525 * @todo document
1526 */
1527 function getPreviewText() {
1528 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang;
1529
1530 $fname = 'EditPage::getPreviewText';
1531 wfProfileIn( $fname );
1532
1533 if ( $this->mTriedSave && !$this->mTokenOk ) {
1534 if ( $this->mTokenOkExceptSuffix ) {
1535 $note = wfMsg( 'token_suffix_mismatch' );
1536 } else {
1537 $note = wfMsg( 'session_fail_preview' );
1538 }
1539 } else {
1540 $note = wfMsg( 'previewnote' );
1541 }
1542
1543 $parserOptions = ParserOptions::newFromUser( $wgUser );
1544 $parserOptions->setEditSection( false );
1545
1546 global $wgRawHtml;
1547 if( $wgRawHtml && !$this->mTokenOk ) {
1548 // Could be an offsite preview attempt. This is very unsafe if
1549 // HTML is enabled, as it could be an attack.
1550 return $wgOut->parse( "<div class='previewnote'>" .
1551 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1552 }
1553
1554 # don't parse user css/js, show message about preview
1555 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1556
1557 if ( $this->isCssJsSubpage ) {
1558 if(preg_match("/\\.css$/", $this->mTitle->getText() ) ) {
1559 $previewtext = wfMsg('usercsspreview');
1560 } else if(preg_match("/\\.js$/", $this->mTitle->getText() ) ) {
1561 $previewtext = wfMsg('userjspreview');
1562 }
1563 $parserOptions->setTidy(true);
1564 $parserOutput = $wgParser->parse( $previewtext , $this->mTitle, $parserOptions );
1565 $wgOut->addHTML( $parserOutput->mText );
1566 $previewHTML = '';
1567 } else {
1568 $toparse = $this->textbox1;
1569
1570 # If we're adding a comment, we need to show the
1571 # summary as the headline
1572 if($this->section=="new" && $this->summary!="") {
1573 $toparse="== {$this->summary} ==\n\n".$toparse;
1574 }
1575
1576 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData;
1577
1578 // Parse mediawiki messages with correct target language
1579 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1580 $pos = strrpos( $this->mTitle->getText(), '/' );
1581 if ( $pos !== false ) {
1582 $code = substr( $this->mTitle->getText(), $pos+1 );
1583 switch ($code) {
1584 case $wgLang->getCode():
1585 $obj = $wgLang; break;
1586 case $wgContLang->getCode():
1587 $obj = $wgContLang; break;
1588 default:
1589 $obj = Language::factory( $code );
1590 }
1591 $parserOptions->setTargetLanguage( $obj );
1592 }
1593 }
1594
1595
1596 $parserOptions->setTidy(true);
1597 $parserOptions->enableLimitReport();
1598 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ),
1599 $this->mTitle, $parserOptions );
1600
1601 $previewHTML = $parserOutput->getText();
1602 $wgOut->addParserOutputNoText( $parserOutput );
1603
1604 # ParserOutput might have altered the page title, so reset it
1605 # Also, use the title defined by DISPLAYTITLE magic word when present
1606 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false ) {
1607 $wgOut->setPageTitle( wfMsg( 'editing', $dt ) );
1608 } else {
1609 $wgOut->setPageTitle( wfMsg( 'editing', $wgTitle->getPrefixedText() ) );
1610 }
1611
1612 foreach ( $parserOutput->getTemplates() as $ns => $template)
1613 foreach ( array_keys( $template ) as $dbk)
1614 $this->mPreviewTemplates[] = Title::makeTitle($ns, $dbk);
1615
1616 if ( count( $parserOutput->getWarnings() ) ) {
1617 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1618 }
1619 }
1620
1621 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1622 "<div class='previewnote'>" . $wgOut->parse( $note ) . "</div>\n";
1623 if ( $this->isConflict ) {
1624 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1625 }
1626
1627 if( $wgUser->getOption( 'previewontop' ) ) {
1628 // Spacer for the edit toolbar
1629 $previewfoot = '<p><br /></p>';
1630 } else {
1631 $previewfoot = '';
1632 }
1633
1634 wfProfileOut( $fname );
1635 return $previewhead . $previewHTML . $previewfoot;
1636 }
1637
1638 /**
1639 * Call the stock "user is blocked" page
1640 */
1641 function blockedPage() {
1642 global $wgOut, $wgUser;
1643 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1644
1645 # If the user made changes, preserve them when showing the markup
1646 # (This happens when a user is blocked during edit, for instance)
1647 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1648 if( $first ) {
1649 $source = $this->mTitle->exists() ? $this->getContent() : false;
1650 } else {
1651 $source = $this->textbox1;
1652 }
1653
1654 # Spit out the source or the user's modified version
1655 if( $source !== false ) {
1656 $rows = $wgUser->getOption( 'rows' );
1657 $cols = $wgUser->getOption( 'cols' );
1658 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1659 $wgOut->addHtml( '<hr />' );
1660 $wgOut->addWikiMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() );
1661 # Why we don't use Xml::element here?
1662 # Is it because if $source is '', it returns <textarea />?
1663 $wgOut->addHtml( Xml::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml::closeElement( 'textarea' ) );
1664 }
1665 }
1666
1667 /**
1668 * Produce the stock "please login to edit pages" page
1669 */
1670 function userNotLoggedInPage() {
1671 global $wgUser, $wgOut, $wgTitle;
1672 $skin = $wgUser->getSkin();
1673
1674 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1675 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1676
1677 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1678 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1679 $wgOut->setArticleRelated( false );
1680
1681 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1682 $wgOut->returnToMain( false, $wgTitle );
1683 }
1684
1685 /**
1686 * Creates a basic error page which informs the user that
1687 * they have attempted to edit a nonexistant section.
1688 */
1689 function noSuchSectionPage() {
1690 global $wgOut, $wgTitle;
1691
1692 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1693 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1694 $wgOut->setArticleRelated( false );
1695
1696 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section );
1697 $wgOut->returnToMain( false, $wgTitle );
1698 }
1699
1700 /**
1701 * Produce the stock "your edit contains spam" page
1702 *
1703 * @param $match Text which triggered one or more filters
1704 */
1705 function spamPage( $match = false ) {
1706 global $wgOut, $wgTitle;
1707
1708 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1709 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1710 $wgOut->setArticleRelated( false );
1711
1712 $wgOut->addHtml( '<div id="spamprotected">' );
1713 $wgOut->addWikiMsg( 'spamprotectiontext' );
1714 if ( $match )
1715 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1716 $wgOut->addHtml( '</div>' );
1717
1718 $wgOut->returnToMain( false, $wgTitle );
1719 }
1720
1721 /**
1722 * @private
1723 * @todo document
1724 */
1725 function mergeChangesInto( &$editText ){
1726 $fname = 'EditPage::mergeChangesInto';
1727 wfProfileIn( $fname );
1728
1729 $db = wfGetDB( DB_MASTER );
1730
1731 // This is the revision the editor started from
1732 $baseRevision = $this->getBaseRevision();
1733 if( is_null( $baseRevision ) ) {
1734 wfProfileOut( $fname );
1735 return false;
1736 }
1737 $baseText = $baseRevision->getText();
1738
1739 // The current state, we want to merge updates into it
1740 $currentRevision = Revision::loadFromTitle(
1741 $db, $this->mTitle );
1742 if( is_null( $currentRevision ) ) {
1743 wfProfileOut( $fname );
1744 return false;
1745 }
1746 $currentText = $currentRevision->getText();
1747
1748 $result = '';
1749 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1750 $editText = $result;
1751 wfProfileOut( $fname );
1752 return true;
1753 } else {
1754 wfProfileOut( $fname );
1755 return false;
1756 }
1757 }
1758
1759 /**
1760 * Check if the browser is on a blacklist of user-agents known to
1761 * mangle UTF-8 data on form submission. Returns true if Unicode
1762 * should make it through, false if it's known to be a problem.
1763 * @return bool
1764 * @private
1765 */
1766 function checkUnicodeCompliantBrowser() {
1767 global $wgBrowserBlackList;
1768 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1769 // No User-Agent header sent? Trust it by default...
1770 return true;
1771 }
1772 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1773 foreach ( $wgBrowserBlackList as $browser ) {
1774 if ( preg_match($browser, $currentbrowser) ) {
1775 return false;
1776 }
1777 }
1778 return true;
1779 }
1780
1781 /**
1782 * @deprecated use $wgParser->stripSectionName()
1783 */
1784 function pseudoParseSectionAnchor( $text ) {
1785 global $wgParser;
1786 return $wgParser->stripSectionName( $text );
1787 }
1788
1789 /**
1790 * Format an anchor fragment as it would appear for a given section name
1791 * @param string $text
1792 * @return string
1793 * @private
1794 */
1795 function sectionAnchor( $text ) {
1796 global $wgParser;
1797 return $wgParser->guessSectionNameFromWikiText( $text );
1798 }
1799
1800 /**
1801 * Shows a bulletin board style toolbar for common editing functions.
1802 * It can be disabled in the user preferences.
1803 * The necessary JavaScript code can be found in skins/common/edit.js.
1804 *
1805 * @return string
1806 */
1807 static function getEditToolbar() {
1808 global $wgStylePath, $wgContLang, $wgLang, $wgJsMimeType;
1809
1810 /**
1811 * toolarray an array of arrays which each include the filename of
1812 * the button image (without path), the opening tag, the closing tag,
1813 * and optionally a sample text that is inserted between the two when no
1814 * selection is highlighted.
1815 * The tip text is shown when the user moves the mouse over the button.
1816 *
1817 * Already here are accesskeys (key), which are not used yet until someone
1818 * can figure out a way to make them work in IE. However, we should make
1819 * sure these keys are not defined on the edit page.
1820 */
1821 $toolarray = array(
1822 array(
1823 'image' => $wgLang->getImageFile('button-bold'),
1824 'id' => 'mw-editbutton-bold',
1825 'open' => '\'\'\'',
1826 'close' => '\'\'\'',
1827 'sample' => wfMsg('bold_sample'),
1828 'tip' => wfMsg('bold_tip'),
1829 'key' => 'B'
1830 ),
1831 array(
1832 'image' => $wgLang->getImageFile('button-italic'),
1833 'id' => 'mw-editbutton-italic',
1834 'open' => '\'\'',
1835 'close' => '\'\'',
1836 'sample' => wfMsg('italic_sample'),
1837 'tip' => wfMsg('italic_tip'),
1838 'key' => 'I'
1839 ),
1840 array(
1841 'image' => $wgLang->getImageFile('button-link'),
1842 'id' => 'mw-editbutton-link',
1843 'open' => '[[',
1844 'close' => ']]',
1845 'sample' => wfMsg('link_sample'),
1846 'tip' => wfMsg('link_tip'),
1847 'key' => 'L'
1848 ),
1849 array(
1850 'image' => $wgLang->getImageFile('button-extlink'),
1851 'id' => 'mw-editbutton-extlink',
1852 'open' => '[',
1853 'close' => ']',
1854 'sample' => wfMsg('extlink_sample'),
1855 'tip' => wfMsg('extlink_tip'),
1856 'key' => 'X'
1857 ),
1858 array(
1859 'image' => $wgLang->getImageFile('button-headline'),
1860 'id' => 'mw-editbutton-headline',
1861 'open' => "\n== ",
1862 'close' => " ==\n",
1863 'sample' => wfMsg('headline_sample'),
1864 'tip' => wfMsg('headline_tip'),
1865 'key' => 'H'
1866 ),
1867 array(
1868 'image' => $wgLang->getImageFile('button-image'),
1869 'id' => 'mw-editbutton-image',
1870 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).':',
1871 'close' => ']]',
1872 'sample' => wfMsg('image_sample'),
1873 'tip' => wfMsg('image_tip'),
1874 'key' => 'D'
1875 ),
1876 array(
1877 'image' => $wgLang->getImageFile('button-media'),
1878 'id' => 'mw-editbutton-media',
1879 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1880 'close' => ']]',
1881 'sample' => wfMsg('media_sample'),
1882 'tip' => wfMsg('media_tip'),
1883 'key' => 'M'
1884 ),
1885 array(
1886 'image' => $wgLang->getImageFile('button-math'),
1887 'id' => 'mw-editbutton-math',
1888 'open' => "<math>",
1889 'close' => "</math>",
1890 'sample' => wfMsg('math_sample'),
1891 'tip' => wfMsg('math_tip'),
1892 'key' => 'C'
1893 ),
1894 array(
1895 'image' => $wgLang->getImageFile('button-nowiki'),
1896 'id' => 'mw-editbutton-nowiki',
1897 'open' => "<nowiki>",
1898 'close' => "</nowiki>",
1899 'sample' => wfMsg('nowiki_sample'),
1900 'tip' => wfMsg('nowiki_tip'),
1901 'key' => 'N'
1902 ),
1903 array(
1904 'image' => $wgLang->getImageFile('button-sig'),
1905 'id' => 'mw-editbutton-signature',
1906 'open' => '--~~~~',
1907 'close' => '',
1908 'sample' => '',
1909 'tip' => wfMsg('sig_tip'),
1910 'key' => 'Y'
1911 ),
1912 array(
1913 'image' => $wgLang->getImageFile('button-hr'),
1914 'id' => 'mw-editbutton-hr',
1915 'open' => "\n----\n",
1916 'close' => '',
1917 'sample' => '',
1918 'tip' => wfMsg('hr_tip'),
1919 'key' => 'R'
1920 )
1921 );
1922 $toolbar = "<div id='toolbar'>\n";
1923 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1924
1925 foreach($toolarray as $tool) {
1926 $params = array(
1927 $image = $wgStylePath.'/common/images/'.$tool['image'],
1928 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1929 // Older browsers show a "speedtip" type message only for ALT.
1930 // Ideally these should be different, realistically they
1931 // probably don't need to be.
1932 $tip = $tool['tip'],
1933 $open = $tool['open'],
1934 $close = $tool['close'],
1935 $sample = $tool['sample'],
1936 $cssId = $tool['id'],
1937 );
1938
1939 $paramList = implode( ',',
1940 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
1941 $toolbar.="addButton($paramList);\n";
1942 }
1943
1944 $toolbar.="/*]]>*/\n</script>";
1945 $toolbar.="\n</div>";
1946 return $toolbar;
1947 }
1948
1949 /**
1950 * Returns an array of html code of the following checkboxes:
1951 * minor and watch
1952 *
1953 * @param $tabindex Current tabindex
1954 * @param $skin Skin object
1955 * @param $checked Array of checkbox => bool, where bool indicates the checked
1956 * status of the checkbox
1957 *
1958 * @return array
1959 */
1960 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1961 global $wgUser;
1962
1963 $checkboxes = array();
1964
1965 $checkboxes['minor'] = '';
1966 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1967 if ( $wgUser->isAllowed('minoredit') ) {
1968 $attribs = array(
1969 'tabindex' => ++$tabindex,
1970 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1971 'id' => 'wpMinoredit',
1972 );
1973 $checkboxes['minor'] =
1974 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1975 "&nbsp;<label for='wpMinoredit'".$skin->tooltip('minoredit').">{$minorLabel}</label>";
1976 }
1977
1978 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1979 $checkboxes['watch'] = '';
1980 if ( $wgUser->isLoggedIn() ) {
1981 $attribs = array(
1982 'tabindex' => ++$tabindex,
1983 'accesskey' => wfMsg( 'accesskey-watch' ),
1984 'id' => 'wpWatchthis',
1985 );
1986 $checkboxes['watch'] =
1987 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1988 "&nbsp;<label for='wpWatchthis'".$skin->tooltip('watch').">{$watchLabel}</label>";
1989 }
1990 return $checkboxes;
1991 }
1992
1993 /**
1994 * Returns an array of html code of the following buttons:
1995 * save, diff, preview and live
1996 *
1997 * @param $tabindex Current tabindex
1998 *
1999 * @return array
2000 */
2001 public function getEditButtons(&$tabindex) {
2002 global $wgLivePreview, $wgUser;
2003
2004 $buttons = array();
2005
2006 $temp = array(
2007 'id' => 'wpSave',
2008 'name' => 'wpSave',
2009 'type' => 'submit',
2010 'tabindex' => ++$tabindex,
2011 'value' => wfMsg('savearticle'),
2012 'accesskey' => wfMsg('accesskey-save'),
2013 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2014 );
2015 $buttons['save'] = Xml::element('input', $temp, '');
2016
2017 ++$tabindex; // use the same for preview and live preview
2018 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
2019 $temp = array(
2020 'id' => 'wpPreview',
2021 'name' => 'wpPreview',
2022 'type' => 'submit',
2023 'tabindex' => $tabindex,
2024 'value' => wfMsg('showpreview'),
2025 'accesskey' => '',
2026 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2027 'style' => 'display: none;',
2028 );
2029 $buttons['preview'] = Xml::element('input', $temp, '');
2030
2031 $temp = array(
2032 'id' => 'wpLivePreview',
2033 'name' => 'wpLivePreview',
2034 'type' => 'submit',
2035 'tabindex' => $tabindex,
2036 'value' => wfMsg('showlivepreview'),
2037 'accesskey' => wfMsg('accesskey-preview'),
2038 'title' => '',
2039 'onclick' => $this->doLivePreviewScript(),
2040 );
2041 $buttons['live'] = Xml::element('input', $temp, '');
2042 } else {
2043 $temp = array(
2044 'id' => 'wpPreview',
2045 'name' => 'wpPreview',
2046 'type' => 'submit',
2047 'tabindex' => $tabindex,
2048 'value' => wfMsg('showpreview'),
2049 'accesskey' => wfMsg('accesskey-preview'),
2050 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2051 );
2052 $buttons['preview'] = Xml::element('input', $temp, '');
2053 $buttons['live'] = '';
2054 }
2055
2056 $temp = array(
2057 'id' => 'wpDiff',
2058 'name' => 'wpDiff',
2059 'type' => 'submit',
2060 'tabindex' => ++$tabindex,
2061 'value' => wfMsg('showdiff'),
2062 'accesskey' => wfMsg('accesskey-diff'),
2063 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2064 );
2065 $buttons['diff'] = Xml::element('input', $temp, '');
2066
2067 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons ) );
2068 return $buttons;
2069 }
2070
2071 /**
2072 * Output preview text only. This can be sucked into the edit page
2073 * via JavaScript, and saves the server time rendering the skin as
2074 * well as theoretically being more robust on the client (doesn't
2075 * disturb the edit box's undo history, won't eat your text on
2076 * failure, etc).
2077 *
2078 * @todo This doesn't include category or interlanguage links.
2079 * Would need to enhance it a bit, <s>maybe wrap them in XML
2080 * or something...</s> that might also require more skin
2081 * initialization, so check whether that's a problem.
2082 */
2083 function livePreview() {
2084 global $wgOut;
2085 $wgOut->disable();
2086 header( 'Content-type: text/xml; charset=utf-8' );
2087 header( 'Cache-control: no-cache' );
2088
2089 $previewText = $this->getPreviewText();
2090 #$categories = $skin->getCategoryLinks();
2091
2092 $s =
2093 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2094 Xml::tags( 'livepreview', null,
2095 Xml::element( 'preview', null, $previewText )
2096 #. Xml::element( 'category', null, $categories )
2097 );
2098 echo $s;
2099 }
2100
2101
2102 /**
2103 * Get a diff between the current contents of the edit box and the
2104 * version of the page we're editing from.
2105 *
2106 * If this is a section edit, we'll replace the section as for final
2107 * save and then make a comparison.
2108 */
2109 function showDiff() {
2110 $oldtext = $this->mArticle->fetchContent();
2111 $newtext = $this->mArticle->replaceSection(
2112 $this->section, $this->textbox1, $this->summary, $this->edittime );
2113 $newtext = $this->mArticle->preSaveTransform( $newtext );
2114 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2115 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2116 if ( $oldtext !== false || $newtext != '' ) {
2117 $de = new DifferenceEngine( $this->mTitle );
2118 $de->setText( $oldtext, $newtext );
2119 $difftext = $de->getDiff( $oldtitle, $newtitle );
2120 $de->showDiffStyle();
2121 } else {
2122 $difftext = '';
2123 }
2124
2125 global $wgOut;
2126 $wgOut->addHtml( '<div id="wikiDiff">' . $difftext . '</div>' );
2127 }
2128
2129 /**
2130 * Filter an input field through a Unicode de-armoring process if it
2131 * came from an old browser with known broken Unicode editing issues.
2132 *
2133 * @param WebRequest $request
2134 * @param string $field
2135 * @return string
2136 * @private
2137 */
2138 function safeUnicodeInput( $request, $field ) {
2139 $text = rtrim( $request->getText( $field ) );
2140 return $request->getBool( 'safemode' )
2141 ? $this->unmakesafe( $text )
2142 : $text;
2143 }
2144
2145 /**
2146 * Filter an output field through a Unicode armoring process if it is
2147 * going to an old browser with known broken Unicode editing issues.
2148 *
2149 * @param string $text
2150 * @return string
2151 * @private
2152 */
2153 function safeUnicodeOutput( $text ) {
2154 global $wgContLang;
2155 $codedText = $wgContLang->recodeForEdit( $text );
2156 return $this->checkUnicodeCompliantBrowser()
2157 ? $codedText
2158 : $this->makesafe( $codedText );
2159 }
2160
2161 /**
2162 * A number of web browsers are known to corrupt non-ASCII characters
2163 * in a UTF-8 text editing environment. To protect against this,
2164 * detected browsers will be served an armored version of the text,
2165 * with non-ASCII chars converted to numeric HTML character references.
2166 *
2167 * Preexisting such character references will have a 0 added to them
2168 * to ensure that round-trips do not alter the original data.
2169 *
2170 * @param string $invalue
2171 * @return string
2172 * @private
2173 */
2174 function makesafe( $invalue ) {
2175 // Armor existing references for reversability.
2176 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
2177
2178 $bytesleft = 0;
2179 $result = "";
2180 $working = 0;
2181 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2182 $bytevalue = ord( $invalue{$i} );
2183 if( $bytevalue <= 0x7F ) { //0xxx xxxx
2184 $result .= chr( $bytevalue );
2185 $bytesleft = 0;
2186 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
2187 $working = $working << 6;
2188 $working += ($bytevalue & 0x3F);
2189 $bytesleft--;
2190 if( $bytesleft <= 0 ) {
2191 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2192 }
2193 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
2194 $working = $bytevalue & 0x1F;
2195 $bytesleft = 1;
2196 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
2197 $working = $bytevalue & 0x0F;
2198 $bytesleft = 2;
2199 } else { //1111 0xxx
2200 $working = $bytevalue & 0x07;
2201 $bytesleft = 3;
2202 }
2203 }
2204 return $result;
2205 }
2206
2207 /**
2208 * Reverse the previously applied transliteration of non-ASCII characters
2209 * back to UTF-8. Used to protect data from corruption by broken web browsers
2210 * as listed in $wgBrowserBlackList.
2211 *
2212 * @param string $invalue
2213 * @return string
2214 * @private
2215 */
2216 function unmakesafe( $invalue ) {
2217 $result = "";
2218 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2219 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
2220 $i += 3;
2221 $hexstring = "";
2222 do {
2223 $hexstring .= $invalue{$i};
2224 $i++;
2225 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2226
2227 // Do some sanity checks. These aren't needed for reversability,
2228 // but should help keep the breakage down if the editor
2229 // breaks one of the entities whilst editing.
2230 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2231 $codepoint = hexdec($hexstring);
2232 $result .= codepointToUtf8( $codepoint );
2233 } else {
2234 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2235 }
2236 } else {
2237 $result .= substr( $invalue, $i, 1 );
2238 }
2239 }
2240 // reverse the transform that we made for reversability reasons.
2241 return strtr( $result, array( "&#x0" => "&#x" ) );
2242 }
2243
2244 function noCreatePermission() {
2245 global $wgOut;
2246 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2247 $wgOut->addWikiMsg( 'nocreatetext' );
2248 }
2249
2250 /**
2251 * If there are rows in the deletion log for this page, show them,
2252 * along with a nice little note for the user
2253 *
2254 * @param OutputPage $out
2255 */
2256 protected function showDeletionLog( $out ) {
2257 global $wgUser;
2258 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
2259 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle->getPrefixedText() );
2260 if( $pager->getNumRows() > 0 ) {
2261 $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
2262 $out->addWikiMsg( 'recreate-deleted-warn' );
2263 $out->addHTML(
2264 $loglist->beginLogEventsList() .
2265 $pager->getBody() .
2266 $loglist->endLogEventsList()
2267 );
2268 $out->addHtml( '</div>' );
2269 }
2270 }
2271
2272 /**
2273 * Attempt submission
2274 * @return bool false if output is done, true if the rest of the form should be displayed
2275 */
2276 function attemptSave() {
2277 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2278
2279 $resultDetails = false;
2280 $value = $this->internalAttemptSave( $resultDetails, $wgUser->isAllowed('bot') && $wgRequest->getBool('bot', true) );
2281
2282 if( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) {
2283 $this->didSave = true;
2284 }
2285
2286 switch ($value) {
2287 case self::AS_HOOK_ERROR_EXPECTED:
2288 case self::AS_CONTENT_TOO_BIG:
2289 case self::AS_ARTICLE_WAS_DELETED:
2290 case self::AS_CONFLICT_DETECTED:
2291 case self::AS_SUMMARY_NEEDED:
2292 case self::AS_TEXTBOX_EMPTY:
2293 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
2294 case self::AS_END:
2295 return true;
2296
2297 case self::AS_HOOK_ERROR:
2298 case self::AS_FILTERING:
2299 case self::AS_SUCCESS_NEW_ARTICLE:
2300 case self::AS_SUCCESS_UPDATE:
2301 return false;
2302
2303 case self::AS_SPAM_ERROR:
2304 $this->spamPage ( $resultDetails['spam'] );
2305 return false;
2306
2307 case self::AS_BLOCKED_PAGE_FOR_USER:
2308 $this->blockedPage();
2309 return false;
2310
2311 case self::AS_IMAGE_REDIRECT_ANON:
2312 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2313 return false;
2314
2315 case self::AS_READ_ONLY_PAGE_ANON:
2316 $this->userNotLoggedInPage();
2317 return false;
2318
2319 case self::AS_READ_ONLY_PAGE_LOGGED:
2320 case self::AS_READ_ONLY_PAGE:
2321 $wgOut->readOnlyPage();
2322 return false;
2323
2324 case self::AS_RATE_LIMITED:
2325 $wgOut->rateLimited();
2326 return false;
2327
2328 case self::AS_NO_CREATE_PERMISSION;
2329 $this->noCreatePermission();
2330 return;
2331
2332 case self::AS_BLANK_ARTICLE:
2333 $wgOut->redirect( $wgTitle->getFullURL() );
2334 return false;
2335
2336 case self::AS_IMAGE_REDIRECT_LOGGED:
2337 $wgOut->permissionRequired( 'upload' );
2338 return false;
2339 }
2340 }
2341
2342 function getBaseRevision() {
2343 if ($this->mBaseRevision == false) {
2344 $db = wfGetDB( DB_MASTER );
2345 $baseRevision = Revision::loadFromTimestamp(
2346 $db, $this->mTitle, $this->edittime );
2347 return $this->mBaseRevision = $baseRevision;
2348 } else {
2349 return $this->mBaseRevision;
2350 }
2351 }
2352 }