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