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