Directionality improvements as part of bug 6100 (under $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 ) );
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 global $wgUser;
1638 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
1639 $inputAttrs = ( is_array($inputAttrs) ? $inputAttrs : array() ) + array(
1640 'id' => 'wpSummary',
1641 'maxlength' => '200',
1642 'tabindex' => '1',
1643 'size' => 60,
1644 'spellcheck' => 'true',
1645 ) + $wgUser->getSkin()->tooltipAndAccessKeyAttribs( 'summary' );
1646
1647 $spanLabelAttrs = ( is_array($spanLabelAttrs) ? $spanLabelAttrs : array() ) + array(
1648 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
1649 'id' => "wpSummaryLabel"
1650 );
1651
1652 $label = null;
1653 if ( $labelText ) {
1654 $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
1655 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
1656 }
1657
1658 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
1659
1660 return array( $label, $input );
1661 }
1662
1663 /**
1664 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1665 * up top, or false if this is the comment summary
1666 * down below the textarea
1667 * @param $summary String: The text of the summary to display
1668 * @return String
1669 */
1670 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
1671 global $wgOut, $wgContLang;
1672 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1673 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
1674 if ( $isSubjectPreview ) {
1675 if ( $this->nosummary ) {
1676 return;
1677 }
1678 } else {
1679 if ( !$this->mShowSummaryField ) {
1680 return;
1681 }
1682 }
1683 $summary = $wgContLang->recodeForEdit( $summary );
1684 $labelText = wfMsgExt( $isSubjectPreview ? 'subject' : 'summary', 'parseinline' );
1685 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
1686 $wgOut->addHTML("{$label} {$input}");
1687 }
1688
1689 /**
1690 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1691 * up top, or false if this is the comment summary
1692 * down below the textarea
1693 * @param $summary String: the text of the summary to display
1694 * @return String
1695 */
1696 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
1697 if ( !$summary || ( !$this->preview && !$this->diff ) )
1698 return "";
1699
1700 global $wgParser, $wgUser;
1701 $sk = $wgUser->getSkin();
1702
1703 if ( $isSubjectPreview )
1704 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
1705
1706 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
1707
1708 $summary = wfMsgExt( $message, 'parseinline' ) . $sk->commentBlock( $summary, $this->mTitle, $isSubjectPreview );
1709 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
1710 }
1711
1712 protected function showFormBeforeText() {
1713 global $wgOut;
1714 $section = htmlspecialchars( $this->section );
1715 $wgOut->addHTML( <<<HTML
1716 <input type='hidden' value="{$section}" name="wpSection" />
1717 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
1718 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
1719 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
1720
1721 HTML
1722 );
1723 if ( !$this->checkUnicodeCompliantBrowser() )
1724 $wgOut->addHTML(Html::hidden( 'safemode', '1' ));
1725 }
1726
1727 protected function showFormAfterText() {
1728 global $wgOut, $wgUser;
1729 /**
1730 * To make it harder for someone to slip a user a page
1731 * which submits an edit form to the wiki without their
1732 * knowledge, a random token is associated with the login
1733 * session. If it's not passed back with the submission,
1734 * we won't save the page, or render user JavaScript and
1735 * CSS previews.
1736 *
1737 * For anon editors, who may not have a session, we just
1738 * include the constant suffix to prevent editing from
1739 * broken text-mangling proxies.
1740 */
1741 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->editToken() ) . "\n" );
1742 }
1743
1744 /**
1745 * Subpage overridable method for printing the form for page content editing
1746 * By default this simply outputs wpTextbox1
1747 * Subclasses can override this to provide a custom UI for editing;
1748 * be it a form, or simply wpTextbox1 with a modified content that will be
1749 * reverse modified when extracted from the post data.
1750 * Note that this is basically the inverse for importContentFormData
1751 */
1752 protected function showContentForm() {
1753 $this->showTextbox1();
1754 }
1755
1756 /**
1757 * Method to output wpTextbox1
1758 * The $textoverride method can be used by subclasses overriding showContentForm
1759 * to pass back to this method.
1760 *
1761 * @param $customAttribs An array of html attributes to use in the textarea
1762 * @param $textoverride String: optional text to override $this->textarea1 with
1763 */
1764 protected function showTextbox1($customAttribs = null, $textoverride = null) {
1765 $classes = array(); // Textarea CSS
1766 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
1767 # Is the title semi-protected?
1768 if ( $this->mTitle->isSemiProtected() ) {
1769 $classes[] = 'mw-textarea-sprotected';
1770 } else {
1771 # Then it must be protected based on static groups (regular)
1772 $classes[] = 'mw-textarea-protected';
1773 }
1774 # Is the title cascade-protected?
1775 if ( $this->mTitle->isCascadeProtected() ) {
1776 $classes[] = 'mw-textarea-cprotected';
1777 }
1778 }
1779 $attribs = array( 'tabindex' => 1 );
1780 if ( is_array($customAttribs) )
1781 $attribs += $customAttribs;
1782
1783 if ( $this->wasDeletedSinceLastEdit() )
1784 $attribs['type'] = 'hidden';
1785 if ( !empty( $classes ) ) {
1786 if ( isset($attribs['class']) )
1787 $classes[] = $attribs['class'];
1788 $attribs['class'] = implode( ' ', $classes );
1789 }
1790
1791 $this->showTextbox( isset($textoverride) ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
1792 }
1793
1794 protected function showTextbox2() {
1795 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
1796 }
1797
1798 protected function showTextbox( $content, $name, $customAttribs = array() ) {
1799 global $wgOut, $wgUser;
1800
1801 $wikitext = $this->safeUnicodeOutput( $content );
1802 if ( $wikitext !== '' ) {
1803 // Ensure there's a newline at the end, otherwise adding lines
1804 // is awkward.
1805 // But don't add a newline if the ext is empty, or Firefox in XHTML
1806 // mode will show an extra newline. A bit annoying.
1807 $wikitext .= "\n";
1808 }
1809
1810 $attribs = $customAttribs + array(
1811 'accesskey' => ',',
1812 'id' => $name,
1813 'cols' => $wgUser->getIntOption( 'cols' ),
1814 'rows' => $wgUser->getIntOption( 'rows' ),
1815 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
1816 );
1817
1818 global $wgBetterDirectionality;
1819 if( $wgBetterDirectionality ) {
1820 $pageLang = $this->mTitle->getPageLanguage();
1821 $attribs['lang'] = $pageLang->getCode();
1822 $attribs['dir'] = $pageLang->getDir();
1823 }
1824
1825 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
1826 }
1827
1828 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1829 global $wgOut;
1830 $classes = array();
1831 if ( $isOnTop )
1832 $classes[] = 'ontop';
1833
1834 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1835
1836 if ( $this->formtype != 'preview' )
1837 $attribs['style'] = 'display: none;';
1838
1839 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
1840
1841 if ( $this->formtype == 'preview' ) {
1842 $this->showPreview( $previewOutput );
1843 }
1844
1845 $wgOut->addHTML( '</div>' );
1846
1847 if ( $this->formtype == 'diff') {
1848 $this->showDiff();
1849 }
1850 }
1851
1852 /**
1853 * Append preview output to $wgOut.
1854 * Includes category rendering if this is a category page.
1855 *
1856 * @param $text String: the HTML to be output for the preview.
1857 */
1858 protected function showPreview( $text ) {
1859 global $wgOut;
1860 if ( $this->mTitle->getNamespace() == NS_CATEGORY) {
1861 $this->mArticle->openShowCategory();
1862 }
1863 # This hook seems slightly odd here, but makes things more
1864 # consistent for extensions.
1865 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1866 $wgOut->addHTML( $text );
1867 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1868 $this->mArticle->closeShowCategory();
1869 }
1870 }
1871
1872 /**
1873 * Give a chance for site and per-namespace customizations of
1874 * terms of service summary link that might exist separately
1875 * from the copyright notice.
1876 *
1877 * This will display between the save button and the edit tools,
1878 * so should remain short!
1879 */
1880 protected function showTosSummary() {
1881 $msg = 'editpage-tos-summary';
1882 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
1883 if( !wfMessage( $msg )->isDisabled() ) {
1884 global $wgOut;
1885 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1886 $wgOut->addWikiMsgArray( $msg, array() );
1887 $wgOut->addHTML( '</div>' );
1888 }
1889 }
1890
1891 protected function showEditTools() {
1892 global $wgOut;
1893 $wgOut->addHTML( '<div class="mw-editTools">' );
1894 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1895 $wgOut->addHTML( '</div>' );
1896 }
1897
1898 protected function getCopywarn() {
1899 global $wgRightsText;
1900 if ( $wgRightsText ) {
1901 $copywarnMsg = array( 'copyrightwarning',
1902 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1903 $wgRightsText );
1904 } else {
1905 $copywarnMsg = array( 'copyrightwarning2',
1906 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1907 }
1908 // Allow for site and per-namespace customization of contribution/copyright notice.
1909 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle, &$copywarnMsg ) );
1910
1911 return "<div id=\"editpage-copywarn\">\n" .
1912 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
1913 }
1914
1915 protected function showStandardInputs( &$tabindex = 2 ) {
1916 global $wgOut, $wgUser;
1917 $wgOut->addHTML( "<div class='editOptions'>\n" );
1918
1919 if ( $this->section != 'new' ) {
1920 $this->showSummaryInput( false, $this->summary );
1921 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
1922 }
1923
1924 $checkboxes = $this->getCheckboxes( $tabindex, $wgUser->getSkin(),
1925 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1926 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
1927 $wgOut->addHTML( "<div class='editButtons'>\n" );
1928 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
1929
1930 $cancel = $this->getCancelLink();
1931 $separator = wfMsgExt( 'pipe-separator' , 'escapenoentities' );
1932 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
1933 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1934 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1935 htmlspecialchars( wfMsg( 'newwindow' ) );
1936 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$separator}{$edithelp}</span>\n" );
1937 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
1938 }
1939
1940 /**
1941 * Show an edit conflict. textbox1 is already shown in showEditForm().
1942 * If you want to use another entry point to this function, be careful.
1943 */
1944 protected function showConflict() {
1945 global $wgOut;
1946 $this->textbox2 = $this->textbox1;
1947 $this->textbox1 = $this->getContent();
1948 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1949 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
1950
1951 $de = new DifferenceEngine( $this->mTitle );
1952 $de->setText( $this->textbox2, $this->textbox1 );
1953 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1954
1955 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
1956 $this->showTextbox2();
1957 }
1958 }
1959
1960 protected function getLastDelete() {
1961 $dbr = wfGetDB( DB_SLAVE );
1962 $data = $dbr->selectRow(
1963 array( 'logging', 'user' ),
1964 array( 'log_type',
1965 'log_action',
1966 'log_timestamp',
1967 'log_user',
1968 'log_namespace',
1969 'log_title',
1970 'log_comment',
1971 'log_params',
1972 'log_deleted',
1973 'user_name' ),
1974 array( 'log_namespace' => $this->mTitle->getNamespace(),
1975 'log_title' => $this->mTitle->getDBkey(),
1976 'log_type' => 'delete',
1977 'log_action' => 'delete',
1978 'user_id=log_user' ),
1979 __METHOD__,
1980 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1981 );
1982 // Quick paranoid permission checks...
1983 if( is_object( $data ) ) {
1984 if( $data->log_deleted & LogPage::DELETED_USER )
1985 $data->user_name = wfMsgHtml( 'rev-deleted-user' );
1986 if( $data->log_deleted & LogPage::DELETED_COMMENT )
1987 $data->log_comment = wfMsgHtml( 'rev-deleted-comment' );
1988 }
1989 return $data;
1990 }
1991
1992 /**
1993 * Get the rendered text for previewing.
1994 * @return string
1995 */
1996 function getPreviewText() {
1997 global $wgOut, $wgUser, $wgParser;
1998
1999 wfProfileIn( __METHOD__ );
2000
2001 if ( $this->mTriedSave && !$this->mTokenOk ) {
2002 if ( $this->mTokenOkExceptSuffix ) {
2003 $note = wfMsg( 'token_suffix_mismatch' );
2004 } else {
2005 $note = wfMsg( 'session_fail_preview' );
2006 }
2007 } elseif ( $this->incompleteForm ) {
2008 $note = wfMsg( 'edit_form_incomplete' );
2009 } else {
2010 $note = wfMsg( 'previewnote' );
2011 }
2012
2013 $parserOptions = ParserOptions::newFromUser( $wgUser );
2014 $parserOptions->setEditSection( false );
2015 $parserOptions->setIsPreview( true );
2016 $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' );
2017
2018 global $wgRawHtml;
2019 if ( $wgRawHtml && !$this->mTokenOk ) {
2020 // Could be an offsite preview attempt. This is very unsafe if
2021 // HTML is enabled, as it could be an attack.
2022 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2023 wfMsg( 'session_fail_preview_html' ) . "</div>" );
2024 wfProfileOut( __METHOD__ );
2025 return $parsedNote;
2026 }
2027
2028 # don't parse user css/js, show message about preview
2029 # 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?
2030
2031 if ( $this->isCssJsSubpage || $this->mTitle->isCssOrJsPage() ) {
2032 $level = 'user';
2033 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2034 $level = 'site';
2035 }
2036
2037 # Used messages to make sure grep find them:
2038 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2039 if (preg_match( "/\\.css$/", $this->mTitle->getText() ) ) {
2040 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2041 $class = "mw-code mw-css";
2042 } elseif (preg_match( "/\\.js$/", $this->mTitle->getText() ) ) {
2043 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2044 $class = "mw-code mw-js";
2045 } else {
2046 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2047 }
2048
2049 $parserOptions->setTidy( true );
2050 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
2051 $previewHTML = $parserOutput->mText;
2052 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1 ) . "\n</pre>\n";
2053 } else {
2054 $rt = Title::newFromRedirectArray( $this->textbox1 );
2055 if ( $rt ) {
2056 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
2057 } else {
2058 $toparse = $this->textbox1;
2059
2060 # If we're adding a comment, we need to show the
2061 # summary as the headline
2062 if ( $this->section == "new" && $this->summary != "" ) {
2063 $toparse = "== {$this->summary} ==\n\n" . $toparse;
2064 }
2065
2066 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2067
2068 // In which language to parse the page
2069 // (Should this still be only for MediaWiki pages, or for all pages?)
2070 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2071 $parserOptions->setTargetLanguage( $this->mTitle->getPageLanguage() );
2072 }
2073 $parserOptions->setTidy( true );
2074 $parserOptions->enableLimitReport();
2075 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ),
2076 $this->mTitle, $parserOptions );
2077
2078 $previewHTML = $parserOutput->getText();
2079 $this->mParserOutput = $parserOutput;
2080 $wgOut->addParserOutputNoText( $parserOutput );
2081
2082 if ( count( $parserOutput->getWarnings() ) ) {
2083 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2084 }
2085 }
2086 }
2087
2088 if( $this->isConflict ) {
2089 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2090 } else {
2091 $conflict = '<hr />';
2092 }
2093
2094 $previewhead = "<div class='previewnote'>\n" .
2095 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2096 $wgOut->parse( $note ) . $conflict . "</div>\n";
2097
2098 global $wgBetterDirectionality;
2099 if( $wgBetterDirectionality ) {
2100 $pageLang = $this->mTitle->getPageLanguage();
2101 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2102 'class' => 'mw-content-'.$pageLang->getDir() );
2103 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
2104 }
2105 wfProfileOut( __METHOD__ );
2106 return $previewhead . $previewHTML . $this->previewTextAfterContent;
2107 }
2108
2109 /**
2110 * @return Array
2111 */
2112 function getTemplates() {
2113 if ( $this->preview || $this->section != '' ) {
2114 $templates = array();
2115 if ( !isset( $this->mParserOutput ) ) {
2116 return $templates;
2117 }
2118 foreach( $this->mParserOutput->getTemplates() as $ns => $template) {
2119 foreach( array_keys( $template ) as $dbk ) {
2120 $templates[] = Title::makeTitle($ns, $dbk);
2121 }
2122 }
2123 return $templates;
2124 } else {
2125 return $this->mArticle->getUsedTemplates();
2126 }
2127 }
2128
2129 /**
2130 * Call the stock "user is blocked" page
2131 */
2132 function blockedPage() {
2133 global $wgOut;
2134 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
2135
2136 # If the user made changes, preserve them when showing the markup
2137 # (This happens when a user is blocked during edit, for instance)
2138 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
2139 if ( $first ) {
2140 $source = $this->mTitle->exists() ? $this->getContent() : false;
2141 } else {
2142 $source = $this->textbox1;
2143 }
2144
2145 # Spit out the source or the user's modified version
2146 if ( $source !== false ) {
2147 $wgOut->addHTML( '<hr />' );
2148 $wgOut->addWikiMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() );
2149 $this->showTextbox1( array( 'readonly' ), $source );
2150 }
2151 }
2152
2153 /**
2154 * Produce the stock "please login to edit pages" page
2155 */
2156 function userNotLoggedInPage() {
2157 global $wgUser, $wgOut;
2158 $skin = $wgUser->getSkin();
2159
2160 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
2161 $loginLink = $skin->link(
2162 $loginTitle,
2163 wfMsgHtml( 'loginreqlink' ),
2164 array(),
2165 array( 'returnto' => $this->getContextTitle()->getPrefixedText() ),
2166 array( 'known', 'noclasses' )
2167 );
2168
2169 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
2170 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2171 $wgOut->setArticleRelated( false );
2172
2173 $wgOut->addWikiMsgArray( 'whitelistedittext', array( $loginLink ), array( 'replaceafter' ) );
2174 $wgOut->returnToMain( false, $this->getContextTitle() );
2175 }
2176
2177 /**
2178 * Creates a basic error page which informs the user that
2179 * they have attempted to edit a nonexistent section.
2180 */
2181 function noSuchSectionPage() {
2182 global $wgOut;
2183
2184 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
2185 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2186 $wgOut->setArticleRelated( false );
2187
2188 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section );
2189 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
2190 $wgOut->addHTML( $res );
2191
2192 $wgOut->returnToMain( false, $this->mTitle );
2193 }
2194
2195 /**
2196 * Produce the stock "your edit contains spam" page
2197 *
2198 * @param $match Text which triggered one or more filters
2199 * @deprecated since 1.17 Use method spamPageWithContent() instead
2200 */
2201 static function spamPage( $match = false ) {
2202 global $wgOut, $wgTitle;
2203
2204 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
2205 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2206 $wgOut->setArticleRelated( false );
2207
2208 $wgOut->addHTML( '<div id="spamprotected">' );
2209 $wgOut->addWikiMsg( 'spamprotectiontext' );
2210 if ( $match ) {
2211 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2212 }
2213 $wgOut->addHTML( '</div>' );
2214
2215 $wgOut->returnToMain( false, $wgTitle );
2216 }
2217
2218 /**
2219 * Show "your edit contains spam" page with your diff and text
2220 *
2221 * @param $match Text which triggered one or more filters
2222 */
2223 public function spamPageWithContent( $match = false ) {
2224 global $wgOut;
2225 $this->textbox2 = $this->textbox1;
2226
2227 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
2228 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2229 $wgOut->setArticleRelated( false );
2230
2231 $wgOut->addHTML( '<div id="spamprotected">' );
2232 $wgOut->addWikiMsg( 'spamprotectiontext' );
2233 if ( $match ) {
2234 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2235 }
2236 $wgOut->addHTML( '</div>' );
2237
2238 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2239 $de = new DifferenceEngine( $this->mTitle );
2240 $de->setText( $this->getContent(), $this->textbox2 );
2241 $de->showDiff( wfMsg( "storedversion" ), wfMsg( "yourtext" ) );
2242
2243 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2244 $this->showTextbox2();
2245
2246 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
2247 }
2248
2249
2250 /**
2251 * @private
2252 * @todo document
2253 *
2254 * @parma $editText string
2255 *
2256 * @return bool
2257 */
2258 function mergeChangesInto( &$editText ){
2259 wfProfileIn( __METHOD__ );
2260
2261 $db = wfGetDB( DB_MASTER );
2262
2263 // This is the revision the editor started from
2264 $baseRevision = $this->getBaseRevision();
2265 if ( is_null( $baseRevision ) ) {
2266 wfProfileOut( __METHOD__ );
2267 return false;
2268 }
2269 $baseText = $baseRevision->getText();
2270
2271 // The current state, we want to merge updates into it
2272 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2273 if ( is_null( $currentRevision ) ) {
2274 wfProfileOut( __METHOD__ );
2275 return false;
2276 }
2277 $currentText = $currentRevision->getText();
2278
2279 $result = '';
2280 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
2281 $editText = $result;
2282 wfProfileOut( __METHOD__ );
2283 return true;
2284 } else {
2285 wfProfileOut( __METHOD__ );
2286 return false;
2287 }
2288 }
2289
2290 /**
2291 * Check if the browser is on a blacklist of user-agents known to
2292 * mangle UTF-8 data on form submission. Returns true if Unicode
2293 * should make it through, false if it's known to be a problem.
2294 * @return bool
2295 * @private
2296 */
2297 function checkUnicodeCompliantBrowser() {
2298 global $wgBrowserBlackList;
2299 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2300 // No User-Agent header sent? Trust it by default...
2301 return true;
2302 }
2303 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2304 foreach ( $wgBrowserBlackList as $browser ) {
2305 if ( preg_match($browser, $currentbrowser) ) {
2306 return false;
2307 }
2308 }
2309 return true;
2310 }
2311
2312 /**
2313 * Format an anchor fragment as it would appear for a given section name
2314 * @param $text String
2315 * @return String
2316 * @private
2317 */
2318 function sectionAnchor( $text ) {
2319 global $wgParser;
2320 return $wgParser->guessSectionNameFromWikiText( $text );
2321 }
2322
2323 /**
2324 * Shows a bulletin board style toolbar for common editing functions.
2325 * It can be disabled in the user preferences.
2326 * The necessary JavaScript code can be found in skins/common/edit.js.
2327 *
2328 * @return string
2329 */
2330 static function getEditToolbar() {
2331 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2332 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2333
2334 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
2335
2336 /**
2337 * $toolarray is an array of arrays each of which includes the
2338 * filename of the button image (without path), the opening
2339 * tag, the closing tag, optionally a sample text that is
2340 * inserted between the two when no selection is highlighted
2341 * and an option to select which switches the automatic
2342 * selection of inserted text (default is true, see
2343 * mw-editbutton-image). The tip text is shown when the user
2344 * moves the mouse over the button.
2345 *
2346 * Also here: accesskeys (key), which are not used yet until
2347 * someone can figure out a way to make them work in
2348 * IE. However, we should make sure these keys are not defined
2349 * on the edit page.
2350 */
2351 $toolarray = array(
2352 array(
2353 'image' => $wgLang->getImageFile( 'button-bold' ),
2354 'id' => 'mw-editbutton-bold',
2355 'open' => '\'\'\'',
2356 'close' => '\'\'\'',
2357 'sample' => wfMsg( 'bold_sample' ),
2358 'tip' => wfMsg( 'bold_tip' ),
2359 'key' => 'B'
2360 ),
2361 array(
2362 'image' => $wgLang->getImageFile( 'button-italic' ),
2363 'id' => 'mw-editbutton-italic',
2364 'open' => '\'\'',
2365 'close' => '\'\'',
2366 'sample' => wfMsg( 'italic_sample' ),
2367 'tip' => wfMsg( 'italic_tip' ),
2368 'key' => 'I'
2369 ),
2370 array(
2371 'image' => $wgLang->getImageFile( 'button-link' ),
2372 'id' => 'mw-editbutton-link',
2373 'open' => '[[',
2374 'close' => ']]',
2375 'sample' => wfMsg( 'link_sample' ),
2376 'tip' => wfMsg( 'link_tip' ),
2377 'key' => 'L'
2378 ),
2379 array(
2380 'image' => $wgLang->getImageFile( 'button-extlink' ),
2381 'id' => 'mw-editbutton-extlink',
2382 'open' => '[',
2383 'close' => ']',
2384 'sample' => wfMsg( 'extlink_sample' ),
2385 'tip' => wfMsg( 'extlink_tip' ),
2386 'key' => 'X'
2387 ),
2388 array(
2389 'image' => $wgLang->getImageFile( 'button-headline' ),
2390 'id' => 'mw-editbutton-headline',
2391 'open' => "\n== ",
2392 'close' => " ==\n",
2393 'sample' => wfMsg( 'headline_sample' ),
2394 'tip' => wfMsg( 'headline_tip' ),
2395 'key' => 'H'
2396 ),
2397 $imagesAvailable ? array(
2398 'image' => $wgLang->getImageFile( 'button-image' ),
2399 'id' => 'mw-editbutton-image',
2400 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
2401 'close' => ']]',
2402 'sample' => wfMsg( 'image_sample' ),
2403 'tip' => wfMsg( 'image_tip' ),
2404 'key' => 'D',
2405 'select' => true
2406 ) : false,
2407 $imagesAvailable ? array(
2408 'image' => $wgLang->getImageFile( 'button-media' ),
2409 'id' => 'mw-editbutton-media',
2410 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
2411 'close' => ']]',
2412 'sample' => wfMsg( 'media_sample' ),
2413 'tip' => wfMsg( 'media_tip' ),
2414 'key' => 'M'
2415 ) : false,
2416 $wgUseTeX ? array(
2417 'image' => $wgLang->getImageFile( 'button-math' ),
2418 'id' => 'mw-editbutton-math',
2419 'open' => "<math>",
2420 'close' => "</math>",
2421 'sample' => wfMsg( 'math_sample' ),
2422 'tip' => wfMsg( 'math_tip' ),
2423 'key' => 'C'
2424 ) : false,
2425 array(
2426 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2427 'id' => 'mw-editbutton-nowiki',
2428 'open' => "<nowiki>",
2429 'close' => "</nowiki>",
2430 'sample' => wfMsg( 'nowiki_sample' ),
2431 'tip' => wfMsg( 'nowiki_tip' ),
2432 'key' => 'N'
2433 ),
2434 array(
2435 'image' => $wgLang->getImageFile( 'button-sig' ),
2436 'id' => 'mw-editbutton-signature',
2437 'open' => '--~~~~',
2438 'close' => '',
2439 'sample' => '',
2440 'tip' => wfMsg( 'sig_tip' ),
2441 'key' => 'Y'
2442 ),
2443 array(
2444 'image' => $wgLang->getImageFile( 'button-hr' ),
2445 'id' => 'mw-editbutton-hr',
2446 'open' => "\n----\n",
2447 'close' => '',
2448 'sample' => '',
2449 'tip' => wfMsg( 'hr_tip' ),
2450 'key' => 'R'
2451 )
2452 );
2453 $toolbar = "<div id='toolbar'>\n";
2454
2455 $script = '';
2456 foreach ( $toolarray as $tool ) {
2457 if ( !$tool ) {
2458 continue;
2459 }
2460
2461 if( !isset( $tool['select'] ) ) {
2462 $tool['select'] = true;
2463 }
2464
2465 $params = array(
2466 $image = $wgStylePath . '/common/images/' . $tool['image'],
2467 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2468 // Older browsers show a "speedtip" type message only for ALT.
2469 // Ideally these should be different, realistically they
2470 // probably don't need to be.
2471 $tip = $tool['tip'],
2472 $open = $tool['open'],
2473 $close = $tool['close'],
2474 $sample = $tool['sample'],
2475 $cssId = $tool['id'],
2476 );
2477
2478 $paramList = implode( ',',
2479 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2480 $script .= "mw.toolbar.addButton($paramList);\n";
2481 }
2482 $wgOut->addScript( Html::inlineScript(
2483 "if ( window.mediaWiki ) {{$script}}"
2484 ) );
2485
2486 $toolbar .= "\n</div>";
2487
2488 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2489
2490 return $toolbar;
2491 }
2492
2493 /**
2494 * Returns an array of html code of the following checkboxes:
2495 * minor and watch
2496 *
2497 * @param $tabindex Current tabindex
2498 * @param $skin Skin object
2499 * @param $checked Array of checkbox => bool, where bool indicates the checked
2500 * status of the checkbox
2501 *
2502 * @return array
2503 */
2504 public function getCheckboxes( &$tabindex, $skin, $checked ) {
2505 global $wgUser;
2506
2507 $checkboxes = array();
2508
2509 // don't show the minor edit checkbox if it's a new page or section
2510 if ( !$this->isNew ) {
2511 $checkboxes['minor'] = '';
2512 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2513 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2514 $attribs = array(
2515 'tabindex' => ++$tabindex,
2516 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2517 'id' => 'wpMinoredit',
2518 );
2519 $checkboxes['minor'] =
2520 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2521 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
2522 Xml::expandAttributes( array( 'title' => $skin->titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2523 ">{$minorLabel}</label>";
2524 }
2525 }
2526
2527 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2528 $checkboxes['watch'] = '';
2529 if ( $wgUser->isLoggedIn() ) {
2530 $attribs = array(
2531 'tabindex' => ++$tabindex,
2532 'accesskey' => wfMsg( 'accesskey-watch' ),
2533 'id' => 'wpWatchthis',
2534 );
2535 $checkboxes['watch'] =
2536 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2537 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
2538 Xml::expandAttributes( array( 'title' => $skin->titleAttrib( 'watch', 'withaccess' ) ) ) .
2539 ">{$watchLabel}</label>";
2540 }
2541 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2542 return $checkboxes;
2543 }
2544
2545 /**
2546 * Returns an array of html code of the following buttons:
2547 * save, diff, preview and live
2548 *
2549 * @param $tabindex Current tabindex
2550 *
2551 * @return array
2552 */
2553 public function getEditButtons( &$tabindex ) {
2554 $buttons = array();
2555
2556 $temp = array(
2557 'id' => 'wpSave',
2558 'name' => 'wpSave',
2559 'type' => 'submit',
2560 'tabindex' => ++$tabindex,
2561 'value' => wfMsg( 'savearticle' ),
2562 'accesskey' => wfMsg( 'accesskey-save' ),
2563 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2564 );
2565 $buttons['save'] = Xml::element('input', $temp, '');
2566
2567 ++$tabindex; // use the same for preview and live preview
2568 $temp = array(
2569 'id' => 'wpPreview',
2570 'name' => 'wpPreview',
2571 'type' => 'submit',
2572 'tabindex' => $tabindex,
2573 'value' => wfMsg( 'showpreview' ),
2574 'accesskey' => wfMsg( 'accesskey-preview' ),
2575 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2576 );
2577 $buttons['preview'] = Xml::element( 'input', $temp, '' );
2578 $buttons['live'] = '';
2579
2580 $temp = array(
2581 'id' => 'wpDiff',
2582 'name' => 'wpDiff',
2583 'type' => 'submit',
2584 'tabindex' => ++$tabindex,
2585 'value' => wfMsg( 'showdiff' ),
2586 'accesskey' => wfMsg( 'accesskey-diff' ),
2587 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2588 );
2589 $buttons['diff'] = Xml::element( 'input', $temp, '' );
2590
2591 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2592 return $buttons;
2593 }
2594
2595 /**
2596 * Output preview text only. This can be sucked into the edit page
2597 * via JavaScript, and saves the server time rendering the skin as
2598 * well as theoretically being more robust on the client (doesn't
2599 * disturb the edit box's undo history, won't eat your text on
2600 * failure, etc).
2601 *
2602 * @todo This doesn't include category or interlanguage links.
2603 * Would need to enhance it a bit, <s>maybe wrap them in XML
2604 * or something...</s> that might also require more skin
2605 * initialization, so check whether that's a problem.
2606 */
2607 function livePreview() {
2608 global $wgOut;
2609 $wgOut->disable();
2610 header( 'Content-type: text/xml; charset=utf-8' );
2611 header( 'Cache-control: no-cache' );
2612
2613 $previewText = $this->getPreviewText();
2614 #$categories = $skin->getCategoryLinks();
2615
2616 $s =
2617 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2618 Xml::tags( 'livepreview', null,
2619 Xml::element( 'preview', null, $previewText )
2620 #. Xml::element( 'category', null, $categories )
2621 );
2622 echo $s;
2623 }
2624
2625 /**
2626 * @return string
2627 */
2628 public function getCancelLink() {
2629 global $wgUser;
2630
2631 $cancelParams = array();
2632 if ( !$this->isConflict && $this->mArticle->getOldID() > 0 ) {
2633 $cancelParams['oldid'] = $this->mArticle->getOldID();
2634 }
2635
2636 return $wgUser->getSkin()->link(
2637 $this->getContextTitle(),
2638 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2639 array( 'id' => 'mw-editform-cancel' ),
2640 $cancelParams,
2641 array( 'known', 'noclasses' )
2642 );
2643 }
2644
2645 /**
2646 * Get a diff between the current contents of the edit box and the
2647 * version of the page we're editing from.
2648 *
2649 * If this is a section edit, we'll replace the section as for final
2650 * save and then make a comparison.
2651 */
2652 function showDiff() {
2653 $oldtext = $this->mArticle->fetchContent();
2654 $newtext = $this->mArticle->replaceSection(
2655 $this->section, $this->textbox1, $this->summary, $this->edittime );
2656
2657 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2658
2659 $newtext = $this->mArticle->preSaveTransform( $newtext );
2660 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2661 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2662 if ( $oldtext !== false || $newtext != '' ) {
2663 $de = new DifferenceEngine( $this->mTitle );
2664 $de->setText( $oldtext, $newtext );
2665 $difftext = $de->getDiff( $oldtitle, $newtitle );
2666 $de->showDiffStyle();
2667 } else {
2668 $difftext = '';
2669 }
2670
2671 global $wgOut;
2672 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2673 }
2674
2675 /**
2676 * Filter an input field through a Unicode de-armoring process if it
2677 * came from an old browser with known broken Unicode editing issues.
2678 *
2679 * @param $request WebRequest
2680 * @param $field String
2681 * @return String
2682 * @private
2683 */
2684 function safeUnicodeInput( $request, $field ) {
2685 $text = rtrim( $request->getText( $field ) );
2686 return $request->getBool( 'safemode' )
2687 ? $this->unmakesafe( $text )
2688 : $text;
2689 }
2690
2691 /**
2692 * @param $request WebRequest
2693 * @param $text string
2694 * @return string
2695 */
2696 function safeUnicodeText( $request, $text ) {
2697 $text = rtrim( $text );
2698 return $request->getBool( 'safemode' )
2699 ? $this->unmakesafe( $text )
2700 : $text;
2701 }
2702
2703 /**
2704 * Filter an output field through a Unicode armoring process if it is
2705 * going to an old browser with known broken Unicode editing issues.
2706 *
2707 * @param $text String
2708 * @return String
2709 * @private
2710 */
2711 function safeUnicodeOutput( $text ) {
2712 global $wgContLang;
2713 $codedText = $wgContLang->recodeForEdit( $text );
2714 return $this->checkUnicodeCompliantBrowser()
2715 ? $codedText
2716 : $this->makesafe( $codedText );
2717 }
2718
2719 /**
2720 * A number of web browsers are known to corrupt non-ASCII characters
2721 * in a UTF-8 text editing environment. To protect against this,
2722 * detected browsers will be served an armored version of the text,
2723 * with non-ASCII chars converted to numeric HTML character references.
2724 *
2725 * Preexisting such character references will have a 0 added to them
2726 * to ensure that round-trips do not alter the original data.
2727 *
2728 * @param $invalue String
2729 * @return String
2730 * @private
2731 */
2732 function makesafe( $invalue ) {
2733 // Armor existing references for reversability.
2734 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
2735
2736 $bytesleft = 0;
2737 $result = "";
2738 $working = 0;
2739 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2740 $bytevalue = ord( $invalue[$i] );
2741 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2742 $result .= chr( $bytevalue );
2743 $bytesleft = 0;
2744 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2745 $working = $working << 6;
2746 $working += ($bytevalue & 0x3F);
2747 $bytesleft--;
2748 if ( $bytesleft <= 0 ) {
2749 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2750 }
2751 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2752 $working = $bytevalue & 0x1F;
2753 $bytesleft = 1;
2754 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2755 $working = $bytevalue & 0x0F;
2756 $bytesleft = 2;
2757 } else { //1111 0xxx
2758 $working = $bytevalue & 0x07;
2759 $bytesleft = 3;
2760 }
2761 }
2762 return $result;
2763 }
2764
2765 /**
2766 * Reverse the previously applied transliteration of non-ASCII characters
2767 * back to UTF-8. Used to protect data from corruption by broken web browsers
2768 * as listed in $wgBrowserBlackList.
2769 *
2770 * @param $invalue String
2771 * @return String
2772 * @private
2773 */
2774 function unmakesafe( $invalue ) {
2775 $result = "";
2776 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2777 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+3] != '0' ) ) {
2778 $i += 3;
2779 $hexstring = "";
2780 do {
2781 $hexstring .= $invalue[$i];
2782 $i++;
2783 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
2784
2785 // Do some sanity checks. These aren't needed for reversability,
2786 // but should help keep the breakage down if the editor
2787 // breaks one of the entities whilst editing.
2788 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2789 $codepoint = hexdec($hexstring);
2790 $result .= codepointToUtf8( $codepoint );
2791 } else {
2792 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2793 }
2794 } else {
2795 $result .= substr( $invalue, $i, 1 );
2796 }
2797 }
2798 // reverse the transform that we made for reversability reasons.
2799 return strtr( $result, array( "&#x0" => "&#x" ) );
2800 }
2801
2802 function noCreatePermission() {
2803 global $wgOut;
2804 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2805 $wgOut->addWikiMsg( 'nocreatetext' );
2806 }
2807
2808 /**
2809 * Attempt submission
2810 * @return bool false if output is done, true if the rest of the form should be displayed
2811 */
2812 function attemptSave() {
2813 global $wgUser, $wgOut;
2814
2815 $resultDetails = false;
2816 # Allow bots to exempt some edits from bot flagging
2817 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
2818 $value = $this->internalAttemptSave( $resultDetails, $bot );
2819
2820 if ( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) {
2821 $this->didSave = true;
2822 }
2823
2824 switch ( $value ) {
2825 case self::AS_HOOK_ERROR_EXPECTED:
2826 case self::AS_CONTENT_TOO_BIG:
2827 case self::AS_ARTICLE_WAS_DELETED:
2828 case self::AS_CONFLICT_DETECTED:
2829 case self::AS_SUMMARY_NEEDED:
2830 case self::AS_TEXTBOX_EMPTY:
2831 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
2832 case self::AS_END:
2833 return true;
2834
2835 case self::AS_HOOK_ERROR:
2836 case self::AS_FILTERING:
2837 return false;
2838
2839 case self::AS_SUCCESS_NEW_ARTICLE:
2840 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
2841 $wgOut->redirect( $this->mTitle->getFullURL( $query ) );
2842 return false;
2843
2844 case self::AS_SUCCESS_UPDATE:
2845 $extraQuery = '';
2846 $sectionanchor = $resultDetails['sectionanchor'];
2847
2848 // Give extensions a chance to modify URL query on update
2849 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle, &$sectionanchor, &$extraQuery ) );
2850
2851 if ( $resultDetails['redirect'] ) {
2852 if ( $extraQuery == '' ) {
2853 $extraQuery = 'redirect=no';
2854 } else {
2855 $extraQuery = 'redirect=no&' . $extraQuery;
2856 }
2857 }
2858 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
2859 return false;
2860
2861 case self::AS_SPAM_ERROR:
2862 $this->spamPageWithContent( $resultDetails['spam'] );
2863 return false;
2864
2865 case self::AS_BLOCKED_PAGE_FOR_USER:
2866 $this->blockedPage();
2867 return false;
2868
2869 case self::AS_IMAGE_REDIRECT_ANON:
2870 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2871 return false;
2872
2873 case self::AS_READ_ONLY_PAGE_ANON:
2874 $this->userNotLoggedInPage();
2875 return false;
2876
2877 case self::AS_READ_ONLY_PAGE_LOGGED:
2878 case self::AS_READ_ONLY_PAGE:
2879 $wgOut->readOnlyPage();
2880 return false;
2881
2882 case self::AS_RATE_LIMITED:
2883 $wgOut->rateLimited();
2884 return false;
2885
2886 case self::AS_NO_CREATE_PERMISSION:
2887 $this->noCreatePermission();
2888 return false;
2889
2890 case self::AS_BLANK_ARTICLE:
2891 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
2892 return false;
2893
2894 case self::AS_IMAGE_REDIRECT_LOGGED:
2895 $wgOut->permissionRequired( 'upload' );
2896 return false;
2897 }
2898 }
2899
2900 /**
2901 * @return Revision
2902 */
2903 function getBaseRevision() {
2904 if ( !$this->mBaseRevision ) {
2905 $db = wfGetDB( DB_MASTER );
2906 $baseRevision = Revision::loadFromTimestamp(
2907 $db, $this->mTitle, $this->edittime );
2908 return $this->mBaseRevision = $baseRevision;
2909 } else {
2910 return $this->mBaseRevision;
2911 }
2912 }
2913 }