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