Merge "Remove button-math"
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * Page edition user interface.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * The edit page/HTML interface (split from Article)
25 * The actual database and text munging is still in Article,
26 * but it should get easier to call those from alternate
27 * interfaces.
28 *
29 * EditPage cares about two distinct titles:
30 * $this->mContextTitle is the page that forms submit to, links point to,
31 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
32 * page in the database that is actually being edited. These are
33 * usually the same, but they are now allowed to be different.
34 *
35 * Surgeon General's Warning: prolonged exposure to this class is known to cause
36 * headaches, which may be fatal.
37 */
38 class EditPage {
39 /**
40 * Status: Article successfully updated
41 */
42 const AS_SUCCESS_UPDATE = 200;
43
44 /**
45 * Status: Article successfully created
46 */
47 const AS_SUCCESS_NEW_ARTICLE = 201;
48
49 /**
50 * Status: Article update aborted by a hook function
51 */
52 const AS_HOOK_ERROR = 210;
53
54 /**
55 * Status: A hook function returned an error
56 */
57 const AS_HOOK_ERROR_EXPECTED = 212;
58
59 /**
60 * Status: User is blocked from editing this page
61 */
62 const AS_BLOCKED_PAGE_FOR_USER = 215;
63
64 /**
65 * Status: Content too big (> $wgMaxArticleSize)
66 */
67 const AS_CONTENT_TOO_BIG = 216;
68
69 /**
70 * Status: User cannot edit? (not used)
71 */
72 const AS_USER_CANNOT_EDIT = 217;
73
74 /**
75 * Status: this anonymous user is not allowed to edit this page
76 */
77 const AS_READ_ONLY_PAGE_ANON = 218;
78
79 /**
80 * Status: this logged in user is not allowed to edit this page
81 */
82 const AS_READ_ONLY_PAGE_LOGGED = 219;
83
84 /**
85 * Status: wiki is in readonly mode (wfReadOnly() == true)
86 */
87 const AS_READ_ONLY_PAGE = 220;
88
89 /**
90 * Status: rate limiter for action 'edit' was tripped
91 */
92 const AS_RATE_LIMITED = 221;
93
94 /**
95 * Status: article was deleted while editing and param wpRecreate == false or form
96 * was not posted
97 */
98 const AS_ARTICLE_WAS_DELETED = 222;
99
100 /**
101 * Status: user tried to create this page, but is not allowed to do that
102 * ( Title->userCan('create') == false )
103 */
104 const AS_NO_CREATE_PERMISSION = 223;
105
106 /**
107 * Status: user tried to create a blank page
108 */
109 const AS_BLANK_ARTICLE = 224;
110
111 /**
112 * Status: (non-resolvable) edit conflict
113 */
114 const AS_CONFLICT_DETECTED = 225;
115
116 /**
117 * Status: no edit summary given and the user has forceeditsummary set and the user is not
118 * editing in his own userspace or talkspace and wpIgnoreBlankSummary == false
119 */
120 const AS_SUMMARY_NEEDED = 226;
121
122 /**
123 * Status: user tried to create a new section without content
124 */
125 const AS_TEXTBOX_EMPTY = 228;
126
127 /**
128 * Status: article is too big (> $wgMaxArticleSize), after merging in the new section
129 */
130 const AS_MAX_ARTICLE_SIZE_EXCEEDED = 229;
131
132 /**
133 * not used
134 */
135 const AS_OK = 230;
136
137 /**
138 * Status: WikiPage::doEdit() was unsuccessful
139 */
140 const AS_END = 231;
141
142 /**
143 * Status: summary contained spam according to one of the regexes in $wgSummarySpamRegex
144 */
145 const AS_SPAM_ERROR = 232;
146
147 /**
148 * Status: anonymous user is not allowed to upload (User::isAllowed('upload') == false)
149 */
150 const AS_IMAGE_REDIRECT_ANON = 233;
151
152 /**
153 * Status: logged in user is not allowed to upload (User::isAllowed('upload') == false)
154 */
155 const AS_IMAGE_REDIRECT_LOGGED = 234;
156
157 /**
158 * Status: can't parse content
159 */
160 const AS_PARSE_ERROR = 240;
161
162 /**
163 * HTML id and name for the beginning of the edit form.
164 */
165 const EDITFORM_ID = 'editform';
166
167 /**
168 * Prefix of key for cookie used to pass post-edit state.
169 * The revision id edited is added after this
170 */
171 const POST_EDIT_COOKIE_KEY_PREFIX = 'PostEditRevision';
172
173 /**
174 * Duration of PostEdit cookie, in seconds.
175 * The cookie will be removed instantly if the JavaScript runs.
176 *
177 * Otherwise, though, we don't want the cookies to accumulate.
178 * RFC 2109 ( https://www.ietf.org/rfc/rfc2109.txt ) specifies a possible limit of only 20 cookies per domain.
179 * This still applies at least to some versions of IE without full updates:
180 * https://blogs.msdn.com/b/ieinternals/archive/2009/08/20/wininet-ie-cookie-internals-faq.aspx
181 *
182 * A value of 20 minutes should be enough to take into account slow loads and minor
183 * clock skew while still avoiding cookie accumulation when JavaScript is turned off.
184 */
185 const POST_EDIT_COOKIE_DURATION = 1200;
186
187 /**
188 * @var Article
189 */
190 var $mArticle;
191
192 /**
193 * @var Title
194 */
195 var $mTitle;
196 private $mContextTitle = null;
197 var $action = 'submit';
198 var $isConflict = false;
199 var $isCssJsSubpage = false;
200 var $isCssSubpage = false;
201 var $isJsSubpage = false;
202 var $isWrongCaseCssJsPage = false;
203 var $isNew = false; // new page or new section
204 var $deletedSinceEdit;
205 var $formtype;
206 var $firsttime;
207 var $lastDelete;
208 var $mTokenOk = false;
209 var $mTokenOkExceptSuffix = false;
210 var $mTriedSave = false;
211 var $incompleteForm = false;
212 var $tooBig = false;
213 var $kblength = false;
214 var $missingComment = false;
215 var $missingSummary = false;
216 var $allowBlankSummary = false;
217 var $autoSumm = '';
218 var $hookError = '';
219 #var $mPreviewTemplates;
220
221 /**
222 * @var ParserOutput
223 */
224 var $mParserOutput;
225
226 /**
227 * Has a summary been preset using GET parameter &summary= ?
228 * @var Bool
229 */
230 var $hasPresetSummary = false;
231
232 var $mBaseRevision = false;
233 var $mShowSummaryField = true;
234
235 # Form values
236 var $save = false, $preview = false, $diff = false;
237 var $minoredit = false, $watchthis = false, $recreate = false;
238 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
239 var $edittime = '', $section = '', $sectiontitle = '', $starttime = '';
240 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
241 var $contentModel = null, $contentFormat = null;
242
243 # Placeholders for text injection by hooks (must be HTML)
244 # extensions should take care to _append_ to the present value
245 public $editFormPageTop = ''; // Before even the preview
246 public $editFormTextTop = '';
247 public $editFormTextBeforeContent = '';
248 public $editFormTextAfterWarn = '';
249 public $editFormTextAfterTools = '';
250 public $editFormTextBottom = '';
251 public $editFormTextAfterContent = '';
252 public $previewTextAfterContent = '';
253 public $mPreloadContent = null;
254
255 /* $didSave should be set to true whenever an article was successfully altered. */
256 public $didSave = false;
257 public $undidRev = 0;
258
259 public $suppressIntro = false;
260
261 /**
262 * Set to true to allow editing of non-text content types.
263 *
264 * @var bool
265 */
266 public $allowNonTextContent = false;
267
268 /**
269 * @param $article Article
270 */
271 public function __construct( Article $article ) {
272 $this->mArticle = $article;
273 $this->mTitle = $article->getTitle();
274
275 $this->contentModel = $this->mTitle->getContentModel();
276
277 $handler = ContentHandler::getForModelID( $this->contentModel );
278 $this->contentFormat = $handler->getDefaultFormat();
279 }
280
281 /**
282 * @return Article
283 */
284 public function getArticle() {
285 return $this->mArticle;
286 }
287
288 /**
289 * @since 1.19
290 * @return Title
291 */
292 public function getTitle() {
293 return $this->mTitle;
294 }
295
296 /**
297 * Set the context Title object
298 *
299 * @param $title Title object or null
300 */
301 public function setContextTitle( $title ) {
302 $this->mContextTitle = $title;
303 }
304
305 /**
306 * Get the context title object.
307 * If not set, $wgTitle will be returned. This behavior might change in
308 * the future to return $this->mTitle instead.
309 *
310 * @return Title object
311 */
312 public function getContextTitle() {
313 if ( is_null( $this->mContextTitle ) ) {
314 global $wgTitle;
315 return $wgTitle;
316 } else {
317 return $this->mContextTitle;
318 }
319 }
320
321 /**
322 * Returns if the given content model is editable.
323 *
324 * @param string $modelId The ID of the content model to test. Use CONTENT_MODEL_XXX constants.
325 * @return bool
326 * @throws MWException if $modelId has no known handler
327 */
328 public function isSupportedContentModel( $modelId ) {
329 return $this->allowNonTextContent ||
330 ContentHandler::getForModelID( $modelId ) instanceof TextContentHandler;
331 }
332
333 function submit() {
334 $this->edit();
335 }
336
337 /**
338 * This is the function that gets called for "action=edit". It
339 * sets up various member variables, then passes execution to
340 * another function, usually showEditForm()
341 *
342 * The edit form is self-submitting, so that when things like
343 * preview and edit conflicts occur, we get the same form back
344 * with the extra stuff added. Only when the final submission
345 * is made and all is well do we actually save and redirect to
346 * the newly-edited page.
347 */
348 function edit() {
349 global $wgOut, $wgRequest, $wgUser;
350 // Allow extensions to modify/prevent this form or submission
351 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
352 return;
353 }
354
355 wfProfileIn( __METHOD__ );
356 wfDebug( __METHOD__ . ": enter\n" );
357
358 // If they used redlink=1 and the page exists, redirect to the main article
359 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
360 $wgOut->redirect( $this->mTitle->getFullURL() );
361 wfProfileOut( __METHOD__ );
362 return;
363 }
364
365 $this->importFormData( $wgRequest );
366 $this->firsttime = false;
367
368 if ( $this->live ) {
369 $this->livePreview();
370 wfProfileOut( __METHOD__ );
371 return;
372 }
373
374 if ( wfReadOnly() && $this->save ) {
375 // Force preview
376 $this->save = false;
377 $this->preview = true;
378 }
379
380 if ( $this->save ) {
381 $this->formtype = 'save';
382 } elseif ( $this->preview ) {
383 $this->formtype = 'preview';
384 } elseif ( $this->diff ) {
385 $this->formtype = 'diff';
386 } else { # First time through
387 $this->firsttime = true;
388 if ( $this->previewOnOpen() ) {
389 $this->formtype = 'preview';
390 } else {
391 $this->formtype = 'initial';
392 }
393 }
394
395 $permErrors = $this->getEditPermissionErrors();
396 if ( $permErrors ) {
397 wfDebug( __METHOD__ . ": User can't edit\n" );
398 // Auto-block user's IP if the account was "hard" blocked
399 $wgUser->spreadAnyEditBlock();
400
401 $this->displayPermissionsError( $permErrors );
402
403 wfProfileOut( __METHOD__ );
404 return;
405 }
406
407 wfProfileIn( __METHOD__ . "-business-end" );
408
409 $this->isConflict = false;
410 // css / js subpages of user pages get a special treatment
411 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
412 $this->isCssSubpage = $this->mTitle->isCssSubpage();
413 $this->isJsSubpage = $this->mTitle->isJsSubpage();
414 $this->isWrongCaseCssJsPage = $this->isWrongCaseCssJsPage();
415
416 # Show applicable editing introductions
417 if ( $this->formtype == 'initial' || $this->firsttime ) {
418 $this->showIntro();
419 }
420
421 # Attempt submission here. This will check for edit conflicts,
422 # and redundantly check for locked database, blocked IPs, etc.
423 # that edit() already checked just in case someone tries to sneak
424 # in the back door with a hand-edited submission URL.
425
426 if ( 'save' == $this->formtype ) {
427 if ( !$this->attemptSave() ) {
428 wfProfileOut( __METHOD__ . "-business-end" );
429 wfProfileOut( __METHOD__ );
430 return;
431 }
432 }
433
434 # First time through: get contents, set time for conflict
435 # checking, etc.
436 if ( 'initial' == $this->formtype || $this->firsttime ) {
437 if ( $this->initialiseForm() === false ) {
438 $this->noSuchSectionPage();
439 wfProfileOut( __METHOD__ . "-business-end" );
440 wfProfileOut( __METHOD__ );
441 return;
442 }
443
444 if ( !$this->mTitle->getArticleID() ) {
445 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
446 } else {
447 wfRunHooks( 'EditFormInitialText', array( $this ) );
448 }
449
450 }
451
452 $this->showEditForm();
453 wfProfileOut( __METHOD__ . "-business-end" );
454 wfProfileOut( __METHOD__ );
455 }
456
457 /**
458 * @return array
459 */
460 protected function getEditPermissionErrors() {
461 global $wgUser;
462 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
463 # Can this title be created?
464 if ( !$this->mTitle->exists() ) {
465 $permErrors = array_merge( $permErrors,
466 wfArrayDiff2( $this->mTitle->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
467 }
468 # Ignore some permissions errors when a user is just previewing/viewing diffs
469 $remove = array();
470 foreach ( $permErrors as $error ) {
471 if ( ( $this->preview || $this->diff )
472 && ( $error[0] == 'blockedtext' || $error[0] == 'autoblockedtext' )
473 ) {
474 $remove[] = $error;
475 }
476 }
477 $permErrors = wfArrayDiff2( $permErrors, $remove );
478 return $permErrors;
479 }
480
481 /**
482 * Display a permissions error page, like OutputPage::showPermissionsErrorPage(),
483 * but with the following differences:
484 * - If redlink=1, the user will be redirected to the page
485 * - If there is content to display or the error occurs while either saving,
486 * previewing or showing the difference, it will be a
487 * "View source for ..." page displaying the source code after the error message.
488 *
489 * @since 1.19
490 * @param array $permErrors of permissions errors, as returned by
491 * Title::getUserPermissionsErrors().
492 * @throws PermissionsError
493 */
494 protected function displayPermissionsError( array $permErrors ) {
495 global $wgRequest, $wgOut;
496
497 if ( $wgRequest->getBool( 'redlink' ) ) {
498 // The edit page was reached via a red link.
499 // Redirect to the article page and let them click the edit tab if
500 // they really want a permission error.
501 $wgOut->redirect( $this->mTitle->getFullURL() );
502 return;
503 }
504
505 $content = $this->getContentObject();
506
507 # Use the normal message if there's nothing to display
508 if ( $this->firsttime && ( !$content || $content->isEmpty() ) ) {
509 $action = $this->mTitle->exists() ? 'edit' :
510 ( $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage' );
511 throw new PermissionsError( $action, $permErrors );
512 }
513
514 $wgOut->setRobotPolicy( 'noindex,nofollow' );
515 $wgOut->setPageTitle( wfMessage( 'viewsource-title', $this->getContextTitle()->getPrefixedText() ) );
516 $wgOut->addBacklinkSubtitle( $this->getContextTitle() );
517 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $permErrors, 'edit' ) );
518 $wgOut->addHTML( "<hr />\n" );
519
520 # If the user made changes, preserve them when showing the markup
521 # (This happens when a user is blocked during edit, for instance)
522 if ( !$this->firsttime ) {
523 $text = $this->textbox1;
524 $wgOut->addWikiMsg( 'viewyourtext' );
525 } else {
526 $text = $this->toEditText( $content );
527 $wgOut->addWikiMsg( 'viewsourcetext' );
528 }
529
530 $this->showTextbox( $text, 'wpTextbox1', array( 'readonly' ) );
531
532 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
533 Linker::formatTemplates( $this->getTemplates() ) ) );
534
535 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
536
537 if ( $this->mTitle->exists() ) {
538 $wgOut->returnToMain( null, $this->mTitle );
539 }
540 }
541
542 /**
543 * Show a read-only error
544 * Parameters are the same as OutputPage:readOnlyPage()
545 * Redirect to the article page if redlink=1
546 * @deprecated in 1.19; use displayPermissionsError() instead
547 */
548 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
549 wfDeprecated( __METHOD__, '1.19' );
550
551 global $wgRequest, $wgOut;
552 if ( $wgRequest->getBool( 'redlink' ) ) {
553 // The edit page was reached via a red link.
554 // Redirect to the article page and let them click the edit tab if
555 // they really want a permission error.
556 $wgOut->redirect( $this->mTitle->getFullURL() );
557 } else {
558 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
559 }
560 }
561
562 /**
563 * Should we show a preview when the edit form is first shown?
564 *
565 * @return bool
566 */
567 protected function previewOnOpen() {
568 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
569 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
570 // Explicit override from request
571 return true;
572 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
573 // Explicit override from request
574 return false;
575 } elseif ( $this->section == 'new' ) {
576 // Nothing *to* preview for new sections
577 return false;
578 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
579 // Standard preference behavior
580 return true;
581 } elseif ( !$this->mTitle->exists()
582 && isset( $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()] )
583 && $wgPreviewOnOpenNamespaces[$this->mTitle->getNamespace()]
584 ) {
585 // Categories are special
586 return true;
587 } else {
588 return false;
589 }
590 }
591
592 /**
593 * Checks whether the user entered a skin name in uppercase,
594 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
595 *
596 * @return bool
597 */
598 protected function isWrongCaseCssJsPage() {
599 if ( $this->mTitle->isCssJsSubpage() ) {
600 $name = $this->mTitle->getSkinFromCssJsSubpage();
601 $skins = array_merge(
602 array_keys( Skin::getSkinNames() ),
603 array( 'common' )
604 );
605 return !in_array( $name, $skins )
606 && in_array( strtolower( $name ), $skins );
607 } else {
608 return false;
609 }
610 }
611
612 /**
613 * Returns whether section editing is supported for the current page.
614 * Subclasses may override this to replace the default behavior, which is
615 * to check ContentHandler::supportsSections.
616 *
617 * @return bool true if this edit page supports sections, false otherwise.
618 */
619 protected function isSectionEditSupported() {
620 $contentHandler = ContentHandler::getForTitle( $this->mTitle );
621 return $contentHandler->supportsSections();
622 }
623
624 /**
625 * This function collects the form data and uses it to populate various member variables.
626 * @param $request WebRequest
627 * @throws ErrorPageError
628 */
629 function importFormData( &$request ) {
630 global $wgContLang, $wgUser;
631
632 wfProfileIn( __METHOD__ );
633
634 # Section edit can come from either the form or a link
635 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
636
637 if ( $this->section !== null && $this->section !== '' && !$this->isSectionEditSupported() ) {
638 wfProfileOut( __METHOD__ );
639 throw new ErrorPageError( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
640 }
641
642 $this->isNew = !$this->mTitle->exists() || $this->section == 'new';
643
644 if ( $request->wasPosted() ) {
645 # These fields need to be checked for encoding.
646 # Also remove trailing whitespace, but don't remove _initial_
647 # whitespace from the text boxes. This may be significant formatting.
648 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
649 if ( !$request->getCheck( 'wpTextbox2' ) ) {
650 // Skip this if wpTextbox2 has input, it indicates that we came
651 // from a conflict page with raw page text, not a custom form
652 // modified by subclasses
653 wfProfileIn( get_class( $this ) . "::importContentFormData" );
654 $textbox1 = $this->importContentFormData( $request );
655 if ( $textbox1 !== null ) {
656 $this->textbox1 = $textbox1;
657 }
658
659 wfProfileOut( get_class( $this ) . "::importContentFormData" );
660 }
661
662 # Truncate for whole multibyte characters
663 $this->summary = $wgContLang->truncate( $request->getText( 'wpSummary' ), 255 );
664
665 # If the summary consists of a heading, e.g. '==Foobar==', extract the title from the
666 # header syntax, e.g. 'Foobar'. This is mainly an issue when we are using wpSummary for
667 # section titles.
668 $this->summary = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary );
669
670 # Treat sectiontitle the same way as summary.
671 # Note that wpSectionTitle is not yet a part of the actual edit form, as wpSummary is
672 # currently doing double duty as both edit summary and section title. Right now this
673 # is just to allow API edits to work around this limitation, but this should be
674 # incorporated into the actual edit form when EditPage is rewritten (Bugs 18654, 26312).
675 $this->sectiontitle = $wgContLang->truncate( $request->getText( 'wpSectionTitle' ), 255 );
676 $this->sectiontitle = preg_replace( '/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->sectiontitle );
677
678 $this->edittime = $request->getVal( 'wpEdittime' );
679 $this->starttime = $request->getVal( 'wpStarttime' );
680
681 $undidRev = $request->getInt( 'wpUndidRevision' );
682 if ( $undidRev ) {
683 $this->undidRev = $undidRev;
684 }
685
686 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
687
688 if ( $this->textbox1 === '' && $request->getVal( 'wpTextbox1' ) === null ) {
689 // wpTextbox1 field is missing, possibly due to being "too big"
690 // according to some filter rules such as Suhosin's setting for
691 // suhosin.request.max_value_length (d'oh)
692 $this->incompleteForm = true;
693 } else {
694 // edittime should be one of our last fields; if it's missing,
695 // the submission probably broke somewhere in the middle.
696 $this->incompleteForm = is_null( $this->edittime );
697 }
698 if ( $this->incompleteForm ) {
699 # If the form is incomplete, force to preview.
700 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
701 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
702 $this->preview = true;
703 } else {
704 /* Fallback for live preview */
705 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
706 $this->diff = $request->getCheck( 'wpDiff' );
707
708 // Remember whether a save was requested, so we can indicate
709 // if we forced preview due to session failure.
710 $this->mTriedSave = !$this->preview;
711
712 if ( $this->tokenOk( $request ) ) {
713 # Some browsers will not report any submit button
714 # if the user hits enter in the comment box.
715 # The unmarked state will be assumed to be a save,
716 # if the form seems otherwise complete.
717 wfDebug( __METHOD__ . ": Passed token check.\n" );
718 } elseif ( $this->diff ) {
719 # Failed token check, but only requested "Show Changes".
720 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
721 } else {
722 # Page might be a hack attempt posted from
723 # an external site. Preview instead of saving.
724 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
725 $this->preview = true;
726 }
727 }
728 $this->save = !$this->preview && !$this->diff;
729 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
730 $this->edittime = null;
731 }
732
733 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
734 $this->starttime = null;
735 }
736
737 $this->recreate = $request->getCheck( 'wpRecreate' );
738
739 $this->minoredit = $request->getCheck( 'wpMinoredit' );
740 $this->watchthis = $request->getCheck( 'wpWatchthis' );
741
742 # Don't force edit summaries when a user is editing their own user or talk page
743 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK )
744 && $this->mTitle->getText() == $wgUser->getName()
745 ) {
746 $this->allowBlankSummary = true;
747 } else {
748 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' ) || !$wgUser->getOption( 'forceeditsummary' );
749 }
750
751 $this->autoSumm = $request->getText( 'wpAutoSummary' );
752 } else {
753 # Not a posted form? Start with nothing.
754 wfDebug( __METHOD__ . ": Not a posted form.\n" );
755 $this->textbox1 = '';
756 $this->summary = '';
757 $this->sectiontitle = '';
758 $this->edittime = '';
759 $this->starttime = wfTimestampNow();
760 $this->edit = false;
761 $this->preview = false;
762 $this->save = false;
763 $this->diff = false;
764 $this->minoredit = false;
765 $this->watchthis = $request->getBool( 'watchthis', false ); // Watch may be overridden by request parameters
766 $this->recreate = false;
767
768 // When creating a new section, we can preload a section title by passing it as the
769 // preloadtitle parameter in the URL (Bug 13100)
770 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
771 $this->sectiontitle = $request->getVal( 'preloadtitle' );
772 // Once wpSummary isn't being use for setting section titles, we should delete this.
773 $this->summary = $request->getVal( 'preloadtitle' );
774 } elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
775 $this->summary = $request->getText( 'summary' );
776 if ( $this->summary !== '' ) {
777 $this->hasPresetSummary = true;
778 }
779 }
780
781 if ( $request->getVal( 'minor' ) ) {
782 $this->minoredit = true;
783 }
784 }
785
786 $this->oldid = $request->getInt( 'oldid' );
787
788 $this->bot = $request->getBool( 'bot', true );
789 $this->nosummary = $request->getBool( 'nosummary' );
790
791 $this->contentModel = $request->getText( 'model', $this->contentModel ); #may be overridden by revision
792 $this->contentFormat = $request->getText( 'format', $this->contentFormat ); #may be overridden by revision
793
794 if ( !ContentHandler::getForModelID( $this->contentModel )->isSupportedFormat( $this->contentFormat ) ) {
795 throw new ErrorPageError(
796 'editpage-notsupportedcontentformat-title',
797 'editpage-notsupportedcontentformat-text',
798 array( $this->contentFormat, ContentHandler::getLocalizedName( $this->contentModel ) )
799 );
800 }
801 #TODO: check if the desired model is allowed in this namespace, and if a transition from the page's current model to the new model is allowed
802
803 $this->live = $request->getCheck( 'live' );
804 $this->editintro = $request->getText( 'editintro',
805 // Custom edit intro for new sections
806 $this->section === 'new' ? 'MediaWiki:addsection-editintro' : '' );
807
808 // Allow extensions to modify form data
809 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
810
811 wfProfileOut( __METHOD__ );
812 }
813
814 /**
815 * Subpage overridable method for extracting the page content data from the
816 * posted form to be placed in $this->textbox1, if using customized input
817 * this method should be overridden and return the page text that will be used
818 * for saving, preview parsing and so on...
819 *
820 * @param $request WebRequest
821 */
822 protected function importContentFormData( &$request ) {
823 return; // Don't do anything, EditPage already extracted wpTextbox1
824 }
825
826 /**
827 * Initialise form fields in the object
828 * Called on the first invocation, e.g. when a user clicks an edit link
829 * @return bool -- if the requested section is valid
830 */
831 function initialiseForm() {
832 global $wgUser;
833 $this->edittime = $this->mArticle->getTimestamp();
834
835 $content = $this->getContentObject( false ); #TODO: track content object?!
836 if ( $content === false ) {
837 return false;
838 }
839 $this->textbox1 = $this->toEditText( $content );
840
841 // activate checkboxes if user wants them to be always active
842 # Sort out the "watch" checkbox
843 if ( $wgUser->getOption( 'watchdefault' ) ) {
844 # Watch all edits
845 $this->watchthis = true;
846 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
847 # Watch creations
848 $this->watchthis = true;
849 } elseif ( $wgUser->isWatched( $this->mTitle ) ) {
850 # Already watched
851 $this->watchthis = true;
852 }
853 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew ) {
854 $this->minoredit = true;
855 }
856 if ( $this->textbox1 === false ) {
857 return false;
858 }
859 return true;
860 }
861
862 /**
863 * Fetch initial editing page content.
864 *
865 * @param $def_text string|bool
866 * @return mixed string on success, $def_text for invalid sections
867 * @private
868 * @deprecated since 1.21, get WikiPage::getContent() instead.
869 */
870 function getContent( $def_text = false ) {
871 ContentHandler::deprecated( __METHOD__, '1.21' );
872
873 if ( $def_text !== null && $def_text !== false && $def_text !== '' ) {
874 $def_content = $this->toEditContent( $def_text );
875 } else {
876 $def_content = false;
877 }
878
879 $content = $this->getContentObject( $def_content );
880
881 // Note: EditPage should only be used with text based content anyway.
882 return $this->toEditText( $content );
883 }
884
885 /**
886 * @param Content|null $def_content The default value to return
887 *
888 * @return mixed Content on success, $def_content for invalid sections
889 *
890 * @since 1.21
891 */
892 protected function getContentObject( $def_content = null ) {
893 global $wgOut, $wgRequest, $wgUser, $wgContLang;
894
895 wfProfileIn( __METHOD__ );
896
897 $content = false;
898
899 // For message page not locally set, use the i18n message.
900 // For other non-existent articles, use preload text if any.
901 if ( !$this->mTitle->exists() || $this->section == 'new' ) {
902 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $this->section != 'new' ) {
903 # If this is a system message, get the default text.
904 $msg = $this->mTitle->getDefaultMessageText();
905
906 $content = $this->toEditContent( $msg );
907 }
908 if ( $content === false ) {
909 # If requested, preload some text.
910 $preload = $wgRequest->getVal( 'preload',
911 // Custom preload text for new sections
912 $this->section === 'new' ? 'MediaWiki:addsection-preload' : '' );
913 $params = $wgRequest->getArray( 'preloadparams', array() );
914
915 $content = $this->getPreloadedContent( $preload, $params );
916 }
917 // For existing pages, get text based on "undo" or section parameters.
918 } else {
919 if ( $this->section != '' ) {
920 // Get section edit text (returns $def_text for invalid sections)
921 $orig = $this->getOriginalContent();
922 $content = $orig ? $orig->getSection( $this->section ) : null;
923
924 if ( !$content ) {
925 $content = $def_content;
926 }
927 } else {
928 $undoafter = $wgRequest->getInt( 'undoafter' );
929 $undo = $wgRequest->getInt( 'undo' );
930
931 if ( $undo > 0 && $undoafter > 0 ) {
932
933 $undorev = Revision::newFromId( $undo );
934 $oldrev = Revision::newFromId( $undoafter );
935
936 # Sanity check, make sure it's the right page,
937 # the revisions exist and they were not deleted.
938 # Otherwise, $content will be left as-is.
939 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
940 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
941 !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
942
943 $content = $this->mArticle->getUndoContent( $undorev, $oldrev );
944
945 if ( $content === false ) {
946 # Warn the user that something went wrong
947 $undoMsg = 'failure';
948 } else {
949 $oldContent = $this->mArticle->getPage()->getContent( Revision::RAW );
950 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
951 $newContent = $content->preSaveTransform( $this->mTitle, $wgUser, $popts );
952
953 if ( $newContent->equals( $oldContent ) ) {
954 # Tell the user that the undo results in no change,
955 # i.e. the revisions were already undone.
956 $undoMsg = 'nochange';
957 $content = false;
958 } else {
959 # Inform the user of our success and set an automatic edit summary
960 $undoMsg = 'success';
961
962 # If we just undid one rev, use an autosummary
963 $firstrev = $oldrev->getNext();
964 if ( $firstrev && $firstrev->getId() == $undo ) {
965 $userText = $undorev->getUserText();
966 if ( $userText === '' ) {
967 $undoSummary = wfMessage(
968 'undo-summary-username-hidden',
969 $undo
970 )->inContentLanguage()->text();
971 } else {
972 $undoSummary = wfMessage(
973 'undo-summary',
974 $undo,
975 $userText
976 )->inContentLanguage()->text();
977 }
978 if ( $this->summary === '' ) {
979 $this->summary = $undoSummary;
980 } else {
981 $this->summary = $undoSummary . wfMessage( 'colon-separator' )
982 ->inContentLanguage()->text() . $this->summary;
983 }
984 $this->undidRev = $undo;
985 }
986 $this->formtype = 'diff';
987 }
988 }
989 } else {
990 // Failed basic sanity checks.
991 // Older revisions may have been removed since the link
992 // was created, or we may simply have got bogus input.
993 $undoMsg = 'norev';
994 }
995
996 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
997 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
998 $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
999 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
1000 }
1001
1002 if ( $content === false ) {
1003 $content = $this->getOriginalContent();
1004 }
1005 }
1006 }
1007
1008 wfProfileOut( __METHOD__ );
1009 return $content;
1010 }
1011
1012 /**
1013 * Get the content of the wanted revision, without section extraction.
1014 *
1015 * The result of this function can be used to compare user's input with
1016 * section replaced in its context (using WikiPage::replaceSection())
1017 * to the original text of the edit.
1018 *
1019 * This differs from Article::getContent() that when a missing revision is
1020 * encountered the result will be null and not the
1021 * 'missing-revision' message.
1022 *
1023 * @since 1.19
1024 * @return Content|null
1025 */
1026 private function getOriginalContent() {
1027 if ( $this->section == 'new' ) {
1028 return $this->getCurrentContent();
1029 }
1030 $revision = $this->mArticle->getRevisionFetched();
1031 if ( $revision === null ) {
1032 if ( !$this->contentModel ) {
1033 $this->contentModel = $this->getTitle()->getContentModel();
1034 }
1035 $handler = ContentHandler::getForModelID( $this->contentModel );
1036
1037 return $handler->makeEmptyContent();
1038 }
1039 $content = $revision->getContent();
1040 return $content;
1041 }
1042
1043 /**
1044 * Get the current content of the page. This is basically similar to
1045 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1046 * content object is returned instead of null.
1047 *
1048 * @since 1.21
1049 * @return Content
1050 */
1051 protected function getCurrentContent() {
1052 $rev = $this->mArticle->getRevision();
1053 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1054
1055 if ( $content === false || $content === null ) {
1056 if ( !$this->contentModel ) {
1057 $this->contentModel = $this->getTitle()->getContentModel();
1058 }
1059 $handler = ContentHandler::getForModelID( $this->contentModel );
1060
1061 return $handler->makeEmptyContent();
1062 } else {
1063 # nasty side-effect, but needed for consistency
1064 $this->contentModel = $rev->getContentModel();
1065 $this->contentFormat = $rev->getContentFormat();
1066
1067 return $content;
1068 }
1069 }
1070
1071 /**
1072 * Use this method before edit() to preload some text into the edit box
1073 *
1074 * @param $text string
1075 * @deprecated since 1.21, use setPreloadedContent() instead.
1076 */
1077 public function setPreloadedText( $text ) {
1078 ContentHandler::deprecated( __METHOD__, "1.21" );
1079
1080 $content = $this->toEditContent( $text );
1081
1082 $this->setPreloadedContent( $content );
1083 }
1084
1085 /**
1086 * Use this method before edit() to preload some content into the edit box
1087 *
1088 * @param $content Content
1089 *
1090 * @since 1.21
1091 */
1092 public function setPreloadedContent( Content $content ) {
1093 $this->mPreloadContent = $content;
1094 }
1095
1096 /**
1097 * Get the contents to be preloaded into the box, either set by
1098 * an earlier setPreloadText() or by loading the given page.
1099 *
1100 * @param string $preload representing the title to preload from.
1101 *
1102 * @return String
1103 *
1104 * @deprecated since 1.21, use getPreloadedContent() instead
1105 */
1106 protected function getPreloadedText( $preload ) {
1107 ContentHandler::deprecated( __METHOD__, "1.21" );
1108
1109 $content = $this->getPreloadedContent( $preload );
1110 $text = $this->toEditText( $content );
1111
1112 return $text;
1113 }
1114
1115 /**
1116 * Get the contents to be preloaded into the box, either set by
1117 * an earlier setPreloadText() or by loading the given page.
1118 *
1119 * @param string $preload representing the title to preload from.
1120 * @param Array $params Parameters to use (interface-message style) in the preloaded text
1121 *
1122 * @return Content
1123 *
1124 * @since 1.21
1125 */
1126 protected function getPreloadedContent( $preload, $params = array() ) {
1127 global $wgUser;
1128
1129 if ( !empty( $this->mPreloadContent ) ) {
1130 return $this->mPreloadContent;
1131 }
1132
1133 $handler = ContentHandler::getForTitle( $this->getTitle() );
1134
1135 if ( $preload === '' ) {
1136 return $handler->makeEmptyContent();
1137 }
1138
1139 $title = Title::newFromText( $preload );
1140 # Check for existence to avoid getting MediaWiki:Noarticletext
1141 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1142 //TODO: somehow show a warning to the user!
1143 return $handler->makeEmptyContent();
1144 }
1145
1146 $page = WikiPage::factory( $title );
1147 if ( $page->isRedirect() ) {
1148 $title = $page->getRedirectTarget();
1149 # Same as before
1150 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1151 //TODO: somehow show a warning to the user!
1152 return $handler->makeEmptyContent();
1153 }
1154 $page = WikiPage::factory( $title );
1155 }
1156
1157 $parserOptions = ParserOptions::newFromUser( $wgUser );
1158 $content = $page->getContent( Revision::RAW );
1159
1160 if ( !$content ) {
1161 //TODO: somehow show a warning to the user!
1162 return $handler->makeEmptyContent();
1163 }
1164
1165 if ( $content->getModel() !== $handler->getModelID() ) {
1166 $converted = $content->convert( $handler->getModelID() );
1167
1168 if ( !$converted ) {
1169 //TODO: somehow show a warning to the user!
1170 wfDebug( "Attempt to preload incompatible content: "
1171 . "can't convert " . $content->getModel()
1172 . " to " . $handler->getModelID() );
1173
1174 return $handler->makeEmptyContent();
1175 }
1176
1177 $content = $converted;
1178 }
1179
1180 return $content->preloadTransform( $title, $parserOptions, $params );
1181 }
1182
1183 /**
1184 * Make sure the form isn't faking a user's credentials.
1185 *
1186 * @param $request WebRequest
1187 * @return bool
1188 * @private
1189 */
1190 function tokenOk( &$request ) {
1191 global $wgUser;
1192 $token = $request->getVal( 'wpEditToken' );
1193 $this->mTokenOk = $wgUser->matchEditToken( $token );
1194 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
1195 return $this->mTokenOk;
1196 }
1197
1198 /**
1199 * Sets post-edit cookie indicating the user just saved a particular revision.
1200 *
1201 * This uses a temporary cookie for each revision ID so separate saves will never
1202 * interfere with each other.
1203 *
1204 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1205 * the redirect. It must be clearable by JavaScript code, so it must not be
1206 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1207 * variable.
1208 *
1209 * We use a path of '/' since wgCookiePath is not exposed to JS
1210 *
1211 * If the variable were set on the server, it would be cached, which is unwanted
1212 * since the post-edit state should only apply to the load right after the save.
1213 */
1214 protected function setPostEditCookie() {
1215 $revisionId = $this->mArticle->getLatest();
1216 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1217
1218 $response = RequestContext::getMain()->getRequest()->response();
1219 $response->setcookie( $postEditKey, '1', time() + self::POST_EDIT_COOKIE_DURATION, array(
1220 'path' => '/',
1221 'httpOnly' => false,
1222 ) );
1223 }
1224
1225 /**
1226 * Attempt submission
1227 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1228 * @return bool false if output is done, true if the rest of the form should be displayed
1229 */
1230 public function attemptSave() {
1231 global $wgUser;
1232
1233 $resultDetails = false;
1234 # Allow bots to exempt some edits from bot flagging
1235 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
1236 $status = $this->internalAttemptSave( $resultDetails, $bot );
1237
1238 return $this->handleStatus( $status, $resultDetails );
1239 }
1240
1241 /**
1242 * Handle status, such as after attempt save
1243 *
1244 * @param Status $status
1245 * @param array|bool $resultDetails
1246 *
1247 * @throws ErrorPageError
1248 * return bool false, if output is done, true if rest of the form should be displayed
1249 */
1250 private function handleStatus( Status $status, $resultDetails ) {
1251 global $wgUser, $wgOut;
1252
1253 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1254 if ( $status->value == self::AS_SUCCESS_UPDATE || $status->value == self::AS_SUCCESS_NEW_ARTICLE ) {
1255 $this->didSave = true;
1256 if ( !$resultDetails['nullEdit'] ) {
1257 $this->setPostEditCookie();
1258 }
1259 }
1260
1261 switch ( $status->value ) {
1262 case self::AS_HOOK_ERROR_EXPECTED:
1263 case self::AS_CONTENT_TOO_BIG:
1264 case self::AS_ARTICLE_WAS_DELETED:
1265 case self::AS_CONFLICT_DETECTED:
1266 case self::AS_SUMMARY_NEEDED:
1267 case self::AS_TEXTBOX_EMPTY:
1268 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1269 case self::AS_END:
1270 return true;
1271
1272 case self::AS_HOOK_ERROR:
1273 return false;
1274
1275 case self::AS_PARSE_ERROR:
1276 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1277 return true;
1278
1279 case self::AS_SUCCESS_NEW_ARTICLE:
1280 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1281 $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
1282 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1283 return false;
1284
1285 case self::AS_SUCCESS_UPDATE:
1286 $extraQuery = '';
1287 $sectionanchor = $resultDetails['sectionanchor'];
1288
1289 // Give extensions a chance to modify URL query on update
1290 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle, &$sectionanchor, &$extraQuery ) );
1291
1292 if ( $resultDetails['redirect'] ) {
1293 if ( $extraQuery == '' ) {
1294 $extraQuery = 'redirect=no';
1295 } else {
1296 $extraQuery = 'redirect=no&' . $extraQuery;
1297 }
1298 }
1299 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1300 return false;
1301
1302 case self::AS_BLANK_ARTICLE:
1303 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1304 return false;
1305
1306 case self::AS_SPAM_ERROR:
1307 $this->spamPageWithContent( $resultDetails['spam'] );
1308 return false;
1309
1310 case self::AS_BLOCKED_PAGE_FOR_USER:
1311 throw new UserBlockedError( $wgUser->getBlock() );
1312
1313 case self::AS_IMAGE_REDIRECT_ANON:
1314 case self::AS_IMAGE_REDIRECT_LOGGED:
1315 throw new PermissionsError( 'upload' );
1316
1317 case self::AS_READ_ONLY_PAGE_ANON:
1318 case self::AS_READ_ONLY_PAGE_LOGGED:
1319 throw new PermissionsError( 'edit' );
1320
1321 case self::AS_READ_ONLY_PAGE:
1322 throw new ReadOnlyError;
1323
1324 case self::AS_RATE_LIMITED:
1325 throw new ThrottledError();
1326
1327 case self::AS_NO_CREATE_PERMISSION:
1328 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1329 throw new PermissionsError( $permission );
1330
1331 default:
1332 // We don't recognize $status->value. The only way that can happen
1333 // is if an extension hook aborted from inside ArticleSave.
1334 // Render the status object into $this->hookError
1335 // FIXME this sucks, we should just use the Status object throughout
1336 $this->hookError = '<div class="error">' . $status->getWikitext() .
1337 '</div>';
1338 return true;
1339 }
1340 }
1341
1342 /**
1343 * Run hooks that can filter edits just before they get saved.
1344 *
1345 * @param Content $content the Content to filter.
1346 * @param Status $status for reporting the outcome to the caller
1347 * @param User $user the user performing the edit
1348 *
1349 * @return bool
1350 */
1351 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1352 // Run old style post-section-merge edit filter
1353 if ( !ContentHandler::runLegacyHooks( 'EditFilterMerged',
1354 array( $this, $content, &$this->hookError, $this->summary ) ) ) {
1355
1356 # Error messages etc. could be handled within the hook...
1357 $status->fatal( 'hookaborted' );
1358 $status->value = self::AS_HOOK_ERROR;
1359 return false;
1360 } elseif ( $this->hookError != '' ) {
1361 # ...or the hook could be expecting us to produce an error
1362 $status->fatal( 'hookaborted' );
1363 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1364 return false;
1365 }
1366
1367 // Run new style post-section-merge edit filter
1368 if ( !wfRunHooks( 'EditFilterMergedContent',
1369 array( $this->mArticle->getContext(), $content, $status, $this->summary,
1370 $user, $this->minoredit ) ) ) {
1371
1372 # Error messages etc. could be handled within the hook...
1373 // XXX: $status->value may already be something informative...
1374 $this->hookError = $status->getWikiText();
1375 $status->fatal( 'hookaborted' );
1376 $status->value = self::AS_HOOK_ERROR;
1377 return false;
1378 } elseif ( !$status->isOK() ) {
1379 # ...or the hook could be expecting us to produce an error
1380 // FIXME this sucks, we should just use the Status object throughout
1381 $this->hookError = $status->getWikiText();
1382 $status->fatal( 'hookaborted' );
1383 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1384 return false;
1385 }
1386
1387 return true;
1388 }
1389
1390 /**
1391 * Attempt submission (no UI)
1392 *
1393 * @param array $result array to add statuses to, currently with the possible keys:
1394 * spam - string - Spam string from content if any spam is detected by matchSpamRegex
1395 * sectionanchor - string - Section anchor for a section save
1396 * nullEdit - boolean - Set if doEditContent is OK. True if null edit, false otherwise.
1397 * redirect - boolean - Set if doEditContent is OK. True if resulting revision is a redirect
1398 * @param bool $bot True if edit is being made under the bot right.
1399 *
1400 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1401 *
1402 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1403 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1404 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1405 */
1406 function internalAttemptSave( &$result, $bot = false ) {
1407 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1408
1409 $status = Status::newGood();
1410
1411 wfProfileIn( __METHOD__ );
1412 wfProfileIn( __METHOD__ . '-checks' );
1413
1414 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1415 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1416 $status->fatal( 'hookaborted' );
1417 $status->value = self::AS_HOOK_ERROR;
1418 wfProfileOut( __METHOD__ . '-checks' );
1419 wfProfileOut( __METHOD__ );
1420 return $status;
1421 }
1422
1423 $spam = $wgRequest->getText( 'wpAntispam' );
1424 if ( $spam !== '' ) {
1425 wfDebugLog(
1426 'SimpleAntiSpam',
1427 $wgUser->getName() .
1428 ' editing "' .
1429 $this->mTitle->getPrefixedText() .
1430 '" submitted bogus field "' .
1431 $spam .
1432 '"'
1433 );
1434 $status->fatal( 'spamprotectionmatch', false );
1435 $status->value = self::AS_SPAM_ERROR;
1436 wfProfileOut( __METHOD__ . '-checks' );
1437 wfProfileOut( __METHOD__ );
1438 return $status;
1439 }
1440
1441 try {
1442 # Construct Content object
1443 $textbox_content = $this->toEditContent( $this->textbox1 );
1444 } catch ( MWContentSerializationException $ex ) {
1445 $status->fatal( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
1446 $status->value = self::AS_PARSE_ERROR;
1447 wfProfileOut( __METHOD__ . '-checks' );
1448 wfProfileOut( __METHOD__ );
1449 return $status;
1450 }
1451
1452 # Check image redirect
1453 if ( $this->mTitle->getNamespace() == NS_FILE &&
1454 $textbox_content->isRedirect() &&
1455 !$wgUser->isAllowed( 'upload' ) ) {
1456 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1457 $status->setResult( false, $code );
1458
1459 wfProfileOut( __METHOD__ . '-checks' );
1460 wfProfileOut( __METHOD__ );
1461
1462 return $status;
1463 }
1464
1465 # Check for spam
1466 $match = self::matchSummarySpamRegex( $this->summary );
1467 if ( $match === false && $this->section == 'new' ) {
1468 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1469 # regular summaries, it is added to the actual wikitext.
1470 if ( $this->sectiontitle !== '' ) {
1471 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1472 $match = self::matchSpamRegex( $this->sectiontitle );
1473 } else {
1474 # This branch is taken when the "Add Topic" user interface is used, or the API
1475 # is used with the 'summary' parameter.
1476 $match = self::matchSpamRegex( $this->summary );
1477 }
1478 }
1479 if ( $match === false ) {
1480 $match = self::matchSpamRegex( $this->textbox1 );
1481 }
1482 if ( $match !== false ) {
1483 $result['spam'] = $match;
1484 $ip = $wgRequest->getIP();
1485 $pdbk = $this->mTitle->getPrefixedDBkey();
1486 $match = str_replace( "\n", '', $match );
1487 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1488 $status->fatal( 'spamprotectionmatch', $match );
1489 $status->value = self::AS_SPAM_ERROR;
1490 wfProfileOut( __METHOD__ . '-checks' );
1491 wfProfileOut( __METHOD__ );
1492 return $status;
1493 }
1494 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) ) ) {
1495 # Error messages etc. could be handled within the hook...
1496 $status->fatal( 'hookaborted' );
1497 $status->value = self::AS_HOOK_ERROR;
1498 wfProfileOut( __METHOD__ . '-checks' );
1499 wfProfileOut( __METHOD__ );
1500 return $status;
1501 } elseif ( $this->hookError != '' ) {
1502 # ...or the hook could be expecting us to produce an error
1503 $status->fatal( 'hookaborted' );
1504 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1505 wfProfileOut( __METHOD__ . '-checks' );
1506 wfProfileOut( __METHOD__ );
1507 return $status;
1508 }
1509
1510 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1511 // Auto-block user's IP if the account was "hard" blocked
1512 $wgUser->spreadAnyEditBlock();
1513 # Check block state against master, thus 'false'.
1514 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1515 wfProfileOut( __METHOD__ . '-checks' );
1516 wfProfileOut( __METHOD__ );
1517 return $status;
1518 }
1519
1520 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1521 if ( $this->kblength > $wgMaxArticleSize ) {
1522 // Error will be displayed by showEditForm()
1523 $this->tooBig = true;
1524 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1525 wfProfileOut( __METHOD__ . '-checks' );
1526 wfProfileOut( __METHOD__ );
1527 return $status;
1528 }
1529
1530 if ( !$wgUser->isAllowed( 'edit' ) ) {
1531 if ( $wgUser->isAnon() ) {
1532 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1533 wfProfileOut( __METHOD__ . '-checks' );
1534 wfProfileOut( __METHOD__ );
1535 return $status;
1536 } else {
1537 $status->fatal( 'readonlytext' );
1538 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1539 wfProfileOut( __METHOD__ . '-checks' );
1540 wfProfileOut( __METHOD__ );
1541 return $status;
1542 }
1543 }
1544
1545 if ( wfReadOnly() ) {
1546 $status->fatal( 'readonlytext' );
1547 $status->value = self::AS_READ_ONLY_PAGE;
1548 wfProfileOut( __METHOD__ . '-checks' );
1549 wfProfileOut( __METHOD__ );
1550 return $status;
1551 }
1552 if ( $wgUser->pingLimiter() || $wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1553 $status->fatal( 'actionthrottledtext' );
1554 $status->value = self::AS_RATE_LIMITED;
1555 wfProfileOut( __METHOD__ . '-checks' );
1556 wfProfileOut( __METHOD__ );
1557 return $status;
1558 }
1559
1560 # If the article has been deleted while editing, don't save it without
1561 # confirmation
1562 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1563 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1564 wfProfileOut( __METHOD__ . '-checks' );
1565 wfProfileOut( __METHOD__ );
1566 return $status;
1567 }
1568
1569 wfProfileOut( __METHOD__ . '-checks' );
1570
1571 # Load the page data from the master. If anything changes in the meantime,
1572 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1573 $this->mArticle->loadPageData( 'fromdbmaster' );
1574 $new = !$this->mArticle->exists();
1575
1576 if ( $new ) {
1577 // Late check for create permission, just in case *PARANOIA*
1578 if ( !$this->mTitle->userCan( 'create', $wgUser ) ) {
1579 $status->fatal( 'nocreatetext' );
1580 $status->value = self::AS_NO_CREATE_PERMISSION;
1581 wfDebug( __METHOD__ . ": no create permission\n" );
1582 wfProfileOut( __METHOD__ );
1583 return $status;
1584 }
1585
1586 // Don't save a new page if it's blank or if it's a MediaWiki:
1587 // message with content equivalent to default (allow empty pages
1588 // in this case to disable messages, see bug 50124)
1589 $defaultMessageText = $this->mTitle->getDefaultMessageText();
1590 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1591 $defaultText = $defaultMessageText;
1592 } else {
1593 $defaultText = '';
1594 }
1595
1596 if ( $this->textbox1 === $defaultText ) {
1597 $status->setResult( false, self::AS_BLANK_ARTICLE );
1598 wfProfileOut( __METHOD__ );
1599 return $status;
1600 }
1601
1602 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1603 wfProfileOut( __METHOD__ );
1604 return $status;
1605 }
1606
1607 $content = $textbox_content;
1608
1609 $result['sectionanchor'] = '';
1610 if ( $this->section == 'new' ) {
1611 if ( $this->sectiontitle !== '' ) {
1612 // Insert the section title above the content.
1613 $content = $content->addSectionHeader( $this->sectiontitle );
1614
1615 // Jump to the new section
1616 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1617
1618 // If no edit summary was specified, create one automatically from the section
1619 // title and have it link to the new section. Otherwise, respect the summary as
1620 // passed.
1621 if ( $this->summary === '' ) {
1622 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1623 $this->summary = wfMessage( 'newsectionsummary' )
1624 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1625 }
1626 } elseif ( $this->summary !== '' ) {
1627 // Insert the section title above the content.
1628 $content = $content->addSectionHeader( $this->summary );
1629
1630 // Jump to the new section
1631 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1632
1633 // Create a link to the new section from the edit summary.
1634 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1635 $this->summary = wfMessage( 'newsectionsummary' )
1636 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1637 }
1638 }
1639
1640 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1641
1642 } else { # not $new
1643
1644 # Article exists. Check for edit conflict.
1645
1646 $this->mArticle->clear(); # Force reload of dates, etc.
1647 $timestamp = $this->mArticle->getTimestamp();
1648
1649 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1650
1651 if ( $timestamp != $this->edittime ) {
1652 $this->isConflict = true;
1653 if ( $this->section == 'new' ) {
1654 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
1655 $this->mArticle->getComment() == $this->summary ) {
1656 // Probably a duplicate submission of a new comment.
1657 // This can happen when squid resends a request after
1658 // a timeout but the first one actually went through.
1659 wfDebug( __METHOD__ . ": duplicate new section submission; trigger edit conflict!\n" );
1660 } else {
1661 // New comment; suppress conflict.
1662 $this->isConflict = false;
1663 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1664 }
1665 } elseif ( $this->section == '' && Revision::userWasLastToEdit( DB_MASTER, $this->mTitle->getArticleID(),
1666 $wgUser->getId(), $this->edittime ) ) {
1667 # Suppress edit conflict with self, except for section edits where merging is required.
1668 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1669 $this->isConflict = false;
1670 }
1671 }
1672
1673 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1674 if ( $this->sectiontitle !== '' ) {
1675 $sectionTitle = $this->sectiontitle;
1676 } else {
1677 $sectionTitle = $this->summary;
1678 }
1679
1680 $content = null;
1681
1682 if ( $this->isConflict ) {
1683 wfDebug( __METHOD__ . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1684 . " (article time '{$timestamp}')\n" );
1685
1686 $content = $this->mArticle->replaceSectionContent( $this->section, $textbox_content, $sectionTitle, $this->edittime );
1687 } else {
1688 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
1689 $content = $this->mArticle->replaceSectionContent( $this->section, $textbox_content, $sectionTitle );
1690 }
1691
1692 if ( is_null( $content ) ) {
1693 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1694 $this->isConflict = true;
1695 $content = $textbox_content; // do not try to merge here!
1696 } elseif ( $this->isConflict ) {
1697 # Attempt merge
1698 if ( $this->mergeChangesIntoContent( $content ) ) {
1699 // Successful merge! Maybe we should tell the user the good news?
1700 $this->isConflict = false;
1701 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1702 } else {
1703 $this->section = '';
1704 $this->textbox1 = ContentHandler::getContentText( $content );
1705 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1706 }
1707 }
1708
1709 if ( $this->isConflict ) {
1710 $status->setResult( false, self::AS_CONFLICT_DETECTED );
1711 wfProfileOut( __METHOD__ );
1712 return $status;
1713 }
1714
1715 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1716 wfProfileOut( __METHOD__ );
1717 return $status;
1718 }
1719
1720 if ( $this->section == 'new' ) {
1721 // Handle the user preference to force summaries here
1722 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
1723 $this->missingSummary = true;
1724 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1725 $status->value = self::AS_SUMMARY_NEEDED;
1726 wfProfileOut( __METHOD__ );
1727 return $status;
1728 }
1729
1730 // Do not allow the user to post an empty comment
1731 if ( $this->textbox1 == '' ) {
1732 $this->missingComment = true;
1733 $status->fatal( 'missingcommenttext' );
1734 $status->value = self::AS_TEXTBOX_EMPTY;
1735 wfProfileOut( __METHOD__ );
1736 return $status;
1737 }
1738 } elseif ( !$this->allowBlankSummary
1739 && !$content->equals( $this->getOriginalContent() )
1740 && !$content->isRedirect()
1741 && md5( $this->summary ) == $this->autoSumm
1742 ) {
1743 $this->missingSummary = true;
1744 $status->fatal( 'missingsummary' );
1745 $status->value = self::AS_SUMMARY_NEEDED;
1746 wfProfileOut( __METHOD__ );
1747 return $status;
1748 }
1749
1750 # All's well
1751 wfProfileIn( __METHOD__ . '-sectionanchor' );
1752 $sectionanchor = '';
1753 if ( $this->section == 'new' ) {
1754 if ( $this->sectiontitle !== '' ) {
1755 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1756 // If no edit summary was specified, create one automatically from the section
1757 // title and have it link to the new section. Otherwise, respect the summary as
1758 // passed.
1759 if ( $this->summary === '' ) {
1760 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1761 $this->summary = wfMessage( 'newsectionsummary' )
1762 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1763 }
1764 } elseif ( $this->summary !== '' ) {
1765 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1766 # This is a new section, so create a link to the new section
1767 # in the revision summary.
1768 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1769 $this->summary = wfMessage( 'newsectionsummary' )
1770 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1771 }
1772 } elseif ( $this->section != '' ) {
1773 # Try to get a section anchor from the section source, redirect to edited section if header found
1774 # XXX: might be better to integrate this into Article::replaceSection
1775 # for duplicate heading checking and maybe parsing
1776 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1777 # we can't deal with anchors, includes, html etc in the header for now,
1778 # headline would need to be parsed to improve this
1779 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1780 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1781 }
1782 }
1783 $result['sectionanchor'] = $sectionanchor;
1784 wfProfileOut( __METHOD__ . '-sectionanchor' );
1785
1786 // Save errors may fall down to the edit form, but we've now
1787 // merged the section into full text. Clear the section field
1788 // so that later submission of conflict forms won't try to
1789 // replace that into a duplicated mess.
1790 $this->textbox1 = $this->toEditText( $content );
1791 $this->section = '';
1792
1793 $status->value = self::AS_SUCCESS_UPDATE;
1794 }
1795
1796 // Check for length errors again now that the section is merged in
1797 $this->kblength = (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1798 if ( $this->kblength > $wgMaxArticleSize ) {
1799 $this->tooBig = true;
1800 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
1801 wfProfileOut( __METHOD__ );
1802 return $status;
1803 }
1804
1805 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1806 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
1807 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
1808 ( $bot ? EDIT_FORCE_BOT : 0 );
1809
1810 $doEditStatus = $this->mArticle->doEditContent( $content, $this->summary, $flags,
1811 false, null, $this->contentFormat );
1812
1813 if ( !$doEditStatus->isOK() ) {
1814 // Failure from doEdit()
1815 // Show the edit conflict page for certain recognized errors from doEdit(),
1816 // but don't show it for errors from extension hooks
1817 $errors = $doEditStatus->getErrorsArray();
1818 if ( in_array( $errors[0][0],
1819 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
1820 ) {
1821 $this->isConflict = true;
1822 // Destroys data doEdit() put in $status->value but who cares
1823 $doEditStatus->value = self::AS_END;
1824 }
1825 wfProfileOut( __METHOD__ );
1826 return $doEditStatus;
1827 }
1828
1829 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1830 if ( $result['nullEdit'] ) {
1831 // We don't know if it was a null edit until now, so increment here
1832 $wgUser->pingLimiter( 'linkpurge' );
1833 }
1834 $result['redirect'] = $content->isRedirect();
1835 $this->updateWatchlist();
1836 wfProfileOut( __METHOD__ );
1837 return $status;
1838 }
1839
1840 /**
1841 * Register the change of watch status
1842 */
1843 protected function updateWatchlist() {
1844 global $wgUser;
1845
1846 if ( $wgUser->isLoggedIn()
1847 && $this->watchthis != $wgUser->isWatched( $this->mTitle, WatchedItem::IGNORE_USER_RIGHTS )
1848 ) {
1849 $fname = __METHOD__;
1850 $title = $this->mTitle;
1851 $watch = $this->watchthis;
1852
1853 // Do this in its own transaction to reduce contention...
1854 $dbw = wfGetDB( DB_MASTER );
1855 $dbw->onTransactionIdle( function() use ( $dbw, $title, $watch, $wgUser, $fname ) {
1856 $dbw->begin( $fname );
1857 WatchAction::doWatchOrUnwatch( $watch, $title, $wgUser );
1858 $dbw->commit( $fname );
1859 } );
1860 }
1861 }
1862
1863 /**
1864 * Attempts to merge text content with base and current revisions
1865 *
1866 * @param $editText string
1867 *
1868 * @return bool
1869 * @deprecated since 1.21, use mergeChangesIntoContent() instead
1870 */
1871 function mergeChangesInto( &$editText ) {
1872 ContentHandler::deprecated( __METHOD__, "1.21" );
1873
1874 $editContent = $this->toEditContent( $editText );
1875
1876 $ok = $this->mergeChangesIntoContent( $editContent );
1877
1878 if ( $ok ) {
1879 $editText = $this->toEditText( $editContent );
1880 return true;
1881 }
1882 return false;
1883 }
1884
1885 /**
1886 * Attempts to do 3-way merge of edit content with a base revision
1887 * and current content, in case of edit conflict, in whichever way appropriate
1888 * for the content type.
1889 *
1890 * @since 1.21
1891 *
1892 * @param $editContent
1893 *
1894 * @return bool
1895 */
1896 private function mergeChangesIntoContent( &$editContent ) {
1897 wfProfileIn( __METHOD__ );
1898
1899 $db = wfGetDB( DB_MASTER );
1900
1901 // This is the revision the editor started from
1902 $baseRevision = $this->getBaseRevision();
1903 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
1904
1905 if ( is_null( $baseContent ) ) {
1906 wfProfileOut( __METHOD__ );
1907 return false;
1908 }
1909
1910 // The current state, we want to merge updates into it
1911 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
1912 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
1913
1914 if ( is_null( $currentContent ) ) {
1915 wfProfileOut( __METHOD__ );
1916 return false;
1917 }
1918
1919 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
1920
1921 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1922
1923 if ( $result ) {
1924 $editContent = $result;
1925 wfProfileOut( __METHOD__ );
1926 return true;
1927 }
1928
1929 wfProfileOut( __METHOD__ );
1930 return false;
1931 }
1932
1933 /**
1934 * @return Revision
1935 */
1936 function getBaseRevision() {
1937 if ( !$this->mBaseRevision ) {
1938 $db = wfGetDB( DB_MASTER );
1939 $this->mBaseRevision = Revision::loadFromTimestamp(
1940 $db, $this->mTitle, $this->edittime );
1941 }
1942 return $this->mBaseRevision;
1943 }
1944
1945 /**
1946 * Check given input text against $wgSpamRegex, and return the text of the first match.
1947 *
1948 * @param $text string
1949 *
1950 * @return string|bool matching string or false
1951 */
1952 public static function matchSpamRegex( $text ) {
1953 global $wgSpamRegex;
1954 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1955 $regexes = (array)$wgSpamRegex;
1956 return self::matchSpamRegexInternal( $text, $regexes );
1957 }
1958
1959 /**
1960 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
1961 *
1962 * @param $text string
1963 *
1964 * @return string|bool matching string or false
1965 */
1966 public static function matchSummarySpamRegex( $text ) {
1967 global $wgSummarySpamRegex;
1968 $regexes = (array)$wgSummarySpamRegex;
1969 return self::matchSpamRegexInternal( $text, $regexes );
1970 }
1971
1972 /**
1973 * @param $text string
1974 * @param $regexes array
1975 * @return bool|string
1976 */
1977 protected static function matchSpamRegexInternal( $text, $regexes ) {
1978 foreach ( $regexes as $regex ) {
1979 $matches = array();
1980 if ( preg_match( $regex, $text, $matches ) ) {
1981 return $matches[0];
1982 }
1983 }
1984 return false;
1985 }
1986
1987 function setHeaders() {
1988 global $wgOut, $wgUser;
1989
1990 $wgOut->addModules( 'mediawiki.action.edit' );
1991 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
1992
1993 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1994 $wgOut->addModules( 'mediawiki.action.edit.preview' );
1995 }
1996
1997 if ( $wgUser->getOption( 'useeditwarning', false ) ) {
1998 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
1999 }
2000
2001 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2002
2003 # Enabled article-related sidebar, toplinks, etc.
2004 $wgOut->setArticleRelated( true );
2005
2006 $contextTitle = $this->getContextTitle();
2007 if ( $this->isConflict ) {
2008 $msg = 'editconflict';
2009 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2010 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2011 } else {
2012 $msg = $contextTitle->exists() || ( $contextTitle->getNamespace() == NS_MEDIAWIKI && $contextTitle->getDefaultMessageText() !== false ) ?
2013 'editing' : 'creating';
2014 }
2015 # Use the title defined by DISPLAYTITLE magic word when present
2016 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2017 if ( $displayTitle === false ) {
2018 $displayTitle = $contextTitle->getPrefixedText();
2019 }
2020 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2021 }
2022
2023 /**
2024 * Show all applicable editing introductions
2025 */
2026 protected function showIntro() {
2027 global $wgOut, $wgUser;
2028 if ( $this->suppressIntro ) {
2029 return;
2030 }
2031
2032 $namespace = $this->mTitle->getNamespace();
2033
2034 if ( $namespace == NS_MEDIAWIKI ) {
2035 # Show a warning if editing an interface message
2036 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2037 } elseif ( $namespace == NS_FILE ) {
2038 # Show a hint to shared repo
2039 $file = wfFindFile( $this->mTitle );
2040 if ( $file && !$file->isLocal() ) {
2041 $descUrl = $file->getDescriptionUrl();
2042 # there must be a description url to show a hint to shared repo
2043 if ( $descUrl ) {
2044 if ( !$this->mTitle->exists() ) {
2045 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2046 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2047 ) );
2048 } else {
2049 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2050 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2051 ) );
2052 }
2053 }
2054 }
2055 }
2056
2057 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2058 # Show log extract when the user is currently blocked
2059 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2060 $parts = explode( '/', $this->mTitle->getText(), 2 );
2061 $username = $parts[0];
2062 $user = User::newFromName( $username, false /* allow IP users*/ );
2063 $ip = User::isIP( $username );
2064 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2065 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2066 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2067 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
2068 LogEventsList::showLogExtract(
2069 $wgOut,
2070 'block',
2071 $user->getUserPage(),
2072 '',
2073 array(
2074 'lim' => 1,
2075 'showIfEmpty' => false,
2076 'msgKey' => array(
2077 'blocked-notice-logextract',
2078 $user->getName() # Support GENDER in notice
2079 )
2080 )
2081 );
2082 }
2083 }
2084 # Try to add a custom edit intro, or use the standard one if this is not possible.
2085 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2086 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2087 wfMessage( 'helppage' )->inContentLanguage()->text()
2088 ) );
2089 if ( $wgUser->isLoggedIn() ) {
2090 $wgOut->wrapWikiMsg(
2091 // Suppress the external link icon, consider the help url an internal one
2092 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2093 array(
2094 'newarticletext',
2095 $helpLink
2096 )
2097 );
2098 } else {
2099 $wgOut->wrapWikiMsg(
2100 // Suppress the external link icon, consider the help url an internal one
2101 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2102 array(
2103 'newarticletextanon',
2104 $helpLink
2105 )
2106 );
2107 }
2108 }
2109 # Give a notice if the user is editing a deleted/moved page...
2110 if ( !$this->mTitle->exists() ) {
2111 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
2112 '',
2113 array(
2114 'lim' => 10,
2115 'conds' => array( "log_action != 'revision'" ),
2116 'showIfEmpty' => false,
2117 'msgKey' => array( 'recreate-moveddeleted-warn' )
2118 )
2119 );
2120 }
2121 }
2122
2123 /**
2124 * Attempt to show a custom editing introduction, if supplied
2125 *
2126 * @return bool
2127 */
2128 protected function showCustomIntro() {
2129 if ( $this->editintro ) {
2130 $title = Title::newFromText( $this->editintro );
2131 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2132 global $wgOut;
2133 // Added using template syntax, to take <noinclude>'s into account.
2134 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle );
2135 return true;
2136 }
2137 }
2138 return false;
2139 }
2140
2141 /**
2142 * Gets an editable textual representation of $content.
2143 * The textual representation can be turned by into a Content object by the
2144 * toEditContent() method.
2145 *
2146 * If $content is null or false or a string, $content is returned unchanged.
2147 *
2148 * If the given Content object is not of a type that can be edited using the text base EditPage,
2149 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2150 * content.
2151 *
2152 * @param Content|null|bool|string $content
2153 * @return String the editable text form of the content.
2154 *
2155 * @throws MWException if $content is not an instance of TextContent and $this->allowNonTextContent is not true.
2156 */
2157 protected function toEditText( $content ) {
2158 if ( $content === null || $content === false ) {
2159 return $content;
2160 }
2161
2162 if ( is_string( $content ) ) {
2163 return $content;
2164 }
2165
2166 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2167 throw new MWException( 'This content model is not supported: '
2168 . ContentHandler::getLocalizedName( $content->getModel() ) );
2169 }
2170
2171 return $content->serialize( $this->contentFormat );
2172 }
2173
2174 /**
2175 * Turns the given text into a Content object by unserializing it.
2176 *
2177 * If the resulting Content object is not of a type that can be edited using the text base EditPage,
2178 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2179 * content.
2180 *
2181 * @param string|null|bool $text Text to unserialize
2182 * @return Content The content object created from $text. If $text was false or null, false resp. null will be
2183 * returned instead.
2184 *
2185 * @throws MWException if unserializing the text results in a Content object that is not an instance of TextContent
2186 * and $this->allowNonTextContent is not true.
2187 */
2188 protected function toEditContent( $text ) {
2189 if ( $text === false || $text === null ) {
2190 return $text;
2191 }
2192
2193 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2194 $this->contentModel, $this->contentFormat );
2195
2196 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2197 throw new MWException( 'This content model is not supported: '
2198 . ContentHandler::getLocalizedName( $content->getModel() ) );
2199 }
2200
2201 return $content;
2202 }
2203
2204 /**
2205 * Send the edit form and related headers to $wgOut
2206 * @param $formCallback Callback|null that takes an OutputPage parameter; will be called
2207 * during form output near the top, for captchas and the like.
2208 */
2209 function showEditForm( $formCallback = null ) {
2210 global $wgOut, $wgUser;
2211
2212 wfProfileIn( __METHOD__ );
2213
2214 # need to parse the preview early so that we know which templates are used,
2215 # otherwise users with "show preview after edit box" will get a blank list
2216 # we parse this near the beginning so that setHeaders can do the title
2217 # setting work instead of leaving it in getPreviewText
2218 $previewOutput = '';
2219 if ( $this->formtype == 'preview' ) {
2220 $previewOutput = $this->getPreviewText();
2221 }
2222
2223 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2224
2225 $this->setHeaders();
2226
2227 if ( $this->showHeader() === false ) {
2228 wfProfileOut( __METHOD__ );
2229 return;
2230 }
2231
2232 $wgOut->addHTML( $this->editFormPageTop );
2233
2234 if ( $wgUser->getOption( 'previewontop' ) ) {
2235 $this->displayPreviewArea( $previewOutput, true );
2236 }
2237
2238 $wgOut->addHTML( $this->editFormTextTop );
2239
2240 $showToolbar = true;
2241 if ( $this->wasDeletedSinceLastEdit() ) {
2242 if ( $this->formtype == 'save' ) {
2243 // Hide the toolbar and edit area, user can click preview to get it back
2244 // Add an confirmation checkbox and explanation.
2245 $showToolbar = false;
2246 } else {
2247 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2248 'deletedwhileediting' );
2249 }
2250 }
2251
2252 // @todo add EditForm plugin interface and use it here!
2253 // search for textarea1 and textares2, and allow EditForm to override all uses.
2254 $wgOut->addHTML( Html::openElement( 'form', array( 'id' => self::EDITFORM_ID, 'name' => self::EDITFORM_ID,
2255 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
2256 'enctype' => 'multipart/form-data' ) ) );
2257
2258 if ( is_callable( $formCallback ) ) {
2259 call_user_func_array( $formCallback, array( &$wgOut ) );
2260 }
2261
2262 // Add an empty field to trip up spambots
2263 $wgOut->addHTML(
2264 Xml::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2265 . Html::rawElement( 'label', array( 'for' => 'wpAntiSpam' ), wfMessage( 'simpleantispam-label' )->parse() )
2266 . Xml::element( 'input', array( 'type' => 'text', 'name' => 'wpAntispam', 'id' => 'wpAntispam', 'value' => '' ) )
2267 . Xml::closeElement( 'div' )
2268 );
2269
2270 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2271
2272 // Put these up at the top to ensure they aren't lost on early form submission
2273 $this->showFormBeforeText();
2274
2275 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2276 $username = $this->lastDelete->user_name;
2277 $comment = $this->lastDelete->log_comment;
2278
2279 // It is better to not parse the comment at all than to have templates expanded in the middle
2280 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2281 $key = $comment === ''
2282 ? 'confirmrecreate-noreason'
2283 : 'confirmrecreate';
2284 $wgOut->addHTML(
2285 '<div class="mw-confirm-recreate">' .
2286 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2287 Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2288 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2289 ) .
2290 '</div>'
2291 );
2292 }
2293
2294 # When the summary is hidden, also hide them on preview/show changes
2295 if ( $this->nosummary ) {
2296 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2297 }
2298
2299 # If a blank edit summary was previously provided, and the appropriate
2300 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2301 # user being bounced back more than once in the event that a summary
2302 # is not required.
2303 #####
2304 # For a bit more sophisticated detection of blank summaries, hash the
2305 # automatic one and pass that in the hidden field wpAutoSummary.
2306 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2307 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2308 }
2309
2310 if ( $this->undidRev ) {
2311 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2312 }
2313
2314 if ( $this->hasPresetSummary ) {
2315 // If a summary has been preset using &summary= we don't want to prompt for
2316 // a different summary. Only prompt for a summary if the summary is blanked.
2317 // (Bug 17416)
2318 $this->autoSumm = md5( '' );
2319 }
2320
2321 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2322 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2323
2324 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2325
2326 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2327 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2328
2329 if ( $this->section == 'new' ) {
2330 $this->showSummaryInput( true, $this->summary );
2331 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2332 }
2333
2334 $wgOut->addHTML( $this->editFormTextBeforeContent );
2335
2336 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2337 $wgOut->addHTML( EditPage::getEditToolbar() );
2338 }
2339
2340 if ( $this->isConflict ) {
2341 // In an edit conflict bypass the overridable content form method
2342 // and fallback to the raw wpTextbox1 since editconflicts can't be
2343 // resolved between page source edits and custom ui edits using the
2344 // custom edit ui.
2345 $this->textbox2 = $this->textbox1;
2346
2347 $content = $this->getCurrentContent();
2348 $this->textbox1 = $this->toEditText( $content );
2349
2350 $this->showTextbox1();
2351 } else {
2352 $this->showContentForm();
2353 }
2354
2355 $wgOut->addHTML( $this->editFormTextAfterContent );
2356
2357 $this->showStandardInputs();
2358
2359 $this->showFormAfterText();
2360
2361 $this->showTosSummary();
2362
2363 $this->showEditTools();
2364
2365 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2366
2367 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2368 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
2369
2370 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
2371 Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
2372
2373 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'limitreport' ),
2374 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2375
2376 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2377
2378 if ( $this->isConflict ) {
2379 try {
2380 $this->showConflict();
2381 } catch ( MWContentSerializationException $ex ) {
2382 // this can't really happen, but be nice if it does.
2383 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
2384 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2385 }
2386 }
2387
2388 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2389
2390 if ( !$wgUser->getOption( 'previewontop' ) ) {
2391 $this->displayPreviewArea( $previewOutput, false );
2392 }
2393
2394 wfProfileOut( __METHOD__ );
2395 }
2396
2397 /**
2398 * Extract the section title from current section text, if any.
2399 *
2400 * @param string $text
2401 * @return Mixed|string or false
2402 */
2403 public static function extractSectionTitle( $text ) {
2404 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2405 if ( !empty( $matches[2] ) ) {
2406 global $wgParser;
2407 return $wgParser->stripSectionName( trim( $matches[2] ) );
2408 } else {
2409 return false;
2410 }
2411 }
2412
2413 protected function showHeader() {
2414 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2415
2416 if ( $this->mTitle->isTalkPage() ) {
2417 $wgOut->addWikiMsg( 'talkpagetext' );
2418 }
2419
2420 // Add edit notices
2421 $wgOut->addHTML( implode( "\n", $this->mTitle->getEditNotices( $this->oldid ) ) );
2422
2423 if ( $this->isConflict ) {
2424 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2425 $this->edittime = $this->mArticle->getTimestamp();
2426 } else {
2427 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
2428 // We use $this->section to much before this and getVal('wgSection') directly in other places
2429 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2430 // Someone is welcome to try refactoring though
2431 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2432 return false;
2433 }
2434
2435 if ( $this->section != '' && $this->section != 'new' ) {
2436 if ( !$this->summary && !$this->preview && !$this->diff ) {
2437 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); //FIXME: use Content object
2438 if ( $sectionTitle !== false ) {
2439 $this->summary = "/* $sectionTitle */ ";
2440 }
2441 }
2442 }
2443
2444 if ( $this->missingComment ) {
2445 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2446 }
2447
2448 if ( $this->missingSummary && $this->section != 'new' ) {
2449 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2450 }
2451
2452 if ( $this->missingSummary && $this->section == 'new' ) {
2453 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2454 }
2455
2456 if ( $this->hookError !== '' ) {
2457 $wgOut->addWikiText( $this->hookError );
2458 }
2459
2460 if ( !$this->checkUnicodeCompliantBrowser() ) {
2461 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2462 }
2463
2464 if ( $this->section != 'new' ) {
2465 $revision = $this->mArticle->getRevisionFetched();
2466 if ( $revision ) {
2467 // Let sysop know that this will make private content public if saved
2468
2469 if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2470 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2471 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2472 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2473 }
2474
2475 if ( !$revision->isCurrent() ) {
2476 $this->mArticle->setOldSubtitle( $revision->getId() );
2477 $wgOut->addWikiMsg( 'editingold' );
2478 }
2479 } elseif ( $this->mTitle->exists() ) {
2480 // Something went wrong
2481
2482 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2483 array( 'missing-revision', $this->oldid ) );
2484 }
2485 }
2486 }
2487
2488 if ( wfReadOnly() ) {
2489 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2490 } elseif ( $wgUser->isAnon() ) {
2491 if ( $this->formtype != 'preview' ) {
2492 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2493 } else {
2494 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2495 }
2496 } else {
2497 if ( $this->isCssJsSubpage ) {
2498 # Check the skin exists
2499 if ( $this->isWrongCaseCssJsPage ) {
2500 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
2501 }
2502 if ( $this->formtype !== 'preview' ) {
2503 if ( $this->isCssSubpage ) {
2504 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2505 }
2506
2507 if ( $this->isJsSubpage ) {
2508 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2509 }
2510 }
2511 }
2512 }
2513
2514 if ( $this->mTitle->isProtected( 'edit' ) &&
2515 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2516 ) {
2517 # Is the title semi-protected?
2518 if ( $this->mTitle->isSemiProtected() ) {
2519 $noticeMsg = 'semiprotectedpagewarning';
2520 } else {
2521 # Then it must be protected based on static groups (regular)
2522 $noticeMsg = 'protectedpagewarning';
2523 }
2524 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2525 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2526 }
2527 if ( $this->mTitle->isCascadeProtected() ) {
2528 # Is this page under cascading protection from some source pages?
2529 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2530 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2531 $cascadeSourcesCount = count( $cascadeSources );
2532 if ( $cascadeSourcesCount > 0 ) {
2533 # Explain, and list the titles responsible
2534 foreach ( $cascadeSources as $page ) {
2535 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2536 }
2537 }
2538 $notice .= '</div>';
2539 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2540 }
2541 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2542 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2543 array( 'lim' => 1,
2544 'showIfEmpty' => false,
2545 'msgKey' => array( 'titleprotectedwarning' ),
2546 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2547 }
2548
2549 if ( $this->kblength === false ) {
2550 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2551 }
2552
2553 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2554 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2555 array( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2556 } else {
2557 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2558 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2559 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 ) )
2560 );
2561 }
2562 }
2563 # Add header copyright warning
2564 $this->showHeaderCopyrightWarning();
2565 }
2566
2567 /**
2568 * Standard summary input and label (wgSummary), abstracted so EditPage
2569 * subclasses may reorganize the form.
2570 * Note that you do not need to worry about the label's for=, it will be
2571 * inferred by the id given to the input. You can remove them both by
2572 * passing array( 'id' => false ) to $userInputAttrs.
2573 *
2574 * @param string $summary The value of the summary input
2575 * @param string $labelText The html to place inside the label
2576 * @param array $inputAttrs of attrs to use on the input
2577 * @param array $spanLabelAttrs of attrs to use on the span inside the label
2578 *
2579 * @return array An array in the format array( $label, $input )
2580 */
2581 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2582 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2583 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2584 'id' => 'wpSummary',
2585 'maxlength' => '200',
2586 'tabindex' => '1',
2587 'size' => 60,
2588 'spellcheck' => 'true',
2589 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2590
2591 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2592 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2593 'id' => "wpSummaryLabel"
2594 );
2595
2596 $label = null;
2597 if ( $labelText ) {
2598 $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2599 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2600 }
2601
2602 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2603
2604 return array( $label, $input );
2605 }
2606
2607 /**
2608 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2609 * up top, or false if this is the comment summary
2610 * down below the textarea
2611 * @param string $summary The text of the summary to display
2612 * @return String
2613 */
2614 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2615 global $wgOut, $wgContLang;
2616 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2617 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2618 if ( $isSubjectPreview ) {
2619 if ( $this->nosummary ) {
2620 return;
2621 }
2622 } else {
2623 if ( !$this->mShowSummaryField ) {
2624 return;
2625 }
2626 }
2627 $summary = $wgContLang->recodeForEdit( $summary );
2628 $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
2629 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2630 $wgOut->addHTML( "{$label} {$input}" );
2631 }
2632
2633 /**
2634 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2635 * up top, or false if this is the comment summary
2636 * down below the textarea
2637 * @param string $summary the text of the summary to display
2638 * @return String
2639 */
2640 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2641 // avoid spaces in preview, gets always trimmed on save
2642 $summary = trim( $summary );
2643 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
2644 return "";
2645 }
2646
2647 global $wgParser;
2648
2649 if ( $isSubjectPreview ) {
2650 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2651 ->inContentLanguage()->text();
2652 }
2653
2654 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
2655
2656 $summary = wfMessage( $message )->parse() . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
2657 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2658 }
2659
2660 protected function showFormBeforeText() {
2661 global $wgOut;
2662 $section = htmlspecialchars( $this->section );
2663 $wgOut->addHTML( <<<HTML
2664 <input type='hidden' value="{$section}" name="wpSection" />
2665 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2666 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2667 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2668
2669 HTML
2670 );
2671 if ( !$this->checkUnicodeCompliantBrowser() ) {
2672 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
2673 }
2674 }
2675
2676 protected function showFormAfterText() {
2677 global $wgOut, $wgUser;
2678 /**
2679 * To make it harder for someone to slip a user a page
2680 * which submits an edit form to the wiki without their
2681 * knowledge, a random token is associated with the login
2682 * session. If it's not passed back with the submission,
2683 * we won't save the page, or render user JavaScript and
2684 * CSS previews.
2685 *
2686 * For anon editors, who may not have a session, we just
2687 * include the constant suffix to prevent editing from
2688 * broken text-mangling proxies.
2689 */
2690 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2691 }
2692
2693 /**
2694 * Subpage overridable method for printing the form for page content editing
2695 * By default this simply outputs wpTextbox1
2696 * Subclasses can override this to provide a custom UI for editing;
2697 * be it a form, or simply wpTextbox1 with a modified content that will be
2698 * reverse modified when extracted from the post data.
2699 * Note that this is basically the inverse for importContentFormData
2700 */
2701 protected function showContentForm() {
2702 $this->showTextbox1();
2703 }
2704
2705 /**
2706 * Method to output wpTextbox1
2707 * The $textoverride method can be used by subclasses overriding showContentForm
2708 * to pass back to this method.
2709 *
2710 * @param array $customAttribs of html attributes to use in the textarea
2711 * @param string $textoverride optional text to override $this->textarea1 with
2712 */
2713 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2714 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2715 $attribs = array( 'style' => 'display:none;' );
2716 } else {
2717 $classes = array(); // Textarea CSS
2718 if ( $this->mTitle->isProtected( 'edit' ) &&
2719 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2720 ) {
2721 # Is the title semi-protected?
2722 if ( $this->mTitle->isSemiProtected() ) {
2723 $classes[] = 'mw-textarea-sprotected';
2724 } else {
2725 # Then it must be protected based on static groups (regular)
2726 $classes[] = 'mw-textarea-protected';
2727 }
2728 # Is the title cascade-protected?
2729 if ( $this->mTitle->isCascadeProtected() ) {
2730 $classes[] = 'mw-textarea-cprotected';
2731 }
2732 }
2733
2734 $attribs = array( 'tabindex' => 1 );
2735
2736 if ( is_array( $customAttribs ) ) {
2737 $attribs += $customAttribs;
2738 }
2739
2740 if ( count( $classes ) ) {
2741 if ( isset( $attribs['class'] ) ) {
2742 $classes[] = $attribs['class'];
2743 }
2744 $attribs['class'] = implode( ' ', $classes );
2745 }
2746 }
2747
2748 $this->showTextbox( $textoverride !== null ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
2749 }
2750
2751 protected function showTextbox2() {
2752 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2753 }
2754
2755 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2756 global $wgOut, $wgUser;
2757
2758 $wikitext = $this->safeUnicodeOutput( $text );
2759 if ( strval( $wikitext ) !== '' ) {
2760 // Ensure there's a newline at the end, otherwise adding lines
2761 // is awkward.
2762 // But don't add a newline if the ext is empty, or Firefox in XHTML
2763 // mode will show an extra newline. A bit annoying.
2764 $wikitext .= "\n";
2765 }
2766
2767 $attribs = $customAttribs + array(
2768 'accesskey' => ',',
2769 'id' => $name,
2770 'cols' => $wgUser->getIntOption( 'cols' ),
2771 'rows' => $wgUser->getIntOption( 'rows' ),
2772 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2773 );
2774
2775 $pageLang = $this->mTitle->getPageLanguage();
2776 $attribs['lang'] = $pageLang->getCode();
2777 $attribs['dir'] = $pageLang->getDir();
2778
2779 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
2780 }
2781
2782 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2783 global $wgOut;
2784 $classes = array();
2785 if ( $isOnTop ) {
2786 $classes[] = 'ontop';
2787 }
2788
2789 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2790
2791 if ( $this->formtype != 'preview' ) {
2792 $attribs['style'] = 'display: none;';
2793 }
2794
2795 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
2796
2797 if ( $this->formtype == 'preview' ) {
2798 $this->showPreview( $previewOutput );
2799 }
2800
2801 $wgOut->addHTML( '</div>' );
2802
2803 if ( $this->formtype == 'diff' ) {
2804 try {
2805 $this->showDiff();
2806 } catch ( MWContentSerializationException $ex ) {
2807 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
2808 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2809 }
2810 }
2811 }
2812
2813 /**
2814 * Append preview output to $wgOut.
2815 * Includes category rendering if this is a category page.
2816 *
2817 * @param string $text the HTML to be output for the preview.
2818 */
2819 protected function showPreview( $text ) {
2820 global $wgOut;
2821 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2822 $this->mArticle->openShowCategory();
2823 }
2824 # This hook seems slightly odd here, but makes things more
2825 # consistent for extensions.
2826 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2827 $wgOut->addHTML( $text );
2828 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2829 $this->mArticle->closeShowCategory();
2830 }
2831 }
2832
2833 /**
2834 * Get a diff between the current contents of the edit box and the
2835 * version of the page we're editing from.
2836 *
2837 * If this is a section edit, we'll replace the section as for final
2838 * save and then make a comparison.
2839 */
2840 function showDiff() {
2841 global $wgUser, $wgContLang, $wgOut;
2842
2843 $oldtitlemsg = 'currentrev';
2844 # if message does not exist, show diff against the preloaded default
2845 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
2846 $oldtext = $this->mTitle->getDefaultMessageText();
2847 if ( $oldtext !== false ) {
2848 $oldtitlemsg = 'defaultmessagetext';
2849 $oldContent = $this->toEditContent( $oldtext );
2850 } else {
2851 $oldContent = null;
2852 }
2853 } else {
2854 $oldContent = $this->getCurrentContent();
2855 }
2856
2857 $textboxContent = $this->toEditContent( $this->textbox1 );
2858
2859 $newContent = $this->mArticle->replaceSectionContent(
2860 $this->section, $textboxContent,
2861 $this->summary, $this->edittime );
2862
2863 if ( $newContent ) {
2864 ContentHandler::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
2865 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2866
2867 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
2868 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
2869 }
2870
2871 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
2872 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2873 $newtitle = wfMessage( 'yourtext' )->parse();
2874
2875 if ( !$oldContent ) {
2876 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
2877 }
2878
2879 if ( !$newContent ) {
2880 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
2881 }
2882
2883 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
2884 $de->setContent( $oldContent, $newContent );
2885
2886 $difftext = $de->getDiff( $oldtitle, $newtitle );
2887 $de->showDiffStyle();
2888 } else {
2889 $difftext = '';
2890 }
2891
2892 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2893 }
2894
2895 /**
2896 * Show the header copyright warning.
2897 */
2898 protected function showHeaderCopyrightWarning() {
2899 $msg = 'editpage-head-copy-warn';
2900 if ( !wfMessage( $msg )->isDisabled() ) {
2901 global $wgOut;
2902 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2903 'editpage-head-copy-warn' );
2904 }
2905 }
2906
2907 /**
2908 * Give a chance for site and per-namespace customizations of
2909 * terms of service summary link that might exist separately
2910 * from the copyright notice.
2911 *
2912 * This will display between the save button and the edit tools,
2913 * so should remain short!
2914 */
2915 protected function showTosSummary() {
2916 $msg = 'editpage-tos-summary';
2917 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
2918 if ( !wfMessage( $msg )->isDisabled() ) {
2919 global $wgOut;
2920 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2921 $wgOut->addWikiMsg( $msg );
2922 $wgOut->addHTML( '</div>' );
2923 }
2924 }
2925
2926 protected function showEditTools() {
2927 global $wgOut;
2928 $wgOut->addHTML( '<div class="mw-editTools">' .
2929 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2930 '</div>' );
2931 }
2932
2933 /**
2934 * Get the copyright warning
2935 *
2936 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2937 */
2938 protected function getCopywarn() {
2939 return self::getCopyrightWarning( $this->mTitle );
2940 }
2941
2942 /**
2943 * Get the copyright warning, by default returns wikitext
2944 *
2945 * @param Title $title
2946 * @param string $format output format, valid values are any function of
2947 * a Message object
2948 * @return string
2949 */
2950 public static function getCopyrightWarning( $title, $format = 'plain' ) {
2951 global $wgRightsText;
2952 if ( $wgRightsText ) {
2953 $copywarnMsg = array( 'copyrightwarning',
2954 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2955 $wgRightsText );
2956 } else {
2957 $copywarnMsg = array( 'copyrightwarning2',
2958 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2959 }
2960 // Allow for site and per-namespace customization of contribution/copyright notice.
2961 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2962
2963 return "<div id=\"editpage-copywarn\">\n" .
2964 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
2965 }
2966
2967 /**
2968 * Get the Limit report for page previews
2969 *
2970 * @since 1.22
2971 * @param ParserOutput $output ParserOutput object from the parse
2972 * @return string HTML
2973 */
2974 public static function getPreviewLimitReport( $output ) {
2975 if ( !$output || !$output->getLimitReportData() ) {
2976 return '';
2977 }
2978
2979 wfProfileIn( __METHOD__ );
2980
2981 $limitReport = Html::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
2982 wfMessage( 'limitreport-title' )->parseAsBlock()
2983 );
2984
2985 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
2986 $limitReport .= Html::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
2987
2988 $limitReport .= Html::openElement( 'table', array(
2989 'class' => 'preview-limit-report wikitable'
2990 ) ) .
2991 Html::openElement( 'tbody' );
2992
2993 foreach ( $output->getLimitReportData() as $key => $value ) {
2994 if ( wfRunHooks( 'ParserLimitReportFormat',
2995 array( $key, &$value, &$limitReport, true, true )
2996 ) ) {
2997 $keyMsg = wfMessage( $key );
2998 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
2999 if ( !$valueMsg->exists() ) {
3000 $valueMsg = new RawMessage( '$1' );
3001 }
3002 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3003 $limitReport .= Html::openElement( 'tr' ) .
3004 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3005 Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3006 Html::closeElement( 'tr' );
3007 }
3008 }
3009 }
3010
3011 $limitReport .= Html::closeElement( 'tbody' ) .
3012 Html::closeElement( 'table' ) .
3013 Html::closeElement( 'div' );
3014
3015 wfProfileOut( __METHOD__ );
3016
3017 return $limitReport;
3018 }
3019
3020 protected function showStandardInputs( &$tabindex = 2 ) {
3021 global $wgOut;
3022 $wgOut->addHTML( "<div class='editOptions'>\n" );
3023
3024 if ( $this->section != 'new' ) {
3025 $this->showSummaryInput( false, $this->summary );
3026 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3027 }
3028
3029 $checkboxes = $this->getCheckboxes( $tabindex,
3030 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
3031 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3032
3033 // Show copyright warning.
3034 $wgOut->addWikiText( $this->getCopywarn() );
3035 $wgOut->addHTML( $this->editFormTextAfterWarn );
3036
3037 $wgOut->addHTML( "<div class='editButtons'>\n" );
3038 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3039
3040 $cancel = $this->getCancelLink();
3041 if ( $cancel !== '' ) {
3042 $cancel .= Html::element( 'span',
3043 array( 'class' => 'mw-editButtons-pipe-separator' ),
3044 wfMessage( 'pipe-separator' )->text() );
3045 }
3046 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
3047 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
3048 wfMessage( 'edithelp' )->escaped() . '</a> ' .
3049 wfMessage( 'newwindow' )->parse();
3050 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3051 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3052 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3053 wfRunHooks( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3054 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3055 }
3056
3057 /**
3058 * Show an edit conflict. textbox1 is already shown in showEditForm().
3059 * If you want to use another entry point to this function, be careful.
3060 */
3061 protected function showConflict() {
3062 global $wgOut;
3063
3064 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3065 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3066
3067 $content1 = $this->toEditContent( $this->textbox1 );
3068 $content2 = $this->toEditContent( $this->textbox2 );
3069
3070 $handler = ContentHandler::getForModelID( $this->contentModel );
3071 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3072 $de->setContent( $content2, $content1 );
3073 $de->showDiff(
3074 wfMessage( 'yourtext' )->parse(),
3075 wfMessage( 'storedversion' )->text()
3076 );
3077
3078 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3079 $this->showTextbox2();
3080 }
3081 }
3082
3083 /**
3084 * @return string
3085 */
3086 public function getCancelLink() {
3087 $cancelParams = array();
3088 if ( !$this->isConflict && $this->oldid > 0 ) {
3089 $cancelParams['oldid'] = $this->oldid;
3090 }
3091
3092 return Linker::linkKnown(
3093 $this->getContextTitle(),
3094 wfMessage( 'cancel' )->parse(),
3095 array( 'id' => 'mw-editform-cancel' ),
3096 $cancelParams
3097 );
3098 }
3099
3100 /**
3101 * Returns the URL to use in the form's action attribute.
3102 * This is used by EditPage subclasses when simply customizing the action
3103 * variable in the constructor is not enough. This can be used when the
3104 * EditPage lives inside of a Special page rather than a custom page action.
3105 *
3106 * @param $title Title object for which is being edited (where we go to for &action= links)
3107 * @return string
3108 */
3109 protected function getActionURL( Title $title ) {
3110 return $title->getLocalURL( array( 'action' => $this->action ) );
3111 }
3112
3113 /**
3114 * Check if a page was deleted while the user was editing it, before submit.
3115 * Note that we rely on the logging table, which hasn't been always there,
3116 * but that doesn't matter, because this only applies to brand new
3117 * deletes.
3118 */
3119 protected function wasDeletedSinceLastEdit() {
3120 if ( $this->deletedSinceEdit !== null ) {
3121 return $this->deletedSinceEdit;
3122 }
3123
3124 $this->deletedSinceEdit = false;
3125
3126 if ( $this->mTitle->isDeletedQuick() ) {
3127 $this->lastDelete = $this->getLastDelete();
3128 if ( $this->lastDelete ) {
3129 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3130 if ( $deleteTime > $this->starttime ) {
3131 $this->deletedSinceEdit = true;
3132 }
3133 }
3134 }
3135
3136 return $this->deletedSinceEdit;
3137 }
3138
3139 protected function getLastDelete() {
3140 $dbr = wfGetDB( DB_SLAVE );
3141 $data = $dbr->selectRow(
3142 array( 'logging', 'user' ),
3143 array(
3144 'log_type',
3145 'log_action',
3146 'log_timestamp',
3147 'log_user',
3148 'log_namespace',
3149 'log_title',
3150 'log_comment',
3151 'log_params',
3152 'log_deleted',
3153 'user_name'
3154 ), array(
3155 'log_namespace' => $this->mTitle->getNamespace(),
3156 'log_title' => $this->mTitle->getDBkey(),
3157 'log_type' => 'delete',
3158 'log_action' => 'delete',
3159 'user_id=log_user'
3160 ),
3161 __METHOD__,
3162 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3163 );
3164 // Quick paranoid permission checks...
3165 if ( is_object( $data ) ) {
3166 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3167 $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
3168 }
3169
3170 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3171 $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
3172 }
3173 }
3174 return $data;
3175 }
3176
3177 /**
3178 * Get the rendered text for previewing.
3179 * @throws MWException
3180 * @return string
3181 */
3182 function getPreviewText() {
3183 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3184
3185 wfProfileIn( __METHOD__ );
3186
3187 if ( $wgRawHtml && !$this->mTokenOk ) {
3188 // Could be an offsite preview attempt. This is very unsafe if
3189 // HTML is enabled, as it could be an attack.
3190 $parsedNote = '';
3191 if ( $this->textbox1 !== '' ) {
3192 // Do not put big scary notice, if previewing the empty
3193 // string, which happens when you initially edit
3194 // a category page, due to automatic preview-on-open.
3195 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3196 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3197 }
3198 wfProfileOut( __METHOD__ );
3199 return $parsedNote;
3200 }
3201
3202 $note = '';
3203
3204 try {
3205 $content = $this->toEditContent( $this->textbox1 );
3206
3207 $previewHTML = '';
3208 if ( !wfRunHooks( 'AlternateEditPreview', array( $this, &$content, &$previewHTML, &$this->mParserOutput ) ) ) {
3209 wfProfileOut( __METHOD__ );
3210 return $previewHTML;
3211 }
3212
3213 # provide a anchor link to the editform
3214 $continueEditing = '<span class="mw-continue-editing">' .
3215 '[[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' .
3216 wfMessage( 'continue-editing' )->text() . ']]</span>';
3217 if ( $this->mTriedSave && !$this->mTokenOk ) {
3218 if ( $this->mTokenOkExceptSuffix ) {
3219 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3220
3221 } else {
3222 $note = wfMessage( 'session_fail_preview' )->plain();
3223 }
3224 } elseif ( $this->incompleteForm ) {
3225 $note = wfMessage( 'edit_form_incomplete' )->plain();
3226 } else {
3227 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3228 }
3229
3230 $parserOptions = $this->mArticle->makeParserOptions( $this->mArticle->getContext() );
3231 $parserOptions->setEditSection( false );
3232 $parserOptions->setIsPreview( true );
3233 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3234
3235 # don't parse non-wikitext pages, show message about preview
3236 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3237 if ( $this->mTitle->isCssJsSubpage() ) {
3238 $level = 'user';
3239 } elseif ( $this->mTitle->isCssOrJsPage() ) {
3240 $level = 'site';
3241 } else {
3242 $level = false;
3243 }
3244
3245 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3246 $format = 'css';
3247 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3248 $format = 'js';
3249 } else {
3250 $format = false;
3251 }
3252
3253 # Used messages to make sure grep find them:
3254 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3255 if ( $level && $format ) {
3256 $note = "<div id='mw-{$level}{$format}preview'>" .
3257 wfMessage( "{$level}{$format}preview" )->text() .
3258 ' ' . $continueEditing . "</div>";
3259 }
3260 }
3261
3262 # If we're adding a comment, we need to show the
3263 # summary as the headline
3264 if ( $this->section === "new" && $this->summary !== "" ) {
3265 $content = $content->addSectionHeader( $this->summary );
3266 }
3267
3268 $hook_args = array( $this, &$content );
3269 ContentHandler::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3270 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
3271
3272 $parserOptions->enableLimitReport();
3273
3274 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3275 # But it's now deprecated, so never mind
3276
3277 $content = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3278 $parserOutput = $content->getParserOutput( $this->getArticle()->getTitle(), null, $parserOptions );
3279
3280 $previewHTML = $parserOutput->getText();
3281 $this->mParserOutput = $parserOutput;
3282 $wgOut->addParserOutputNoText( $parserOutput );
3283
3284 if ( count( $parserOutput->getWarnings() ) ) {
3285 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3286 }
3287 } catch ( MWContentSerializationException $ex ) {
3288 $m = wfMessage( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
3289 $note .= "\n\n" . $m->parse();
3290 $previewHTML = '';
3291 }
3292
3293 if ( $this->isConflict ) {
3294 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3295 } else {
3296 $conflict = '<hr />';
3297 }
3298
3299 $previewhead = "<div class='previewnote'>\n" .
3300 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3301 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3302
3303 $pageViewLang = $this->mTitle->getPageViewLanguage();
3304 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3305 'class' => 'mw-content-' . $pageViewLang->getDir() );
3306 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3307
3308 wfProfileOut( __METHOD__ );
3309 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3310 }
3311
3312 /**
3313 * @return Array
3314 */
3315 function getTemplates() {
3316 if ( $this->preview || $this->section != '' ) {
3317 $templates = array();
3318 if ( !isset( $this->mParserOutput ) ) {
3319 return $templates;
3320 }
3321 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3322 foreach ( array_keys( $template ) as $dbk ) {
3323 $templates[] = Title::makeTitle( $ns, $dbk );
3324 }
3325 }
3326 return $templates;
3327 } else {
3328 return $this->mTitle->getTemplateLinksFrom();
3329 }
3330 }
3331
3332 /**
3333 * Shows a bulletin board style toolbar for common editing functions.
3334 * It can be disabled in the user preferences.
3335 * The necessary JavaScript code can be found in skins/common/edit.js.
3336 *
3337 * @return string
3338 */
3339 static function getEditToolbar() {
3340 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3341 global $wgEnableUploads, $wgForeignFileRepos;
3342
3343 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3344
3345 /**
3346 * $toolarray is an array of arrays each of which includes the
3347 * filename of the button image (without path), the opening
3348 * tag, the closing tag, optionally a sample text that is
3349 * inserted between the two when no selection is highlighted
3350 * and. The tip text is shown when the user moves the mouse
3351 * over the button.
3352 *
3353 * Also here: accesskeys (key), which are not used yet until
3354 * someone can figure out a way to make them work in
3355 * IE. However, we should make sure these keys are not defined
3356 * on the edit page.
3357 */
3358 $toolarray = array(
3359 array(
3360 'image' => $wgLang->getImageFile( 'button-bold' ),
3361 'id' => 'mw-editbutton-bold',
3362 'open' => '\'\'\'',
3363 'close' => '\'\'\'',
3364 'sample' => wfMessage( 'bold_sample' )->text(),
3365 'tip' => wfMessage( 'bold_tip' )->text(),
3366 'key' => 'B'
3367 ),
3368 array(
3369 'image' => $wgLang->getImageFile( 'button-italic' ),
3370 'id' => 'mw-editbutton-italic',
3371 'open' => '\'\'',
3372 'close' => '\'\'',
3373 'sample' => wfMessage( 'italic_sample' )->text(),
3374 'tip' => wfMessage( 'italic_tip' )->text(),
3375 'key' => 'I'
3376 ),
3377 array(
3378 'image' => $wgLang->getImageFile( 'button-link' ),
3379 'id' => 'mw-editbutton-link',
3380 'open' => '[[',
3381 'close' => ']]',
3382 'sample' => wfMessage( 'link_sample' )->text(),
3383 'tip' => wfMessage( 'link_tip' )->text(),
3384 'key' => 'L'
3385 ),
3386 array(
3387 'image' => $wgLang->getImageFile( 'button-extlink' ),
3388 'id' => 'mw-editbutton-extlink',
3389 'open' => '[',
3390 'close' => ']',
3391 'sample' => wfMessage( 'extlink_sample' )->text(),
3392 'tip' => wfMessage( 'extlink_tip' )->text(),
3393 'key' => 'X'
3394 ),
3395 array(
3396 'image' => $wgLang->getImageFile( 'button-headline' ),
3397 'id' => 'mw-editbutton-headline',
3398 'open' => "\n== ",
3399 'close' => " ==\n",
3400 'sample' => wfMessage( 'headline_sample' )->text(),
3401 'tip' => wfMessage( 'headline_tip' )->text(),
3402 'key' => 'H'
3403 ),
3404 $imagesAvailable ? array(
3405 'image' => $wgLang->getImageFile( 'button-image' ),
3406 'id' => 'mw-editbutton-image',
3407 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3408 'close' => ']]',
3409 'sample' => wfMessage( 'image_sample' )->text(),
3410 'tip' => wfMessage( 'image_tip' )->text(),
3411 'key' => 'D',
3412 ) : false,
3413 $imagesAvailable ? array(
3414 'image' => $wgLang->getImageFile( 'button-media' ),
3415 'id' => 'mw-editbutton-media',
3416 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3417 'close' => ']]',
3418 'sample' => wfMessage( 'media_sample' )->text(),
3419 'tip' => wfMessage( 'media_tip' )->text(),
3420 'key' => 'M'
3421 ) : false,
3422 array(
3423 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3424 'id' => 'mw-editbutton-nowiki',
3425 'open' => "<nowiki>",
3426 'close' => "</nowiki>",
3427 'sample' => wfMessage( 'nowiki_sample' )->text(),
3428 'tip' => wfMessage( 'nowiki_tip' )->text(),
3429 'key' => 'N'
3430 ),
3431 array(
3432 'image' => $wgLang->getImageFile( 'button-sig' ),
3433 'id' => 'mw-editbutton-signature',
3434 'open' => '--~~~~',
3435 'close' => '',
3436 'sample' => '',
3437 'tip' => wfMessage( 'sig_tip' )->text(),
3438 'key' => 'Y'
3439 ),
3440 array(
3441 'image' => $wgLang->getImageFile( 'button-hr' ),
3442 'id' => 'mw-editbutton-hr',
3443 'open' => "\n----\n",
3444 'close' => '',
3445 'sample' => '',
3446 'tip' => wfMessage( 'hr_tip' )->text(),
3447 'key' => 'R'
3448 )
3449 );
3450
3451 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3452 foreach ( $toolarray as $tool ) {
3453 if ( !$tool ) {
3454 continue;
3455 }
3456
3457 $params = array(
3458 $wgStylePath . '/common/images/' . $tool['image'],
3459 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3460 // Older browsers show a "speedtip" type message only for ALT.
3461 // Ideally these should be different, realistically they
3462 // probably don't need to be.
3463 $tool['tip'],
3464 $tool['open'],
3465 $tool['close'],
3466 $tool['sample'],
3467 $tool['id'],
3468 );
3469
3470 $script .= Xml::encodeJsCall( 'mw.toolbar.addButton', $params );
3471 }
3472
3473 // This used to be called on DOMReady from mediawiki.action.edit, which
3474 // ended up causing race conditions with the setup code above.
3475 $script .= "\n" .
3476 "// Create button bar\n" .
3477 "$(function() { mw.toolbar.init(); } );\n";
3478
3479 $script .= '});';
3480 $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
3481
3482 $toolbar = '<div id="toolbar"></div>';
3483
3484 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3485
3486 return $toolbar;
3487 }
3488
3489 /**
3490 * Returns an array of html code of the following checkboxes:
3491 * minor and watch
3492 *
3493 * @param int $tabindex Current tabindex
3494 * @param array $checked of checkbox => bool, where bool indicates the checked
3495 * status of the checkbox
3496 *
3497 * @return array
3498 */
3499 public function getCheckboxes( &$tabindex, $checked ) {
3500 global $wgUser;
3501
3502 $checkboxes = array();
3503
3504 // don't show the minor edit checkbox if it's a new page or section
3505 if ( !$this->isNew ) {
3506 $checkboxes['minor'] = '';
3507 $minorLabel = wfMessage( 'minoredit' )->parse();
3508 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3509 $attribs = array(
3510 'tabindex' => ++$tabindex,
3511 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3512 'id' => 'wpMinoredit',
3513 );
3514 $checkboxes['minor'] =
3515 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3516 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
3517 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3518 ">{$minorLabel}</label>";
3519 }
3520 }
3521
3522 $watchLabel = wfMessage( 'watchthis' )->parse();
3523 $checkboxes['watch'] = '';
3524 if ( $wgUser->isLoggedIn() ) {
3525 $attribs = array(
3526 'tabindex' => ++$tabindex,
3527 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3528 'id' => 'wpWatchthis',
3529 );
3530 $checkboxes['watch'] =
3531 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3532 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
3533 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
3534 ">{$watchLabel}</label>";
3535 }
3536 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3537 return $checkboxes;
3538 }
3539
3540 /**
3541 * Returns an array of html code of the following buttons:
3542 * save, diff, preview and live
3543 *
3544 * @param int $tabindex Current tabindex
3545 *
3546 * @return array
3547 */
3548 public function getEditButtons( &$tabindex ) {
3549 $buttons = array();
3550
3551 $temp = array(
3552 'id' => 'wpSave',
3553 'name' => 'wpSave',
3554 'type' => 'submit',
3555 'tabindex' => ++$tabindex,
3556 'value' => wfMessage( 'savearticle' )->text(),
3557 'accesskey' => wfMessage( 'accesskey-save' )->text(),
3558 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
3559 );
3560 $buttons['save'] = Xml::element( 'input', $temp, '' );
3561
3562 ++$tabindex; // use the same for preview and live preview
3563 $temp = array(
3564 'id' => 'wpPreview',
3565 'name' => 'wpPreview',
3566 'type' => 'submit',
3567 'tabindex' => $tabindex,
3568 'value' => wfMessage( 'showpreview' )->text(),
3569 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
3570 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
3571 );
3572 $buttons['preview'] = Xml::element( 'input', $temp, '' );
3573 $buttons['live'] = '';
3574
3575 $temp = array(
3576 'id' => 'wpDiff',
3577 'name' => 'wpDiff',
3578 'type' => 'submit',
3579 'tabindex' => ++$tabindex,
3580 'value' => wfMessage( 'showdiff' )->text(),
3581 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
3582 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
3583 );
3584 $buttons['diff'] = Xml::element( 'input', $temp, '' );
3585
3586 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3587 return $buttons;
3588 }
3589
3590 /**
3591 * Output preview text only. This can be sucked into the edit page
3592 * via JavaScript, and saves the server time rendering the skin as
3593 * well as theoretically being more robust on the client (doesn't
3594 * disturb the edit box's undo history, won't eat your text on
3595 * failure, etc).
3596 *
3597 * @todo This doesn't include category or interlanguage links.
3598 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3599 * or something...</s>" that might also require more skin
3600 * initialization, so check whether that's a problem.
3601 */
3602 function livePreview() {
3603 global $wgOut;
3604 $wgOut->disable();
3605 header( 'Content-type: text/xml; charset=utf-8' );
3606 header( 'Cache-control: no-cache' );
3607
3608 $previewText = $this->getPreviewText();
3609 #$categories = $skin->getCategoryLinks();
3610
3611 $s =
3612 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3613 Xml::tags( 'livepreview', null,
3614 Xml::element( 'preview', null, $previewText )
3615 #. Xml::element( 'category', null, $categories )
3616 );
3617 echo $s;
3618 }
3619
3620 /**
3621 * Call the stock "user is blocked" page
3622 *
3623 * @deprecated in 1.19; throw an exception directly instead
3624 */
3625 function blockedPage() {
3626 wfDeprecated( __METHOD__, '1.19' );
3627 global $wgUser;
3628
3629 throw new UserBlockedError( $wgUser->getBlock() );
3630 }
3631
3632 /**
3633 * Produce the stock "please login to edit pages" page
3634 *
3635 * @deprecated in 1.19; throw an exception directly instead
3636 */
3637 function userNotLoggedInPage() {
3638 wfDeprecated( __METHOD__, '1.19' );
3639 throw new PermissionsError( 'edit' );
3640 }
3641
3642 /**
3643 * Show an error page saying to the user that he has insufficient permissions
3644 * to create a new page
3645 *
3646 * @deprecated in 1.19; throw an exception directly instead
3647 */
3648 function noCreatePermission() {
3649 wfDeprecated( __METHOD__, '1.19' );
3650 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
3651 throw new PermissionsError( $permission );
3652 }
3653
3654 /**
3655 * Creates a basic error page which informs the user that
3656 * they have attempted to edit a nonexistent section.
3657 */
3658 function noSuchSectionPage() {
3659 global $wgOut;
3660
3661 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3662
3663 $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
3664 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3665 $wgOut->addHTML( $res );
3666
3667 $wgOut->returnToMain( false, $this->mTitle );
3668 }
3669
3670 /**
3671 * Show "your edit contains spam" page with your diff and text
3672 *
3673 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3674 */
3675 public function spamPageWithContent( $match = false ) {
3676 global $wgOut, $wgLang;
3677 $this->textbox2 = $this->textbox1;
3678
3679 if ( is_array( $match ) ) {
3680 $match = $wgLang->listToText( $match );
3681 }
3682 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3683
3684 $wgOut->addHTML( '<div id="spamprotected">' );
3685 $wgOut->addWikiMsg( 'spamprotectiontext' );
3686 if ( $match ) {
3687 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3688 }
3689 $wgOut->addHTML( '</div>' );
3690
3691 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3692 $this->showDiff();
3693
3694 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3695 $this->showTextbox2();
3696
3697 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3698 }
3699
3700 /**
3701 * Check if the browser is on a blacklist of user-agents known to
3702 * mangle UTF-8 data on form submission. Returns true if Unicode
3703 * should make it through, false if it's known to be a problem.
3704 * @return bool
3705 */
3706 private function checkUnicodeCompliantBrowser() {
3707 global $wgBrowserBlackList, $wgRequest;
3708
3709 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3710 if ( $currentbrowser === false ) {
3711 // No User-Agent header sent? Trust it by default...
3712 return true;
3713 }
3714
3715 foreach ( $wgBrowserBlackList as $browser ) {
3716 if ( preg_match( $browser, $currentbrowser ) ) {
3717 return false;
3718 }
3719 }
3720 return true;
3721 }
3722
3723 /**
3724 * Filter an input field through a Unicode de-armoring process if it
3725 * came from an old browser with known broken Unicode editing issues.
3726 *
3727 * @param WebRequest $request
3728 * @param string $field
3729 * @return string
3730 */
3731 protected function safeUnicodeInput( $request, $field ) {
3732 $text = rtrim( $request->getText( $field ) );
3733 return $request->getBool( 'safemode' )
3734 ? $this->unmakeSafe( $text )
3735 : $text;
3736 }
3737
3738 /**
3739 * Filter an output field through a Unicode armoring process if it is
3740 * going to an old browser with known broken Unicode editing issues.
3741 *
3742 * @param string $text
3743 * @return string
3744 */
3745 protected function safeUnicodeOutput( $text ) {
3746 global $wgContLang;
3747 $codedText = $wgContLang->recodeForEdit( $text );
3748 return $this->checkUnicodeCompliantBrowser()
3749 ? $codedText
3750 : $this->makeSafe( $codedText );
3751 }
3752
3753 /**
3754 * A number of web browsers are known to corrupt non-ASCII characters
3755 * in a UTF-8 text editing environment. To protect against this,
3756 * detected browsers will be served an armored version of the text,
3757 * with non-ASCII chars converted to numeric HTML character references.
3758 *
3759 * Preexisting such character references will have a 0 added to them
3760 * to ensure that round-trips do not alter the original data.
3761 *
3762 * @param string $invalue
3763 * @return string
3764 */
3765 private function makeSafe( $invalue ) {
3766 // Armor existing references for reversibility.
3767 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
3768
3769 $bytesleft = 0;
3770 $result = "";
3771 $working = 0;
3772 for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
3773 $bytevalue = ord( $invalue[$i] );
3774 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3775 $result .= chr( $bytevalue );
3776 $bytesleft = 0;
3777 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3778 $working = $working << 6;
3779 $working += ( $bytevalue & 0x3F );
3780 $bytesleft--;
3781 if ( $bytesleft <= 0 ) {
3782 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3783 }
3784 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3785 $working = $bytevalue & 0x1F;
3786 $bytesleft = 1;
3787 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3788 $working = $bytevalue & 0x0F;
3789 $bytesleft = 2;
3790 } else { // 1111 0xxx
3791 $working = $bytevalue & 0x07;
3792 $bytesleft = 3;
3793 }
3794 }
3795 return $result;
3796 }
3797
3798 /**
3799 * Reverse the previously applied transliteration of non-ASCII characters
3800 * back to UTF-8. Used to protect data from corruption by broken web browsers
3801 * as listed in $wgBrowserBlackList.
3802 *
3803 * @param string $invalue
3804 * @return string
3805 */
3806 private function unmakeSafe( $invalue ) {
3807 $result = "";
3808 $valueLength = strlen( $invalue );
3809 for ( $i = 0; $i < $valueLength; $i++ ) {
3810 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
3811 $i += 3;
3812 $hexstring = "";
3813 do {
3814 $hexstring .= $invalue[$i];
3815 $i++;
3816 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3817
3818 // Do some sanity checks. These aren't needed for reversibility,
3819 // but should help keep the breakage down if the editor
3820 // breaks one of the entities whilst editing.
3821 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3822 $codepoint = hexdec( $hexstring );
3823 $result .= codepointToUtf8( $codepoint );
3824 } else {
3825 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3826 }
3827 } else {
3828 $result .= substr( $invalue, $i, 1 );
3829 }
3830 }
3831 // reverse the transform that we made for reversibility reasons.
3832 return strtr( $result, array( "&#x0" => "&#x" ) );
3833 }
3834 }