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