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