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