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