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