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