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