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