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