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