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