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