Merge "Set visibility for some methods and remove unused ones"
[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
914 $content = $this->getPreloadedContent( $preload );
915 }
916 // For existing pages, get text based on "undo" or section parameters.
917 } else {
918 if ( $this->section != '' ) {
919 // Get section edit text (returns $def_text for invalid sections)
920 $orig = $this->getOriginalContent();
921 $content = $orig ? $orig->getSection( $this->section ) : null;
922
923 if ( !$content ) {
924 $content = $def_content;
925 }
926 } else {
927 $undoafter = $wgRequest->getInt( 'undoafter' );
928 $undo = $wgRequest->getInt( 'undo' );
929
930 if ( $undo > 0 && $undoafter > 0 ) {
931
932 $undorev = Revision::newFromId( $undo );
933 $oldrev = Revision::newFromId( $undoafter );
934
935 # Sanity check, make sure it's the right page,
936 # the revisions exist and they were not deleted.
937 # Otherwise, $content will be left as-is.
938 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
939 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
940 !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
941
942 $content = $this->mArticle->getUndoContent( $undorev, $oldrev );
943
944 if ( $content === false ) {
945 # Warn the user that something went wrong
946 $undoMsg = 'failure';
947 } else {
948 $oldContent = $this->mArticle->getPage()->getContent( Revision::RAW );
949 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
950 $newContent = $content->preSaveTransform( $this->mTitle, $wgUser, $popts );
951
952 if ( $newContent->equals( $oldContent ) ) {
953 # Tell the user that the undo results in no change,
954 # i.e. the revisions were already undone.
955 $undoMsg = 'nochange';
956 $content = false;
957 } else {
958 # Inform the user of our success and set an automatic edit summary
959 $undoMsg = 'success';
960
961 # If we just undid one rev, use an autosummary
962 $firstrev = $oldrev->getNext();
963 if ( $firstrev && $firstrev->getId() == $undo ) {
964 $userText = $undorev->getUserText();
965 if ( $userText === '' ) {
966 $undoSummary = wfMessage(
967 'undo-summary-username-hidden',
968 $undo
969 )->inContentLanguage()->text();
970 } else {
971 $undoSummary = wfMessage(
972 'undo-summary',
973 $undo,
974 $userText
975 )->inContentLanguage()->text();
976 }
977 if ( $this->summary === '' ) {
978 $this->summary = $undoSummary;
979 } else {
980 $this->summary = $undoSummary . wfMessage( 'colon-separator' )
981 ->inContentLanguage()->text() . $this->summary;
982 }
983 $this->undidRev = $undo;
984 }
985 $this->formtype = 'diff';
986 }
987 }
988 } else {
989 // Failed basic sanity checks.
990 // Older revisions may have been removed since the link
991 // was created, or we may simply have got bogus input.
992 $undoMsg = 'norev';
993 }
994
995 // Messages: undo-success, undo-failure, undo-norev, undo-nochange
996 $class = ( $undoMsg == 'success' ? '' : 'error ' ) . "mw-undo-{$undoMsg}";
997 $this->editFormPageTop .= $wgOut->parse( "<div class=\"{$class}\">" .
998 wfMessage( 'undo-' . $undoMsg )->plain() . '</div>', true, /* interface */true );
999 }
1000
1001 if ( $content === false ) {
1002 $content = $this->getOriginalContent();
1003 }
1004 }
1005 }
1006
1007 wfProfileOut( __METHOD__ );
1008 return $content;
1009 }
1010
1011 /**
1012 * Get the content of the wanted revision, without section extraction.
1013 *
1014 * The result of this function can be used to compare user's input with
1015 * section replaced in its context (using WikiPage::replaceSection())
1016 * to the original text of the edit.
1017 *
1018 * This differs from Article::getContent() that when a missing revision is
1019 * encountered the result will be null and not the
1020 * 'missing-revision' message.
1021 *
1022 * @since 1.19
1023 * @return Content|null
1024 */
1025 private function getOriginalContent() {
1026 if ( $this->section == 'new' ) {
1027 return $this->getCurrentContent();
1028 }
1029 $revision = $this->mArticle->getRevisionFetched();
1030 if ( $revision === null ) {
1031 if ( !$this->contentModel ) {
1032 $this->contentModel = $this->getTitle()->getContentModel();
1033 }
1034 $handler = ContentHandler::getForModelID( $this->contentModel );
1035
1036 return $handler->makeEmptyContent();
1037 }
1038 $content = $revision->getContent();
1039 return $content;
1040 }
1041
1042 /**
1043 * Get the current content of the page. This is basically similar to
1044 * WikiPage::getContent( Revision::RAW ) except that when the page doesn't exist an empty
1045 * content object is returned instead of null.
1046 *
1047 * @since 1.21
1048 * @return Content
1049 */
1050 protected function getCurrentContent() {
1051 $rev = $this->mArticle->getRevision();
1052 $content = $rev ? $rev->getContent( Revision::RAW ) : null;
1053
1054 if ( $content === false || $content === null ) {
1055 if ( !$this->contentModel ) {
1056 $this->contentModel = $this->getTitle()->getContentModel();
1057 }
1058 $handler = ContentHandler::getForModelID( $this->contentModel );
1059
1060 return $handler->makeEmptyContent();
1061 } else {
1062 # nasty side-effect, but needed for consistency
1063 $this->contentModel = $rev->getContentModel();
1064 $this->contentFormat = $rev->getContentFormat();
1065
1066 return $content;
1067 }
1068 }
1069
1070 /**
1071 * Use this method before edit() to preload some text into the edit box
1072 *
1073 * @param $text string
1074 * @deprecated since 1.21, use setPreloadedContent() instead.
1075 */
1076 public function setPreloadedText( $text ) {
1077 ContentHandler::deprecated( __METHOD__, "1.21" );
1078
1079 $content = $this->toEditContent( $text );
1080
1081 $this->setPreloadedContent( $content );
1082 }
1083
1084 /**
1085 * Use this method before edit() to preload some content into the edit box
1086 *
1087 * @param $content Content
1088 *
1089 * @since 1.21
1090 */
1091 public function setPreloadedContent( Content $content ) {
1092 $this->mPreloadContent = $content;
1093 }
1094
1095 /**
1096 * Get the contents to be preloaded into the box, either set by
1097 * an earlier setPreloadText() or by loading the given page.
1098 *
1099 * @param string $preload representing the title to preload from.
1100 *
1101 * @return String
1102 *
1103 * @deprecated since 1.21, use getPreloadedContent() instead
1104 */
1105 protected function getPreloadedText( $preload ) {
1106 ContentHandler::deprecated( __METHOD__, "1.21" );
1107
1108 $content = $this->getPreloadedContent( $preload );
1109 $text = $this->toEditText( $content );
1110
1111 return $text;
1112 }
1113
1114 /**
1115 * Get the contents to be preloaded into the box, either set by
1116 * an earlier setPreloadText() or by loading the given page.
1117 *
1118 * @param string $preload representing the title to preload from.
1119 *
1120 * @return Content
1121 *
1122 * @since 1.21
1123 */
1124 protected function getPreloadedContent( $preload ) {
1125 global $wgUser;
1126
1127 if ( !empty( $this->mPreloadContent ) ) {
1128 return $this->mPreloadContent;
1129 }
1130
1131 $handler = ContentHandler::getForTitle( $this->getTitle() );
1132
1133 if ( $preload === '' ) {
1134 return $handler->makeEmptyContent();
1135 }
1136
1137 $title = Title::newFromText( $preload );
1138 # Check for existence to avoid getting MediaWiki:Noarticletext
1139 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1140 //TODO: somehow show a warning to the user!
1141 return $handler->makeEmptyContent();
1142 }
1143
1144 $page = WikiPage::factory( $title );
1145 if ( $page->isRedirect() ) {
1146 $title = $page->getRedirectTarget();
1147 # Same as before
1148 if ( $title === null || !$title->exists() || !$title->userCan( 'read', $wgUser ) ) {
1149 //TODO: somehow show a warning to the user!
1150 return $handler->makeEmptyContent();
1151 }
1152 $page = WikiPage::factory( $title );
1153 }
1154
1155 $parserOptions = ParserOptions::newFromUser( $wgUser );
1156 $content = $page->getContent( Revision::RAW );
1157
1158 if ( !$content ) {
1159 //TODO: somehow show a warning to the user!
1160 return $handler->makeEmptyContent();
1161 }
1162
1163 if ( $content->getModel() !== $handler->getModelID() ) {
1164 $converted = $content->convert( $handler->getModelID() );
1165
1166 if ( !$converted ) {
1167 //TODO: somehow show a warning to the user!
1168 wfDebug( "Attempt to preload incompatible content: "
1169 . "can't convert " . $content->getModel()
1170 . " to " . $handler->getModelID() );
1171
1172 return $handler->makeEmptyContent();
1173 }
1174
1175 $content = $converted;
1176 }
1177
1178 return $content->preloadTransform( $title, $parserOptions );
1179 }
1180
1181 /**
1182 * Make sure the form isn't faking a user's credentials.
1183 *
1184 * @param $request WebRequest
1185 * @return bool
1186 * @private
1187 */
1188 function tokenOk( &$request ) {
1189 global $wgUser;
1190 $token = $request->getVal( 'wpEditToken' );
1191 $this->mTokenOk = $wgUser->matchEditToken( $token );
1192 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
1193 return $this->mTokenOk;
1194 }
1195
1196 /**
1197 * Sets post-edit cookie indicating the user just saved a particular revision.
1198 *
1199 * This uses a temporary cookie for each revision ID so separate saves will never
1200 * interfere with each other.
1201 *
1202 * The cookie is deleted in the mediawiki.action.view.postEdit JS module after
1203 * the redirect. It must be clearable by JavaScript code, so it must not be
1204 * marked HttpOnly. The JavaScript code converts the cookie to a wgPostEdit config
1205 * variable.
1206 *
1207 * We use a path of '/' since wgCookiePath is not exposed to JS
1208 *
1209 * If the variable were set on the server, it would be cached, which is unwanted
1210 * since the post-edit state should only apply to the load right after the save.
1211 */
1212 protected function setPostEditCookie() {
1213 $revisionId = $this->mArticle->getLatest();
1214 $postEditKey = self::POST_EDIT_COOKIE_KEY_PREFIX . $revisionId;
1215
1216 $response = RequestContext::getMain()->getRequest()->response();
1217 $response->setcookie( $postEditKey, '1', time() + self::POST_EDIT_COOKIE_DURATION, array(
1218 'path' => '/',
1219 'httpOnly' => false,
1220 ) );
1221 }
1222
1223 /**
1224 * Attempt submission
1225 * @throws UserBlockedError|ReadOnlyError|ThrottledError|PermissionsError
1226 * @return bool false if output is done, true if the rest of the form should be displayed
1227 */
1228 public function attemptSave() {
1229 global $wgUser;
1230
1231 $resultDetails = false;
1232 # Allow bots to exempt some edits from bot flagging
1233 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot;
1234 $status = $this->internalAttemptSave( $resultDetails, $bot );
1235
1236 return $this->handleStatus( $status, $resultDetails );
1237 }
1238
1239 /**
1240 * Handle status, such as after attempt save
1241 *
1242 * @param Status $status
1243 * @param array|bool $resultDetails
1244 *
1245 * @throws ErrorPageError
1246 * return bool false, if output is done, true if rest of the form should be displayed
1247 */
1248 private function handleStatus( Status $status, $resultDetails ) {
1249 global $wgUser, $wgOut;
1250
1251 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
1252 if ( $status->value == self::AS_SUCCESS_UPDATE || $status->value == self::AS_SUCCESS_NEW_ARTICLE ) {
1253 $this->didSave = true;
1254 if ( !$resultDetails['nullEdit'] ) {
1255 $this->setPostEditCookie();
1256 }
1257 }
1258
1259 switch ( $status->value ) {
1260 case self::AS_HOOK_ERROR_EXPECTED:
1261 case self::AS_CONTENT_TOO_BIG:
1262 case self::AS_ARTICLE_WAS_DELETED:
1263 case self::AS_CONFLICT_DETECTED:
1264 case self::AS_SUMMARY_NEEDED:
1265 case self::AS_TEXTBOX_EMPTY:
1266 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
1267 case self::AS_END:
1268 return true;
1269
1270 case self::AS_HOOK_ERROR:
1271 return false;
1272
1273 case self::AS_PARSE_ERROR:
1274 $wgOut->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
1275 return true;
1276
1277 case self::AS_SUCCESS_NEW_ARTICLE:
1278 $query = $resultDetails['redirect'] ? 'redirect=no' : '';
1279 $anchor = isset( $resultDetails['sectionanchor'] ) ? $resultDetails['sectionanchor'] : '';
1280 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $anchor );
1281 return false;
1282
1283 case self::AS_SUCCESS_UPDATE:
1284 $extraQuery = '';
1285 $sectionanchor = $resultDetails['sectionanchor'];
1286
1287 // Give extensions a chance to modify URL query on update
1288 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle, &$sectionanchor, &$extraQuery ) );
1289
1290 if ( $resultDetails['redirect'] ) {
1291 if ( $extraQuery == '' ) {
1292 $extraQuery = 'redirect=no';
1293 } else {
1294 $extraQuery = 'redirect=no&' . $extraQuery;
1295 }
1296 }
1297 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
1298 return false;
1299
1300 case self::AS_BLANK_ARTICLE:
1301 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
1302 return false;
1303
1304 case self::AS_SPAM_ERROR:
1305 $this->spamPageWithContent( $resultDetails['spam'] );
1306 return false;
1307
1308 case self::AS_BLOCKED_PAGE_FOR_USER:
1309 throw new UserBlockedError( $wgUser->getBlock() );
1310
1311 case self::AS_IMAGE_REDIRECT_ANON:
1312 case self::AS_IMAGE_REDIRECT_LOGGED:
1313 throw new PermissionsError( 'upload' );
1314
1315 case self::AS_READ_ONLY_PAGE_ANON:
1316 case self::AS_READ_ONLY_PAGE_LOGGED:
1317 throw new PermissionsError( 'edit' );
1318
1319 case self::AS_READ_ONLY_PAGE:
1320 throw new ReadOnlyError;
1321
1322 case self::AS_RATE_LIMITED:
1323 throw new ThrottledError();
1324
1325 case self::AS_NO_CREATE_PERMISSION:
1326 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
1327 throw new PermissionsError( $permission );
1328
1329 default:
1330 // We don't recognize $status->value. The only way that can happen
1331 // is if an extension hook aborted from inside ArticleSave.
1332 // Render the status object into $this->hookError
1333 // FIXME this sucks, we should just use the Status object throughout
1334 $this->hookError = '<div class="error">' . $status->getWikitext() .
1335 '</div>';
1336 return true;
1337 }
1338 }
1339
1340 /**
1341 * Run hooks that can filter edits just before they get saved.
1342 *
1343 * @param Content $content the Content to filter.
1344 * @param Status $status for reporting the outcome to the caller
1345 * @param User $user the user performing the edit
1346 *
1347 * @return bool
1348 */
1349 protected function runPostMergeFilters( Content $content, Status $status, User $user ) {
1350 // Run old style post-section-merge edit filter
1351 if ( !ContentHandler::runLegacyHooks( 'EditFilterMerged',
1352 array( $this, $content, &$this->hookError, $this->summary ) ) ) {
1353
1354 # Error messages etc. could be handled within the hook...
1355 $status->fatal( 'hookaborted' );
1356 $status->value = self::AS_HOOK_ERROR;
1357 return false;
1358 } elseif ( $this->hookError != '' ) {
1359 # ...or the hook could be expecting us to produce an error
1360 $status->fatal( 'hookaborted' );
1361 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1362 return false;
1363 }
1364
1365 // Run new style post-section-merge edit filter
1366 if ( !wfRunHooks( 'EditFilterMergedContent',
1367 array( $this->mArticle->getContext(), $content, $status, $this->summary,
1368 $user, $this->minoredit ) ) ) {
1369
1370 # Error messages etc. could be handled within the hook...
1371 // XXX: $status->value may already be something informative...
1372 $this->hookError = $status->getWikiText();
1373 $status->fatal( 'hookaborted' );
1374 $status->value = self::AS_HOOK_ERROR;
1375 return false;
1376 } elseif ( !$status->isOK() ) {
1377 # ...or the hook could be expecting us to produce an error
1378 // FIXME this sucks, we should just use the Status object throughout
1379 $this->hookError = $status->getWikiText();
1380 $status->fatal( 'hookaborted' );
1381 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1382 return false;
1383 }
1384
1385 return true;
1386 }
1387
1388 /**
1389 * Attempt submission (no UI)
1390 *
1391 * @param array $result array to add statuses to, currently with the possible keys:
1392 * spam - string - Spam string from content if any spam is detected by matchSpamRegex
1393 * sectionanchor - string - Section anchor for a section save
1394 * nullEdit - boolean - Set if doEditContent is OK. True if null edit, false otherwise.
1395 * redirect - boolean - Set if doEditContent is OK. True if resulting revision is a redirect
1396 * @param bool $bot True if edit is being made under the bot right.
1397 *
1398 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
1399 *
1400 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
1401 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
1402 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
1403 */
1404 function internalAttemptSave( &$result, $bot = false ) {
1405 global $wgUser, $wgRequest, $wgParser, $wgMaxArticleSize;
1406
1407 $status = Status::newGood();
1408
1409 wfProfileIn( __METHOD__ );
1410 wfProfileIn( __METHOD__ . '-checks' );
1411
1412 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
1413 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
1414 $status->fatal( 'hookaborted' );
1415 $status->value = self::AS_HOOK_ERROR;
1416 wfProfileOut( __METHOD__ . '-checks' );
1417 wfProfileOut( __METHOD__ );
1418 return $status;
1419 }
1420
1421 $spam = $wgRequest->getText( 'wpAntispam' );
1422 if ( $spam !== '' ) {
1423 wfDebugLog(
1424 'SimpleAntiSpam',
1425 $wgUser->getName() .
1426 ' editing "' .
1427 $this->mTitle->getPrefixedText() .
1428 '" submitted bogus field "' .
1429 $spam .
1430 '"'
1431 );
1432 $status->fatal( 'spamprotectionmatch', false );
1433 $status->value = self::AS_SPAM_ERROR;
1434 wfProfileOut( __METHOD__ . '-checks' );
1435 wfProfileOut( __METHOD__ );
1436 return $status;
1437 }
1438
1439 try {
1440 # Construct Content object
1441 $textbox_content = $this->toEditContent( $this->textbox1 );
1442 } catch ( MWContentSerializationException $ex ) {
1443 $status->fatal( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
1444 $status->value = self::AS_PARSE_ERROR;
1445 wfProfileOut( __METHOD__ . '-checks' );
1446 wfProfileOut( __METHOD__ );
1447 return $status;
1448 }
1449
1450 # Check image redirect
1451 if ( $this->mTitle->getNamespace() == NS_FILE &&
1452 $textbox_content->isRedirect() &&
1453 !$wgUser->isAllowed( 'upload' ) ) {
1454 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
1455 $status->setResult( false, $code );
1456
1457 wfProfileOut( __METHOD__ . '-checks' );
1458 wfProfileOut( __METHOD__ );
1459
1460 return $status;
1461 }
1462
1463 # Check for spam
1464 $match = self::matchSummarySpamRegex( $this->summary );
1465 if ( $match === false && $this->section == 'new' ) {
1466 # $wgSpamRegex is enforced on this new heading/summary because, unlike
1467 # regular summaries, it is added to the actual wikitext.
1468 if ( $this->sectiontitle !== '' ) {
1469 # This branch is taken when the API is used with the 'sectiontitle' parameter.
1470 $match = self::matchSpamRegex( $this->sectiontitle );
1471 } else {
1472 # This branch is taken when the "Add Topic" user interface is used, or the API
1473 # is used with the 'summary' parameter.
1474 $match = self::matchSpamRegex( $this->summary );
1475 }
1476 }
1477 if ( $match === false ) {
1478 $match = self::matchSpamRegex( $this->textbox1 );
1479 }
1480 if ( $match !== false ) {
1481 $result['spam'] = $match;
1482 $ip = $wgRequest->getIP();
1483 $pdbk = $this->mTitle->getPrefixedDBkey();
1484 $match = str_replace( "\n", '', $match );
1485 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
1486 $status->fatal( 'spamprotectionmatch', $match );
1487 $status->value = self::AS_SPAM_ERROR;
1488 wfProfileOut( __METHOD__ . '-checks' );
1489 wfProfileOut( __METHOD__ );
1490 return $status;
1491 }
1492 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) ) ) {
1493 # Error messages etc. could be handled within the hook...
1494 $status->fatal( 'hookaborted' );
1495 $status->value = self::AS_HOOK_ERROR;
1496 wfProfileOut( __METHOD__ . '-checks' );
1497 wfProfileOut( __METHOD__ );
1498 return $status;
1499 } elseif ( $this->hookError != '' ) {
1500 # ...or the hook could be expecting us to produce an error
1501 $status->fatal( 'hookaborted' );
1502 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1503 wfProfileOut( __METHOD__ . '-checks' );
1504 wfProfileOut( __METHOD__ );
1505 return $status;
1506 }
1507
1508 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1509 // Auto-block user's IP if the account was "hard" blocked
1510 $wgUser->spreadAnyEditBlock();
1511 # Check block state against master, thus 'false'.
1512 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1513 wfProfileOut( __METHOD__ . '-checks' );
1514 wfProfileOut( __METHOD__ );
1515 return $status;
1516 }
1517
1518 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1519 if ( $this->kblength > $wgMaxArticleSize ) {
1520 // Error will be displayed by showEditForm()
1521 $this->tooBig = true;
1522 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1523 wfProfileOut( __METHOD__ . '-checks' );
1524 wfProfileOut( __METHOD__ );
1525 return $status;
1526 }
1527
1528 if ( !$wgUser->isAllowed( 'edit' ) ) {
1529 if ( $wgUser->isAnon() ) {
1530 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1531 wfProfileOut( __METHOD__ . '-checks' );
1532 wfProfileOut( __METHOD__ );
1533 return $status;
1534 } else {
1535 $status->fatal( 'readonlytext' );
1536 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1537 wfProfileOut( __METHOD__ . '-checks' );
1538 wfProfileOut( __METHOD__ );
1539 return $status;
1540 }
1541 }
1542
1543 if ( wfReadOnly() ) {
1544 $status->fatal( 'readonlytext' );
1545 $status->value = self::AS_READ_ONLY_PAGE;
1546 wfProfileOut( __METHOD__ . '-checks' );
1547 wfProfileOut( __METHOD__ );
1548 return $status;
1549 }
1550 if ( $wgUser->pingLimiter() || $wgUser->pingLimiter( 'linkpurge', 0 ) ) {
1551 $status->fatal( 'actionthrottledtext' );
1552 $status->value = self::AS_RATE_LIMITED;
1553 wfProfileOut( __METHOD__ . '-checks' );
1554 wfProfileOut( __METHOD__ );
1555 return $status;
1556 }
1557
1558 # If the article has been deleted while editing, don't save it without
1559 # confirmation
1560 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1561 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1562 wfProfileOut( __METHOD__ . '-checks' );
1563 wfProfileOut( __METHOD__ );
1564 return $status;
1565 }
1566
1567 wfProfileOut( __METHOD__ . '-checks' );
1568
1569 # Load the page data from the master. If anything changes in the meantime,
1570 # we detect it by using page_latest like a token in a 1 try compare-and-swap.
1571 $this->mArticle->loadPageData( 'fromdbmaster' );
1572 $new = !$this->mArticle->exists();
1573
1574 if ( $new ) {
1575 // Late check for create permission, just in case *PARANOIA*
1576 if ( !$this->mTitle->userCan( 'create', $wgUser ) ) {
1577 $status->fatal( 'nocreatetext' );
1578 $status->value = self::AS_NO_CREATE_PERMISSION;
1579 wfDebug( __METHOD__ . ": no create permission\n" );
1580 wfProfileOut( __METHOD__ );
1581 return $status;
1582 }
1583
1584 // Don't save a new page if it's blank or if it's a MediaWiki:
1585 // message with content equivalent to default (allow empty pages
1586 // in this case to disable messages, see bug 50124)
1587 $defaultMessageText = $this->mTitle->getDefaultMessageText();
1588 if ( $this->mTitle->getNamespace() === NS_MEDIAWIKI && $defaultMessageText !== false ) {
1589 $defaultText = $defaultMessageText;
1590 } else {
1591 $defaultText = '';
1592 }
1593
1594 if ( $this->textbox1 === $defaultText ) {
1595 $status->setResult( false, self::AS_BLANK_ARTICLE );
1596 wfProfileOut( __METHOD__ );
1597 return $status;
1598 }
1599
1600 if ( !$this->runPostMergeFilters( $textbox_content, $status, $wgUser ) ) {
1601 wfProfileOut( __METHOD__ );
1602 return $status;
1603 }
1604
1605 $content = $textbox_content;
1606
1607 $result['sectionanchor'] = '';
1608 if ( $this->section == 'new' ) {
1609 if ( $this->sectiontitle !== '' ) {
1610 // Insert the section title above the content.
1611 $content = $content->addSectionHeader( $this->sectiontitle );
1612
1613 // Jump to the new section
1614 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1615
1616 // If no edit summary was specified, create one automatically from the section
1617 // title and have it link to the new section. Otherwise, respect the summary as
1618 // passed.
1619 if ( $this->summary === '' ) {
1620 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1621 $this->summary = wfMessage( 'newsectionsummary' )
1622 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1623 }
1624 } elseif ( $this->summary !== '' ) {
1625 // Insert the section title above the content.
1626 $content = $content->addSectionHeader( $this->summary );
1627
1628 // Jump to the new section
1629 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1630
1631 // Create a link to the new section from the edit summary.
1632 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1633 $this->summary = wfMessage( 'newsectionsummary' )
1634 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1635 }
1636 }
1637
1638 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1639
1640 } else { # not $new
1641
1642 # Article exists. Check for edit conflict.
1643
1644 $this->mArticle->clear(); # Force reload of dates, etc.
1645 $timestamp = $this->mArticle->getTimestamp();
1646
1647 wfDebug( "timestamp: {$timestamp}, edittime: {$this->edittime}\n" );
1648
1649 if ( $timestamp != $this->edittime ) {
1650 $this->isConflict = true;
1651 if ( $this->section == 'new' ) {
1652 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
1653 $this->mArticle->getComment() == $this->summary ) {
1654 // Probably a duplicate submission of a new comment.
1655 // This can happen when squid resends a request after
1656 // a timeout but the first one actually went through.
1657 wfDebug( __METHOD__ . ": duplicate new section submission; trigger edit conflict!\n" );
1658 } else {
1659 // New comment; suppress conflict.
1660 $this->isConflict = false;
1661 wfDebug( __METHOD__ . ": conflict suppressed; new section\n" );
1662 }
1663 } elseif ( $this->section == '' && Revision::userWasLastToEdit( DB_MASTER, $this->mTitle->getArticleID(),
1664 $wgUser->getId(), $this->edittime ) ) {
1665 # Suppress edit conflict with self, except for section edits where merging is required.
1666 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1667 $this->isConflict = false;
1668 }
1669 }
1670
1671 // If sectiontitle is set, use it, otherwise use the summary as the section title.
1672 if ( $this->sectiontitle !== '' ) {
1673 $sectionTitle = $this->sectiontitle;
1674 } else {
1675 $sectionTitle = $this->summary;
1676 }
1677
1678 $content = null;
1679
1680 if ( $this->isConflict ) {
1681 wfDebug( __METHOD__ . ": conflict! getting section '{$this->section}' for time '{$this->edittime}'"
1682 . " (article time '{$timestamp}')\n" );
1683
1684 $content = $this->mArticle->replaceSectionContent( $this->section, $textbox_content, $sectionTitle, $this->edittime );
1685 } else {
1686 wfDebug( __METHOD__ . ": getting section '{$this->section}'\n" );
1687 $content = $this->mArticle->replaceSectionContent( $this->section, $textbox_content, $sectionTitle );
1688 }
1689
1690 if ( is_null( $content ) ) {
1691 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1692 $this->isConflict = true;
1693 $content = $textbox_content; // do not try to merge here!
1694 } elseif ( $this->isConflict ) {
1695 # Attempt merge
1696 if ( $this->mergeChangesIntoContent( $content ) ) {
1697 // Successful merge! Maybe we should tell the user the good news?
1698 $this->isConflict = false;
1699 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1700 } else {
1701 $this->section = '';
1702 $this->textbox1 = ContentHandler::getContentText( $content );
1703 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1704 }
1705 }
1706
1707 if ( $this->isConflict ) {
1708 $status->setResult( false, self::AS_CONFLICT_DETECTED );
1709 wfProfileOut( __METHOD__ );
1710 return $status;
1711 }
1712
1713 if ( !$this->runPostMergeFilters( $content, $status, $wgUser ) ) {
1714 wfProfileOut( __METHOD__ );
1715 return $status;
1716 }
1717
1718 if ( $this->section == 'new' ) {
1719 // Handle the user preference to force summaries here
1720 if ( !$this->allowBlankSummary && trim( $this->summary ) == '' ) {
1721 $this->missingSummary = true;
1722 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1723 $status->value = self::AS_SUMMARY_NEEDED;
1724 wfProfileOut( __METHOD__ );
1725 return $status;
1726 }
1727
1728 // Do not allow the user to post an empty comment
1729 if ( $this->textbox1 == '' ) {
1730 $this->missingComment = true;
1731 $status->fatal( 'missingcommenttext' );
1732 $status->value = self::AS_TEXTBOX_EMPTY;
1733 wfProfileOut( __METHOD__ );
1734 return $status;
1735 }
1736 } elseif ( !$this->allowBlankSummary
1737 && !$content->equals( $this->getOriginalContent() )
1738 && !$content->isRedirect()
1739 && md5( $this->summary ) == $this->autoSumm
1740 ) {
1741 $this->missingSummary = true;
1742 $status->fatal( 'missingsummary' );
1743 $status->value = self::AS_SUMMARY_NEEDED;
1744 wfProfileOut( __METHOD__ );
1745 return $status;
1746 }
1747
1748 # All's well
1749 wfProfileIn( __METHOD__ . '-sectionanchor' );
1750 $sectionanchor = '';
1751 if ( $this->section == 'new' ) {
1752 if ( $this->sectiontitle !== '' ) {
1753 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->sectiontitle );
1754 // If no edit summary was specified, create one automatically from the section
1755 // title and have it link to the new section. Otherwise, respect the summary as
1756 // passed.
1757 if ( $this->summary === '' ) {
1758 $cleanSectionTitle = $wgParser->stripSectionName( $this->sectiontitle );
1759 $this->summary = wfMessage( 'newsectionsummary' )
1760 ->rawParams( $cleanSectionTitle )->inContentLanguage()->text();
1761 }
1762 } elseif ( $this->summary !== '' ) {
1763 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1764 # This is a new section, so create a link to the new section
1765 # in the revision summary.
1766 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1767 $this->summary = wfMessage( 'newsectionsummary' )
1768 ->rawParams( $cleanSummary )->inContentLanguage()->text();
1769 }
1770 } elseif ( $this->section != '' ) {
1771 # Try to get a section anchor from the section source, redirect to edited section if header found
1772 # XXX: might be better to integrate this into Article::replaceSection
1773 # for duplicate heading checking and maybe parsing
1774 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1775 # we can't deal with anchors, includes, html etc in the header for now,
1776 # headline would need to be parsed to improve this
1777 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1778 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1779 }
1780 }
1781 $result['sectionanchor'] = $sectionanchor;
1782 wfProfileOut( __METHOD__ . '-sectionanchor' );
1783
1784 // Save errors may fall down to the edit form, but we've now
1785 // merged the section into full text. Clear the section field
1786 // so that later submission of conflict forms won't try to
1787 // replace that into a duplicated mess.
1788 $this->textbox1 = $this->toEditText( $content );
1789 $this->section = '';
1790
1791 $status->value = self::AS_SUCCESS_UPDATE;
1792 }
1793
1794 // Check for length errors again now that the section is merged in
1795 $this->kblength = (int)( strlen( $this->toEditText( $content ) ) / 1024 );
1796 if ( $this->kblength > $wgMaxArticleSize ) {
1797 $this->tooBig = true;
1798 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
1799 wfProfileOut( __METHOD__ );
1800 return $status;
1801 }
1802
1803 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1804 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
1805 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
1806 ( $bot ? EDIT_FORCE_BOT : 0 );
1807
1808 $doEditStatus = $this->mArticle->doEditContent( $content, $this->summary, $flags,
1809 false, null, $this->contentFormat );
1810
1811 if ( !$doEditStatus->isOK() ) {
1812 // Failure from doEdit()
1813 // Show the edit conflict page for certain recognized errors from doEdit(),
1814 // but don't show it for errors from extension hooks
1815 $errors = $doEditStatus->getErrorsArray();
1816 if ( in_array( $errors[0][0],
1817 array( 'edit-gone-missing', 'edit-conflict', 'edit-already-exists' ) )
1818 ) {
1819 $this->isConflict = true;
1820 // Destroys data doEdit() put in $status->value but who cares
1821 $doEditStatus->value = self::AS_END;
1822 }
1823 wfProfileOut( __METHOD__ );
1824 return $doEditStatus;
1825 }
1826
1827 $result['nullEdit'] = $doEditStatus->hasMessage( 'edit-no-change' );
1828 if ( $result['nullEdit'] ) {
1829 // We don't know if it was a null edit until now, so increment here
1830 $wgUser->pingLimiter( 'linkpurge' );
1831 }
1832 $result['redirect'] = $content->isRedirect();
1833 $this->updateWatchlist();
1834 wfProfileOut( __METHOD__ );
1835 return $status;
1836 }
1837
1838 /**
1839 * Register the change of watch status
1840 */
1841 protected function updateWatchlist() {
1842 global $wgUser;
1843
1844 if ( $wgUser->isLoggedIn()
1845 && $this->watchthis != $wgUser->isWatched( $this->mTitle, WatchedItem::IGNORE_USER_RIGHTS )
1846 ) {
1847 $fname = __METHOD__;
1848 $title = $this->mTitle;
1849 $watch = $this->watchthis;
1850
1851 // Do this in its own transaction to reduce contention...
1852 $dbw = wfGetDB( DB_MASTER );
1853 $dbw->onTransactionIdle( function() use ( $dbw, $title, $watch, $wgUser, $fname ) {
1854 $dbw->begin( $fname );
1855 WatchAction::doWatchOrUnwatch( $watch, $title, $wgUser );
1856 $dbw->commit( $fname );
1857 } );
1858 }
1859 }
1860
1861 /**
1862 * Attempts to merge text content with base and current revisions
1863 *
1864 * @param $editText string
1865 *
1866 * @return bool
1867 * @deprecated since 1.21, use mergeChangesIntoContent() instead
1868 */
1869 function mergeChangesInto( &$editText ) {
1870 ContentHandler::deprecated( __METHOD__, "1.21" );
1871
1872 $editContent = $this->toEditContent( $editText );
1873
1874 $ok = $this->mergeChangesIntoContent( $editContent );
1875
1876 if ( $ok ) {
1877 $editText = $this->toEditText( $editContent );
1878 return true;
1879 }
1880 return false;
1881 }
1882
1883 /**
1884 * Attempts to do 3-way merge of edit content with a base revision
1885 * and current content, in case of edit conflict, in whichever way appropriate
1886 * for the content type.
1887 *
1888 * @since 1.21
1889 *
1890 * @param $editContent
1891 *
1892 * @return bool
1893 */
1894 private function mergeChangesIntoContent( &$editContent ) {
1895 wfProfileIn( __METHOD__ );
1896
1897 $db = wfGetDB( DB_MASTER );
1898
1899 // This is the revision the editor started from
1900 $baseRevision = $this->getBaseRevision();
1901 $baseContent = $baseRevision ? $baseRevision->getContent() : null;
1902
1903 if ( is_null( $baseContent ) ) {
1904 wfProfileOut( __METHOD__ );
1905 return false;
1906 }
1907
1908 // The current state, we want to merge updates into it
1909 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
1910 $currentContent = $currentRevision ? $currentRevision->getContent() : null;
1911
1912 if ( is_null( $currentContent ) ) {
1913 wfProfileOut( __METHOD__ );
1914 return false;
1915 }
1916
1917 $handler = ContentHandler::getForModelID( $baseContent->getModel() );
1918
1919 $result = $handler->merge3( $baseContent, $editContent, $currentContent );
1920
1921 if ( $result ) {
1922 $editContent = $result;
1923 wfProfileOut( __METHOD__ );
1924 return true;
1925 }
1926
1927 wfProfileOut( __METHOD__ );
1928 return false;
1929 }
1930
1931 /**
1932 * @return Revision
1933 */
1934 function getBaseRevision() {
1935 if ( !$this->mBaseRevision ) {
1936 $db = wfGetDB( DB_MASTER );
1937 $this->mBaseRevision = Revision::loadFromTimestamp(
1938 $db, $this->mTitle, $this->edittime );
1939 }
1940 return $this->mBaseRevision;
1941 }
1942
1943 /**
1944 * Check given input text against $wgSpamRegex, and return the text of the first match.
1945 *
1946 * @param $text string
1947 *
1948 * @return string|bool matching string or false
1949 */
1950 public static function matchSpamRegex( $text ) {
1951 global $wgSpamRegex;
1952 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1953 $regexes = (array)$wgSpamRegex;
1954 return self::matchSpamRegexInternal( $text, $regexes );
1955 }
1956
1957 /**
1958 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
1959 *
1960 * @param $text string
1961 *
1962 * @return string|bool matching string or false
1963 */
1964 public static function matchSummarySpamRegex( $text ) {
1965 global $wgSummarySpamRegex;
1966 $regexes = (array)$wgSummarySpamRegex;
1967 return self::matchSpamRegexInternal( $text, $regexes );
1968 }
1969
1970 /**
1971 * @param $text string
1972 * @param $regexes array
1973 * @return bool|string
1974 */
1975 protected static function matchSpamRegexInternal( $text, $regexes ) {
1976 foreach ( $regexes as $regex ) {
1977 $matches = array();
1978 if ( preg_match( $regex, $text, $matches ) ) {
1979 return $matches[0];
1980 }
1981 }
1982 return false;
1983 }
1984
1985 function setHeaders() {
1986 global $wgOut, $wgUser;
1987
1988 $wgOut->addModules( 'mediawiki.action.edit' );
1989 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
1990
1991 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1992 $wgOut->addModules( 'mediawiki.action.edit.preview' );
1993 }
1994
1995 if ( $wgUser->getOption( 'useeditwarning', false ) ) {
1996 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
1997 }
1998
1999 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2000
2001 # Enabled article-related sidebar, toplinks, etc.
2002 $wgOut->setArticleRelated( true );
2003
2004 $contextTitle = $this->getContextTitle();
2005 if ( $this->isConflict ) {
2006 $msg = 'editconflict';
2007 } elseif ( $contextTitle->exists() && $this->section != '' ) {
2008 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
2009 } else {
2010 $msg = $contextTitle->exists() || ( $contextTitle->getNamespace() == NS_MEDIAWIKI && $contextTitle->getDefaultMessageText() !== false ) ?
2011 'editing' : 'creating';
2012 }
2013 # Use the title defined by DISPLAYTITLE magic word when present
2014 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
2015 if ( $displayTitle === false ) {
2016 $displayTitle = $contextTitle->getPrefixedText();
2017 }
2018 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2019 }
2020
2021 /**
2022 * Show all applicable editing introductions
2023 */
2024 protected function showIntro() {
2025 global $wgOut, $wgUser;
2026 if ( $this->suppressIntro ) {
2027 return;
2028 }
2029
2030 $namespace = $this->mTitle->getNamespace();
2031
2032 if ( $namespace == NS_MEDIAWIKI ) {
2033 # Show a warning if editing an interface message
2034 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2035 } elseif ( $namespace == NS_FILE ) {
2036 # Show a hint to shared repo
2037 $file = wfFindFile( $this->mTitle );
2038 if ( $file && !$file->isLocal() ) {
2039 $descUrl = $file->getDescriptionUrl();
2040 # there must be a description url to show a hint to shared repo
2041 if ( $descUrl ) {
2042 if ( !$this->mTitle->exists() ) {
2043 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2044 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2045 ) );
2046 } else {
2047 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2048 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2049 ) );
2050 }
2051 }
2052 }
2053 }
2054
2055 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2056 # Show log extract when the user is currently blocked
2057 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2058 $parts = explode( '/', $this->mTitle->getText(), 2 );
2059 $username = $parts[0];
2060 $user = User::newFromName( $username, false /* allow IP users*/ );
2061 $ip = User::isIP( $username );
2062 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2063 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2064 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2065 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
2066 LogEventsList::showLogExtract(
2067 $wgOut,
2068 'block',
2069 $user->getUserPage(),
2070 '',
2071 array(
2072 'lim' => 1,
2073 'showIfEmpty' => false,
2074 'msgKey' => array(
2075 'blocked-notice-logextract',
2076 $user->getName() # Support GENDER in notice
2077 )
2078 )
2079 );
2080 }
2081 }
2082 # Try to add a custom edit intro, or use the standard one if this is not possible.
2083 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2084 $helpLink = wfExpandUrl( Skin::makeInternalOrExternalUrl(
2085 wfMessage( 'helppage' )->inContentLanguage()->text()
2086 ) );
2087 if ( $wgUser->isLoggedIn() ) {
2088 $wgOut->wrapWikiMsg(
2089 // Suppress the external link icon, consider the help url an internal one
2090 "<div class=\"mw-newarticletext plainlinks\">\n$1\n</div>",
2091 array(
2092 'newarticletext',
2093 $helpLink
2094 )
2095 );
2096 } else {
2097 $wgOut->wrapWikiMsg(
2098 // Suppress the external link icon, consider the help url an internal one
2099 "<div class=\"mw-newarticletextanon plainlinks\">\n$1\n</div>",
2100 array(
2101 'newarticletextanon',
2102 $helpLink
2103 )
2104 );
2105 }
2106 }
2107 # Give a notice if the user is editing a deleted/moved page...
2108 if ( !$this->mTitle->exists() ) {
2109 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
2110 '',
2111 array(
2112 'lim' => 10,
2113 'conds' => array( "log_action != 'revision'" ),
2114 'showIfEmpty' => false,
2115 'msgKey' => array( 'recreate-moveddeleted-warn' )
2116 )
2117 );
2118 }
2119 }
2120
2121 /**
2122 * Attempt to show a custom editing introduction, if supplied
2123 *
2124 * @return bool
2125 */
2126 protected function showCustomIntro() {
2127 if ( $this->editintro ) {
2128 $title = Title::newFromText( $this->editintro );
2129 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2130 global $wgOut;
2131 // Added using template syntax, to take <noinclude>'s into account.
2132 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle );
2133 return true;
2134 }
2135 }
2136 return false;
2137 }
2138
2139 /**
2140 * Gets an editable textual representation of $content.
2141 * The textual representation can be turned by into a Content object by the
2142 * toEditContent() method.
2143 *
2144 * If $content is null or false or a string, $content is returned unchanged.
2145 *
2146 * If the given Content object is not of a type that can be edited using the text base EditPage,
2147 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2148 * content.
2149 *
2150 * @param Content|null|bool|string $content
2151 * @return String the editable text form of the content.
2152 *
2153 * @throws MWException if $content is not an instance of TextContent and $this->allowNonTextContent is not true.
2154 */
2155 protected function toEditText( $content ) {
2156 if ( $content === null || $content === false ) {
2157 return $content;
2158 }
2159
2160 if ( is_string( $content ) ) {
2161 return $content;
2162 }
2163
2164 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2165 throw new MWException( 'This content model is not supported: '
2166 . ContentHandler::getLocalizedName( $content->getModel() ) );
2167 }
2168
2169 return $content->serialize( $this->contentFormat );
2170 }
2171
2172 /**
2173 * Turns the given text into a Content object by unserializing it.
2174 *
2175 * If the resulting Content object is not of a type that can be edited using the text base EditPage,
2176 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2177 * content.
2178 *
2179 * @param string|null|bool $text Text to unserialize
2180 * @return Content The content object created from $text. If $text was false or null, false resp. null will be
2181 * returned instead.
2182 *
2183 * @throws MWException if unserializing the text results in a Content object that is not an instance of TextContent
2184 * and $this->allowNonTextContent is not true.
2185 */
2186 protected function toEditContent( $text ) {
2187 if ( $text === false || $text === null ) {
2188 return $text;
2189 }
2190
2191 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2192 $this->contentModel, $this->contentFormat );
2193
2194 if ( !$this->isSupportedContentModel( $content->getModel() ) ) {
2195 throw new MWException( 'This content model is not supported: '
2196 . ContentHandler::getLocalizedName( $content->getModel() ) );
2197 }
2198
2199 return $content;
2200 }
2201
2202 /**
2203 * Send the edit form and related headers to $wgOut
2204 * @param $formCallback Callback|null that takes an OutputPage parameter; will be called
2205 * during form output near the top, for captchas and the like.
2206 */
2207 function showEditForm( $formCallback = null ) {
2208 global $wgOut, $wgUser;
2209
2210 wfProfileIn( __METHOD__ );
2211
2212 # need to parse the preview early so that we know which templates are used,
2213 # otherwise users with "show preview after edit box" will get a blank list
2214 # we parse this near the beginning so that setHeaders can do the title
2215 # setting work instead of leaving it in getPreviewText
2216 $previewOutput = '';
2217 if ( $this->formtype == 'preview' ) {
2218 $previewOutput = $this->getPreviewText();
2219 }
2220
2221 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2222
2223 $this->setHeaders();
2224
2225 if ( $this->showHeader() === false ) {
2226 wfProfileOut( __METHOD__ );
2227 return;
2228 }
2229
2230 $wgOut->addHTML( $this->editFormPageTop );
2231
2232 if ( $wgUser->getOption( 'previewontop' ) ) {
2233 $this->displayPreviewArea( $previewOutput, true );
2234 }
2235
2236 $wgOut->addHTML( $this->editFormTextTop );
2237
2238 $showToolbar = true;
2239 if ( $this->wasDeletedSinceLastEdit() ) {
2240 if ( $this->formtype == 'save' ) {
2241 // Hide the toolbar and edit area, user can click preview to get it back
2242 // Add an confirmation checkbox and explanation.
2243 $showToolbar = false;
2244 } else {
2245 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2246 'deletedwhileediting' );
2247 }
2248 }
2249
2250 // @todo add EditForm plugin interface and use it here!
2251 // search for textarea1 and textares2, and allow EditForm to override all uses.
2252 $wgOut->addHTML( Html::openElement( 'form', array( 'id' => self::EDITFORM_ID, 'name' => self::EDITFORM_ID,
2253 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
2254 'enctype' => 'multipart/form-data' ) ) );
2255
2256 if ( is_callable( $formCallback ) ) {
2257 call_user_func_array( $formCallback, array( &$wgOut ) );
2258 }
2259
2260 // Add an empty field to trip up spambots
2261 $wgOut->addHTML(
2262 Xml::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2263 . Html::rawElement( 'label', array( 'for' => 'wpAntiSpam' ), wfMessage( 'simpleantispam-label' )->parse() )
2264 . Xml::element( 'input', array( 'type' => 'text', 'name' => 'wpAntispam', 'id' => 'wpAntispam', 'value' => '' ) )
2265 . Xml::closeElement( 'div' )
2266 );
2267
2268 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2269
2270 // Put these up at the top to ensure they aren't lost on early form submission
2271 $this->showFormBeforeText();
2272
2273 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2274 $username = $this->lastDelete->user_name;
2275 $comment = $this->lastDelete->log_comment;
2276
2277 // It is better to not parse the comment at all than to have templates expanded in the middle
2278 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2279 $key = $comment === ''
2280 ? 'confirmrecreate-noreason'
2281 : 'confirmrecreate';
2282 $wgOut->addHTML(
2283 '<div class="mw-confirm-recreate">' .
2284 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2285 Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2286 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2287 ) .
2288 '</div>'
2289 );
2290 }
2291
2292 # When the summary is hidden, also hide them on preview/show changes
2293 if ( $this->nosummary ) {
2294 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2295 }
2296
2297 # If a blank edit summary was previously provided, and the appropriate
2298 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2299 # user being bounced back more than once in the event that a summary
2300 # is not required.
2301 #####
2302 # For a bit more sophisticated detection of blank summaries, hash the
2303 # automatic one and pass that in the hidden field wpAutoSummary.
2304 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2305 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2306 }
2307
2308 if ( $this->undidRev ) {
2309 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2310 }
2311
2312 if ( $this->hasPresetSummary ) {
2313 // If a summary has been preset using &summary= we don't want to prompt for
2314 // a different summary. Only prompt for a summary if the summary is blanked.
2315 // (Bug 17416)
2316 $this->autoSumm = md5( '' );
2317 }
2318
2319 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2320 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2321
2322 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2323
2324 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2325 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2326
2327 if ( $this->section == 'new' ) {
2328 $this->showSummaryInput( true, $this->summary );
2329 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2330 }
2331
2332 $wgOut->addHTML( $this->editFormTextBeforeContent );
2333
2334 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2335 $wgOut->addHTML( EditPage::getEditToolbar() );
2336 }
2337
2338 if ( $this->isConflict ) {
2339 // In an edit conflict bypass the overridable content form method
2340 // and fallback to the raw wpTextbox1 since editconflicts can't be
2341 // resolved between page source edits and custom ui edits using the
2342 // custom edit ui.
2343 $this->textbox2 = $this->textbox1;
2344
2345 $content = $this->getCurrentContent();
2346 $this->textbox1 = $this->toEditText( $content );
2347
2348 $this->showTextbox1();
2349 } else {
2350 $this->showContentForm();
2351 }
2352
2353 $wgOut->addHTML( $this->editFormTextAfterContent );
2354
2355 $this->showStandardInputs();
2356
2357 $this->showFormAfterText();
2358
2359 $this->showTosSummary();
2360
2361 $this->showEditTools();
2362
2363 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2364
2365 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2366 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
2367
2368 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
2369 Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
2370
2371 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'limitreport' ),
2372 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2373
2374 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2375
2376 if ( $this->isConflict ) {
2377 try {
2378 $this->showConflict();
2379 } catch ( MWContentSerializationException $ex ) {
2380 // this can't really happen, but be nice if it does.
2381 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
2382 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2383 }
2384 }
2385
2386 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2387
2388 if ( !$wgUser->getOption( 'previewontop' ) ) {
2389 $this->displayPreviewArea( $previewOutput, false );
2390 }
2391
2392 wfProfileOut( __METHOD__ );
2393 }
2394
2395 /**
2396 * Extract the section title from current section text, if any.
2397 *
2398 * @param string $text
2399 * @return Mixed|string or false
2400 */
2401 public static function extractSectionTitle( $text ) {
2402 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2403 if ( !empty( $matches[2] ) ) {
2404 global $wgParser;
2405 return $wgParser->stripSectionName( trim( $matches[2] ) );
2406 } else {
2407 return false;
2408 }
2409 }
2410
2411 protected function showHeader() {
2412 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2413
2414 if ( $this->mTitle->isTalkPage() ) {
2415 $wgOut->addWikiMsg( 'talkpagetext' );
2416 }
2417
2418 // Add edit notices
2419 $wgOut->addHTML( implode( "\n", $this->mTitle->getEditNotices( $this->oldid ) ) );
2420
2421 if ( $this->isConflict ) {
2422 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2423 $this->edittime = $this->mArticle->getTimestamp();
2424 } else {
2425 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
2426 // We use $this->section to much before this and getVal('wgSection') directly in other places
2427 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2428 // Someone is welcome to try refactoring though
2429 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2430 return false;
2431 }
2432
2433 if ( $this->section != '' && $this->section != 'new' ) {
2434 if ( !$this->summary && !$this->preview && !$this->diff ) {
2435 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); //FIXME: use Content object
2436 if ( $sectionTitle !== false ) {
2437 $this->summary = "/* $sectionTitle */ ";
2438 }
2439 }
2440 }
2441
2442 if ( $this->missingComment ) {
2443 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2444 }
2445
2446 if ( $this->missingSummary && $this->section != 'new' ) {
2447 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2448 }
2449
2450 if ( $this->missingSummary && $this->section == 'new' ) {
2451 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2452 }
2453
2454 if ( $this->hookError !== '' ) {
2455 $wgOut->addWikiText( $this->hookError );
2456 }
2457
2458 if ( !$this->checkUnicodeCompliantBrowser() ) {
2459 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2460 }
2461
2462 if ( $this->section != 'new' ) {
2463 $revision = $this->mArticle->getRevisionFetched();
2464 if ( $revision ) {
2465 // Let sysop know that this will make private content public if saved
2466
2467 if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2468 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2469 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2470 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2471 }
2472
2473 if ( !$revision->isCurrent() ) {
2474 $this->mArticle->setOldSubtitle( $revision->getId() );
2475 $wgOut->addWikiMsg( 'editingold' );
2476 }
2477 } elseif ( $this->mTitle->exists() ) {
2478 // Something went wrong
2479
2480 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2481 array( 'missing-revision', $this->oldid ) );
2482 }
2483 }
2484 }
2485
2486 if ( wfReadOnly() ) {
2487 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2488 } elseif ( $wgUser->isAnon() ) {
2489 if ( $this->formtype != 'preview' ) {
2490 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2491 } else {
2492 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2493 }
2494 } else {
2495 if ( $this->isCssJsSubpage ) {
2496 # Check the skin exists
2497 if ( $this->isWrongCaseCssJsPage ) {
2498 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
2499 }
2500 if ( $this->formtype !== 'preview' ) {
2501 if ( $this->isCssSubpage ) {
2502 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2503 }
2504
2505 if ( $this->isJsSubpage ) {
2506 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2507 }
2508 }
2509 }
2510 }
2511
2512 if ( $this->mTitle->isProtected( 'edit' ) &&
2513 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2514 ) {
2515 # Is the title semi-protected?
2516 if ( $this->mTitle->isSemiProtected() ) {
2517 $noticeMsg = 'semiprotectedpagewarning';
2518 } else {
2519 # Then it must be protected based on static groups (regular)
2520 $noticeMsg = 'protectedpagewarning';
2521 }
2522 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2523 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2524 }
2525 if ( $this->mTitle->isCascadeProtected() ) {
2526 # Is this page under cascading protection from some source pages?
2527 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2528 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2529 $cascadeSourcesCount = count( $cascadeSources );
2530 if ( $cascadeSourcesCount > 0 ) {
2531 # Explain, and list the titles responsible
2532 foreach ( $cascadeSources as $page ) {
2533 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2534 }
2535 }
2536 $notice .= '</div>';
2537 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2538 }
2539 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2540 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2541 array( 'lim' => 1,
2542 'showIfEmpty' => false,
2543 'msgKey' => array( 'titleprotectedwarning' ),
2544 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2545 }
2546
2547 if ( $this->kblength === false ) {
2548 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2549 }
2550
2551 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2552 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2553 array( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2554 } else {
2555 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2556 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2557 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 ) )
2558 );
2559 }
2560 }
2561 # Add header copyright warning
2562 $this->showHeaderCopyrightWarning();
2563 }
2564
2565 /**
2566 * Standard summary input and label (wgSummary), abstracted so EditPage
2567 * subclasses may reorganize the form.
2568 * Note that you do not need to worry about the label's for=, it will be
2569 * inferred by the id given to the input. You can remove them both by
2570 * passing array( 'id' => false ) to $userInputAttrs.
2571 *
2572 * @param string $summary The value of the summary input
2573 * @param string $labelText The html to place inside the label
2574 * @param array $inputAttrs of attrs to use on the input
2575 * @param array $spanLabelAttrs of attrs to use on the span inside the label
2576 *
2577 * @return array An array in the format array( $label, $input )
2578 */
2579 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2580 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2581 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2582 'id' => 'wpSummary',
2583 'maxlength' => '200',
2584 'tabindex' => '1',
2585 'size' => 60,
2586 'spellcheck' => 'true',
2587 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2588
2589 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2590 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2591 'id' => "wpSummaryLabel"
2592 );
2593
2594 $label = null;
2595 if ( $labelText ) {
2596 $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2597 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2598 }
2599
2600 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2601
2602 return array( $label, $input );
2603 }
2604
2605 /**
2606 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2607 * up top, or false if this is the comment summary
2608 * down below the textarea
2609 * @param string $summary The text of the summary to display
2610 * @return String
2611 */
2612 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2613 global $wgOut, $wgContLang;
2614 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2615 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2616 if ( $isSubjectPreview ) {
2617 if ( $this->nosummary ) {
2618 return;
2619 }
2620 } else {
2621 if ( !$this->mShowSummaryField ) {
2622 return;
2623 }
2624 }
2625 $summary = $wgContLang->recodeForEdit( $summary );
2626 $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
2627 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2628 $wgOut->addHTML( "{$label} {$input}" );
2629 }
2630
2631 /**
2632 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2633 * up top, or false if this is the comment summary
2634 * down below the textarea
2635 * @param string $summary the text of the summary to display
2636 * @return String
2637 */
2638 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2639 // avoid spaces in preview, gets always trimmed on save
2640 $summary = trim( $summary );
2641 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
2642 return "";
2643 }
2644
2645 global $wgParser;
2646
2647 if ( $isSubjectPreview ) {
2648 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2649 ->inContentLanguage()->text();
2650 }
2651
2652 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
2653
2654 $summary = wfMessage( $message )->parse() . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
2655 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2656 }
2657
2658 protected function showFormBeforeText() {
2659 global $wgOut;
2660 $section = htmlspecialchars( $this->section );
2661 $wgOut->addHTML( <<<HTML
2662 <input type='hidden' value="{$section}" name="wpSection" />
2663 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2664 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2665 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2666
2667 HTML
2668 );
2669 if ( !$this->checkUnicodeCompliantBrowser() ) {
2670 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
2671 }
2672 }
2673
2674 protected function showFormAfterText() {
2675 global $wgOut, $wgUser;
2676 /**
2677 * To make it harder for someone to slip a user a page
2678 * which submits an edit form to the wiki without their
2679 * knowledge, a random token is associated with the login
2680 * session. If it's not passed back with the submission,
2681 * we won't save the page, or render user JavaScript and
2682 * CSS previews.
2683 *
2684 * For anon editors, who may not have a session, we just
2685 * include the constant suffix to prevent editing from
2686 * broken text-mangling proxies.
2687 */
2688 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2689 }
2690
2691 /**
2692 * Subpage overridable method for printing the form for page content editing
2693 * By default this simply outputs wpTextbox1
2694 * Subclasses can override this to provide a custom UI for editing;
2695 * be it a form, or simply wpTextbox1 with a modified content that will be
2696 * reverse modified when extracted from the post data.
2697 * Note that this is basically the inverse for importContentFormData
2698 */
2699 protected function showContentForm() {
2700 $this->showTextbox1();
2701 }
2702
2703 /**
2704 * Method to output wpTextbox1
2705 * The $textoverride method can be used by subclasses overriding showContentForm
2706 * to pass back to this method.
2707 *
2708 * @param array $customAttribs of html attributes to use in the textarea
2709 * @param string $textoverride optional text to override $this->textarea1 with
2710 */
2711 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2712 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2713 $attribs = array( 'style' => 'display:none;' );
2714 } else {
2715 $classes = array(); // Textarea CSS
2716 if ( $this->mTitle->isProtected( 'edit' ) &&
2717 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2718 ) {
2719 # Is the title semi-protected?
2720 if ( $this->mTitle->isSemiProtected() ) {
2721 $classes[] = 'mw-textarea-sprotected';
2722 } else {
2723 # Then it must be protected based on static groups (regular)
2724 $classes[] = 'mw-textarea-protected';
2725 }
2726 # Is the title cascade-protected?
2727 if ( $this->mTitle->isCascadeProtected() ) {
2728 $classes[] = 'mw-textarea-cprotected';
2729 }
2730 }
2731
2732 $attribs = array( 'tabindex' => 1 );
2733
2734 if ( is_array( $customAttribs ) ) {
2735 $attribs += $customAttribs;
2736 }
2737
2738 if ( count( $classes ) ) {
2739 if ( isset( $attribs['class'] ) ) {
2740 $classes[] = $attribs['class'];
2741 }
2742 $attribs['class'] = implode( ' ', $classes );
2743 }
2744 }
2745
2746 $this->showTextbox( $textoverride !== null ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
2747 }
2748
2749 protected function showTextbox2() {
2750 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2751 }
2752
2753 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2754 global $wgOut, $wgUser;
2755
2756 $wikitext = $this->safeUnicodeOutput( $text );
2757 if ( strval( $wikitext ) !== '' ) {
2758 // Ensure there's a newline at the end, otherwise adding lines
2759 // is awkward.
2760 // But don't add a newline if the ext is empty, or Firefox in XHTML
2761 // mode will show an extra newline. A bit annoying.
2762 $wikitext .= "\n";
2763 }
2764
2765 $attribs = $customAttribs + array(
2766 'accesskey' => ',',
2767 'id' => $name,
2768 'cols' => $wgUser->getIntOption( 'cols' ),
2769 'rows' => $wgUser->getIntOption( 'rows' ),
2770 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2771 );
2772
2773 $pageLang = $this->mTitle->getPageLanguage();
2774 $attribs['lang'] = $pageLang->getCode();
2775 $attribs['dir'] = $pageLang->getDir();
2776
2777 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
2778 }
2779
2780 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2781 global $wgOut;
2782 $classes = array();
2783 if ( $isOnTop ) {
2784 $classes[] = 'ontop';
2785 }
2786
2787 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2788
2789 if ( $this->formtype != 'preview' ) {
2790 $attribs['style'] = 'display: none;';
2791 }
2792
2793 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
2794
2795 if ( $this->formtype == 'preview' ) {
2796 $this->showPreview( $previewOutput );
2797 }
2798
2799 $wgOut->addHTML( '</div>' );
2800
2801 if ( $this->formtype == 'diff' ) {
2802 try {
2803 $this->showDiff();
2804 } catch ( MWContentSerializationException $ex ) {
2805 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
2806 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2807 }
2808 }
2809 }
2810
2811 /**
2812 * Append preview output to $wgOut.
2813 * Includes category rendering if this is a category page.
2814 *
2815 * @param string $text the HTML to be output for the preview.
2816 */
2817 protected function showPreview( $text ) {
2818 global $wgOut;
2819 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2820 $this->mArticle->openShowCategory();
2821 }
2822 # This hook seems slightly odd here, but makes things more
2823 # consistent for extensions.
2824 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2825 $wgOut->addHTML( $text );
2826 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2827 $this->mArticle->closeShowCategory();
2828 }
2829 }
2830
2831 /**
2832 * Get a diff between the current contents of the edit box and the
2833 * version of the page we're editing from.
2834 *
2835 * If this is a section edit, we'll replace the section as for final
2836 * save and then make a comparison.
2837 */
2838 function showDiff() {
2839 global $wgUser, $wgContLang, $wgOut;
2840
2841 $oldtitlemsg = 'currentrev';
2842 # if message does not exist, show diff against the preloaded default
2843 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
2844 $oldtext = $this->mTitle->getDefaultMessageText();
2845 if ( $oldtext !== false ) {
2846 $oldtitlemsg = 'defaultmessagetext';
2847 $oldContent = $this->toEditContent( $oldtext );
2848 } else {
2849 $oldContent = null;
2850 }
2851 } else {
2852 $oldContent = $this->getCurrentContent();
2853 }
2854
2855 $textboxContent = $this->toEditContent( $this->textbox1 );
2856
2857 $newContent = $this->mArticle->replaceSectionContent(
2858 $this->section, $textboxContent,
2859 $this->summary, $this->edittime );
2860
2861 if ( $newContent ) {
2862 ContentHandler::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
2863 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2864
2865 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
2866 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
2867 }
2868
2869 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
2870 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2871 $newtitle = wfMessage( 'yourtext' )->parse();
2872
2873 if ( !$oldContent ) {
2874 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
2875 }
2876
2877 if ( !$newContent ) {
2878 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
2879 }
2880
2881 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
2882 $de->setContent( $oldContent, $newContent );
2883
2884 $difftext = $de->getDiff( $oldtitle, $newtitle );
2885 $de->showDiffStyle();
2886 } else {
2887 $difftext = '';
2888 }
2889
2890 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2891 }
2892
2893 /**
2894 * Show the header copyright warning.
2895 */
2896 protected function showHeaderCopyrightWarning() {
2897 $msg = 'editpage-head-copy-warn';
2898 if ( !wfMessage( $msg )->isDisabled() ) {
2899 global $wgOut;
2900 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2901 'editpage-head-copy-warn' );
2902 }
2903 }
2904
2905 /**
2906 * Give a chance for site and per-namespace customizations of
2907 * terms of service summary link that might exist separately
2908 * from the copyright notice.
2909 *
2910 * This will display between the save button and the edit tools,
2911 * so should remain short!
2912 */
2913 protected function showTosSummary() {
2914 $msg = 'editpage-tos-summary';
2915 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
2916 if ( !wfMessage( $msg )->isDisabled() ) {
2917 global $wgOut;
2918 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2919 $wgOut->addWikiMsg( $msg );
2920 $wgOut->addHTML( '</div>' );
2921 }
2922 }
2923
2924 protected function showEditTools() {
2925 global $wgOut;
2926 $wgOut->addHTML( '<div class="mw-editTools">' .
2927 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2928 '</div>' );
2929 }
2930
2931 /**
2932 * Get the copyright warning
2933 *
2934 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2935 */
2936 protected function getCopywarn() {
2937 return self::getCopyrightWarning( $this->mTitle );
2938 }
2939
2940 /**
2941 * Get the copyright warning, by default returns wikitext
2942 *
2943 * @param Title $title
2944 * @param string $format output format, valid values are any function of
2945 * a Message object
2946 * @return string
2947 */
2948 public static function getCopyrightWarning( $title, $format = 'plain' ) {
2949 global $wgRightsText;
2950 if ( $wgRightsText ) {
2951 $copywarnMsg = array( 'copyrightwarning',
2952 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2953 $wgRightsText );
2954 } else {
2955 $copywarnMsg = array( 'copyrightwarning2',
2956 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2957 }
2958 // Allow for site and per-namespace customization of contribution/copyright notice.
2959 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2960
2961 return "<div id=\"editpage-copywarn\">\n" .
2962 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
2963 }
2964
2965 /**
2966 * Get the Limit report for page previews
2967 *
2968 * @since 1.22
2969 * @param ParserOutput $output ParserOutput object from the parse
2970 * @return string HTML
2971 */
2972 public static function getPreviewLimitReport( $output ) {
2973 if ( !$output || !$output->getLimitReportData() ) {
2974 return '';
2975 }
2976
2977 wfProfileIn( __METHOD__ );
2978
2979 $limitReport = Html::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
2980 wfMessage( 'limitreport-title' )->parseAsBlock()
2981 );
2982
2983 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
2984 $limitReport .= Html::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
2985
2986 $limitReport .= Html::openElement( 'table', array(
2987 'class' => 'preview-limit-report wikitable'
2988 ) ) .
2989 Html::openElement( 'tbody' );
2990
2991 foreach ( $output->getLimitReportData() as $key => $value ) {
2992 if ( wfRunHooks( 'ParserLimitReportFormat',
2993 array( $key, &$value, &$limitReport, true, true )
2994 ) ) {
2995 $keyMsg = wfMessage( $key );
2996 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
2997 if ( !$valueMsg->exists() ) {
2998 $valueMsg = new RawMessage( '$1' );
2999 }
3000 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
3001 $limitReport .= Html::openElement( 'tr' ) .
3002 Html::rawElement( 'th', null, $keyMsg->parse() ) .
3003 Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
3004 Html::closeElement( 'tr' );
3005 }
3006 }
3007 }
3008
3009 $limitReport .= Html::closeElement( 'tbody' ) .
3010 Html::closeElement( 'table' ) .
3011 Html::closeElement( 'div' );
3012
3013 wfProfileOut( __METHOD__ );
3014
3015 return $limitReport;
3016 }
3017
3018 protected function showStandardInputs( &$tabindex = 2 ) {
3019 global $wgOut;
3020 $wgOut->addHTML( "<div class='editOptions'>\n" );
3021
3022 if ( $this->section != 'new' ) {
3023 $this->showSummaryInput( false, $this->summary );
3024 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
3025 }
3026
3027 $checkboxes = $this->getCheckboxes( $tabindex,
3028 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
3029 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
3030
3031 // Show copyright warning.
3032 $wgOut->addWikiText( $this->getCopywarn() );
3033 $wgOut->addHTML( $this->editFormTextAfterWarn );
3034
3035 $wgOut->addHTML( "<div class='editButtons'>\n" );
3036 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3037
3038 $cancel = $this->getCancelLink();
3039 if ( $cancel !== '' ) {
3040 $cancel .= Html::element( 'span',
3041 array( 'class' => 'mw-editButtons-pipe-separator' ),
3042 wfMessage( 'pipe-separator' )->text() );
3043 }
3044 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
3045 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
3046 wfMessage( 'edithelp' )->escaped() . '</a> ' .
3047 wfMessage( 'newwindow' )->parse();
3048 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3049 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3050 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3051 wfRunHooks( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3052 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3053 }
3054
3055 /**
3056 * Show an edit conflict. textbox1 is already shown in showEditForm().
3057 * If you want to use another entry point to this function, be careful.
3058 */
3059 protected function showConflict() {
3060 global $wgOut;
3061
3062 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3063 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3064
3065 $content1 = $this->toEditContent( $this->textbox1 );
3066 $content2 = $this->toEditContent( $this->textbox2 );
3067
3068 $handler = ContentHandler::getForModelID( $this->contentModel );
3069 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3070 $de->setContent( $content2, $content1 );
3071 $de->showDiff(
3072 wfMessage( 'yourtext' )->parse(),
3073 wfMessage( 'storedversion' )->text()
3074 );
3075
3076 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3077 $this->showTextbox2();
3078 }
3079 }
3080
3081 /**
3082 * @return string
3083 */
3084 public function getCancelLink() {
3085 $cancelParams = array();
3086 if ( !$this->isConflict && $this->oldid > 0 ) {
3087 $cancelParams['oldid'] = $this->oldid;
3088 }
3089
3090 return Linker::linkKnown(
3091 $this->getContextTitle(),
3092 wfMessage( 'cancel' )->parse(),
3093 array( 'id' => 'mw-editform-cancel' ),
3094 $cancelParams
3095 );
3096 }
3097
3098 /**
3099 * Returns the URL to use in the form's action attribute.
3100 * This is used by EditPage subclasses when simply customizing the action
3101 * variable in the constructor is not enough. This can be used when the
3102 * EditPage lives inside of a Special page rather than a custom page action.
3103 *
3104 * @param $title Title object for which is being edited (where we go to for &action= links)
3105 * @return string
3106 */
3107 protected function getActionURL( Title $title ) {
3108 return $title->getLocalURL( array( 'action' => $this->action ) );
3109 }
3110
3111 /**
3112 * Check if a page was deleted while the user was editing it, before submit.
3113 * Note that we rely on the logging table, which hasn't been always there,
3114 * but that doesn't matter, because this only applies to brand new
3115 * deletes.
3116 */
3117 protected function wasDeletedSinceLastEdit() {
3118 if ( $this->deletedSinceEdit !== null ) {
3119 return $this->deletedSinceEdit;
3120 }
3121
3122 $this->deletedSinceEdit = false;
3123
3124 if ( $this->mTitle->isDeletedQuick() ) {
3125 $this->lastDelete = $this->getLastDelete();
3126 if ( $this->lastDelete ) {
3127 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3128 if ( $deleteTime > $this->starttime ) {
3129 $this->deletedSinceEdit = true;
3130 }
3131 }
3132 }
3133
3134 return $this->deletedSinceEdit;
3135 }
3136
3137 protected function getLastDelete() {
3138 $dbr = wfGetDB( DB_SLAVE );
3139 $data = $dbr->selectRow(
3140 array( 'logging', 'user' ),
3141 array(
3142 'log_type',
3143 'log_action',
3144 'log_timestamp',
3145 'log_user',
3146 'log_namespace',
3147 'log_title',
3148 'log_comment',
3149 'log_params',
3150 'log_deleted',
3151 'user_name'
3152 ), array(
3153 'log_namespace' => $this->mTitle->getNamespace(),
3154 'log_title' => $this->mTitle->getDBkey(),
3155 'log_type' => 'delete',
3156 'log_action' => 'delete',
3157 'user_id=log_user'
3158 ),
3159 __METHOD__,
3160 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3161 );
3162 // Quick paranoid permission checks...
3163 if ( is_object( $data ) ) {
3164 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3165 $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
3166 }
3167
3168 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3169 $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
3170 }
3171 }
3172 return $data;
3173 }
3174
3175 /**
3176 * Get the rendered text for previewing.
3177 * @throws MWException
3178 * @return string
3179 */
3180 function getPreviewText() {
3181 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3182
3183 wfProfileIn( __METHOD__ );
3184
3185 if ( $wgRawHtml && !$this->mTokenOk ) {
3186 // Could be an offsite preview attempt. This is very unsafe if
3187 // HTML is enabled, as it could be an attack.
3188 $parsedNote = '';
3189 if ( $this->textbox1 !== '' ) {
3190 // Do not put big scary notice, if previewing the empty
3191 // string, which happens when you initially edit
3192 // a category page, due to automatic preview-on-open.
3193 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3194 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3195 }
3196 wfProfileOut( __METHOD__ );
3197 return $parsedNote;
3198 }
3199
3200 $note = '';
3201
3202 try {
3203 $content = $this->toEditContent( $this->textbox1 );
3204
3205 $previewHTML = '';
3206 if ( !wfRunHooks( 'AlternateEditPreview', array( $this, &$content, &$previewHTML, &$this->mParserOutput ) ) ) {
3207 wfProfileOut( __METHOD__ );
3208 return $previewHTML;
3209 }
3210
3211 # provide a anchor link to the editform
3212 $continueEditing = '<span class="mw-continue-editing">' .
3213 '[[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' .
3214 wfMessage( 'continue-editing' )->text() . ']]</span>';
3215 if ( $this->mTriedSave && !$this->mTokenOk ) {
3216 if ( $this->mTokenOkExceptSuffix ) {
3217 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3218
3219 } else {
3220 $note = wfMessage( 'session_fail_preview' )->plain();
3221 }
3222 } elseif ( $this->incompleteForm ) {
3223 $note = wfMessage( 'edit_form_incomplete' )->plain();
3224 } else {
3225 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3226 }
3227
3228 $parserOptions = $this->mArticle->makeParserOptions( $this->mArticle->getContext() );
3229 $parserOptions->setEditSection( false );
3230 $parserOptions->setIsPreview( true );
3231 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3232
3233 # don't parse non-wikitext pages, show message about preview
3234 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3235 if ( $this->mTitle->isCssJsSubpage() ) {
3236 $level = 'user';
3237 } elseif ( $this->mTitle->isCssOrJsPage() ) {
3238 $level = 'site';
3239 } else {
3240 $level = false;
3241 }
3242
3243 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3244 $format = 'css';
3245 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3246 $format = 'js';
3247 } else {
3248 $format = false;
3249 }
3250
3251 # Used messages to make sure grep find them:
3252 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3253 if ( $level && $format ) {
3254 $note = "<div id='mw-{$level}{$format}preview'>" .
3255 wfMessage( "{$level}{$format}preview" )->text() .
3256 ' ' . $continueEditing . "</div>";
3257 }
3258 }
3259
3260 # If we're adding a comment, we need to show the
3261 # summary as the headline
3262 if ( $this->section === "new" && $this->summary !== "" ) {
3263 $content = $content->addSectionHeader( $this->summary );
3264 }
3265
3266 $hook_args = array( $this, &$content );
3267 ContentHandler::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3268 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
3269
3270 $parserOptions->enableLimitReport();
3271
3272 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3273 # But it's now deprecated, so never mind
3274
3275 $content = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3276 $parserOutput = $content->getParserOutput( $this->getArticle()->getTitle(), null, $parserOptions );
3277
3278 $previewHTML = $parserOutput->getText();
3279 $this->mParserOutput = $parserOutput;
3280 $wgOut->addParserOutputNoText( $parserOutput );
3281
3282 if ( count( $parserOutput->getWarnings() ) ) {
3283 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3284 }
3285 } catch ( MWContentSerializationException $ex ) {
3286 $m = wfMessage( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
3287 $note .= "\n\n" . $m->parse();
3288 $previewHTML = '';
3289 }
3290
3291 if ( $this->isConflict ) {
3292 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3293 } else {
3294 $conflict = '<hr />';
3295 }
3296
3297 $previewhead = "<div class='previewnote'>\n" .
3298 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3299 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3300
3301 $pageViewLang = $this->mTitle->getPageViewLanguage();
3302 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3303 'class' => 'mw-content-' . $pageViewLang->getDir() );
3304 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3305
3306 wfProfileOut( __METHOD__ );
3307 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3308 }
3309
3310 /**
3311 * @return Array
3312 */
3313 function getTemplates() {
3314 if ( $this->preview || $this->section != '' ) {
3315 $templates = array();
3316 if ( !isset( $this->mParserOutput ) ) {
3317 return $templates;
3318 }
3319 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3320 foreach ( array_keys( $template ) as $dbk ) {
3321 $templates[] = Title::makeTitle( $ns, $dbk );
3322 }
3323 }
3324 return $templates;
3325 } else {
3326 return $this->mTitle->getTemplateLinksFrom();
3327 }
3328 }
3329
3330 /**
3331 * Shows a bulletin board style toolbar for common editing functions.
3332 * It can be disabled in the user preferences.
3333 * The necessary JavaScript code can be found in skins/common/edit.js.
3334 *
3335 * @return string
3336 */
3337 static function getEditToolbar() {
3338 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3339 global $wgEnableUploads, $wgForeignFileRepos;
3340
3341 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3342
3343 /**
3344 * $toolarray is an array of arrays each of which includes the
3345 * filename of the button image (without path), the opening
3346 * tag, the closing tag, optionally a sample text that is
3347 * inserted between the two when no selection is highlighted
3348 * and. The tip text is shown when the user moves the mouse
3349 * over the button.
3350 *
3351 * Also here: accesskeys (key), which are not used yet until
3352 * someone can figure out a way to make them work in
3353 * IE. However, we should make sure these keys are not defined
3354 * on the edit page.
3355 */
3356 $toolarray = array(
3357 array(
3358 'image' => $wgLang->getImageFile( 'button-bold' ),
3359 'id' => 'mw-editbutton-bold',
3360 'open' => '\'\'\'',
3361 'close' => '\'\'\'',
3362 'sample' => wfMessage( 'bold_sample' )->text(),
3363 'tip' => wfMessage( 'bold_tip' )->text(),
3364 'key' => 'B'
3365 ),
3366 array(
3367 'image' => $wgLang->getImageFile( 'button-italic' ),
3368 'id' => 'mw-editbutton-italic',
3369 'open' => '\'\'',
3370 'close' => '\'\'',
3371 'sample' => wfMessage( 'italic_sample' )->text(),
3372 'tip' => wfMessage( 'italic_tip' )->text(),
3373 'key' => 'I'
3374 ),
3375 array(
3376 'image' => $wgLang->getImageFile( 'button-link' ),
3377 'id' => 'mw-editbutton-link',
3378 'open' => '[[',
3379 'close' => ']]',
3380 'sample' => wfMessage( 'link_sample' )->text(),
3381 'tip' => wfMessage( 'link_tip' )->text(),
3382 'key' => 'L'
3383 ),
3384 array(
3385 'image' => $wgLang->getImageFile( 'button-extlink' ),
3386 'id' => 'mw-editbutton-extlink',
3387 'open' => '[',
3388 'close' => ']',
3389 'sample' => wfMessage( 'extlink_sample' )->text(),
3390 'tip' => wfMessage( 'extlink_tip' )->text(),
3391 'key' => 'X'
3392 ),
3393 array(
3394 'image' => $wgLang->getImageFile( 'button-headline' ),
3395 'id' => 'mw-editbutton-headline',
3396 'open' => "\n== ",
3397 'close' => " ==\n",
3398 'sample' => wfMessage( 'headline_sample' )->text(),
3399 'tip' => wfMessage( 'headline_tip' )->text(),
3400 'key' => 'H'
3401 ),
3402 $imagesAvailable ? array(
3403 'image' => $wgLang->getImageFile( 'button-image' ),
3404 'id' => 'mw-editbutton-image',
3405 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3406 'close' => ']]',
3407 'sample' => wfMessage( 'image_sample' )->text(),
3408 'tip' => wfMessage( 'image_tip' )->text(),
3409 'key' => 'D',
3410 ) : false,
3411 $imagesAvailable ? array(
3412 'image' => $wgLang->getImageFile( 'button-media' ),
3413 'id' => 'mw-editbutton-media',
3414 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3415 'close' => ']]',
3416 'sample' => wfMessage( 'media_sample' )->text(),
3417 'tip' => wfMessage( 'media_tip' )->text(),
3418 'key' => 'M'
3419 ) : false,
3420 class_exists( 'MathRenderer' ) ? array(
3421 'image' => $wgLang->getImageFile( 'button-math' ),
3422 'id' => 'mw-editbutton-math',
3423 'open' => "<math>",
3424 'close' => "</math>",
3425 'sample' => wfMessage( 'math_sample' )->text(),
3426 'tip' => wfMessage( 'math_tip' )->text(),
3427 'key' => 'C'
3428 ) : false,
3429 array(
3430 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3431 'id' => 'mw-editbutton-nowiki',
3432 'open' => "<nowiki>",
3433 'close' => "</nowiki>",
3434 'sample' => wfMessage( 'nowiki_sample' )->text(),
3435 'tip' => wfMessage( 'nowiki_tip' )->text(),
3436 'key' => 'N'
3437 ),
3438 array(
3439 'image' => $wgLang->getImageFile( 'button-sig' ),
3440 'id' => 'mw-editbutton-signature',
3441 'open' => '--~~~~',
3442 'close' => '',
3443 'sample' => '',
3444 'tip' => wfMessage( 'sig_tip' )->text(),
3445 'key' => 'Y'
3446 ),
3447 array(
3448 'image' => $wgLang->getImageFile( 'button-hr' ),
3449 'id' => 'mw-editbutton-hr',
3450 'open' => "\n----\n",
3451 'close' => '',
3452 'sample' => '',
3453 'tip' => wfMessage( 'hr_tip' )->text(),
3454 'key' => 'R'
3455 )
3456 );
3457
3458 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3459 foreach ( $toolarray as $tool ) {
3460 if ( !$tool ) {
3461 continue;
3462 }
3463
3464 $params = array(
3465 $wgStylePath . '/common/images/' . $tool['image'],
3466 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3467 // Older browsers show a "speedtip" type message only for ALT.
3468 // Ideally these should be different, realistically they
3469 // probably don't need to be.
3470 $tool['tip'],
3471 $tool['open'],
3472 $tool['close'],
3473 $tool['sample'],
3474 $tool['id'],
3475 );
3476
3477 $script .= Xml::encodeJsCall( 'mw.toolbar.addButton', $params );
3478 }
3479
3480 // This used to be called on DOMReady from mediawiki.action.edit, which
3481 // ended up causing race conditions with the setup code above.
3482 $script .= "\n" .
3483 "// Create button bar\n" .
3484 "$(function() { mw.toolbar.init(); } );\n";
3485
3486 $script .= '});';
3487 $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
3488
3489 $toolbar = '<div id="toolbar"></div>';
3490
3491 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3492
3493 return $toolbar;
3494 }
3495
3496 /**
3497 * Returns an array of html code of the following checkboxes:
3498 * minor and watch
3499 *
3500 * @param int $tabindex Current tabindex
3501 * @param array $checked of checkbox => bool, where bool indicates the checked
3502 * status of the checkbox
3503 *
3504 * @return array
3505 */
3506 public function getCheckboxes( &$tabindex, $checked ) {
3507 global $wgUser;
3508
3509 $checkboxes = array();
3510
3511 // don't show the minor edit checkbox if it's a new page or section
3512 if ( !$this->isNew ) {
3513 $checkboxes['minor'] = '';
3514 $minorLabel = wfMessage( 'minoredit' )->parse();
3515 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3516 $attribs = array(
3517 'tabindex' => ++$tabindex,
3518 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3519 'id' => 'wpMinoredit',
3520 );
3521 $checkboxes['minor'] =
3522 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3523 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
3524 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3525 ">{$minorLabel}</label>";
3526 }
3527 }
3528
3529 $watchLabel = wfMessage( 'watchthis' )->parse();
3530 $checkboxes['watch'] = '';
3531 if ( $wgUser->isLoggedIn() ) {
3532 $attribs = array(
3533 'tabindex' => ++$tabindex,
3534 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3535 'id' => 'wpWatchthis',
3536 );
3537 $checkboxes['watch'] =
3538 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3539 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
3540 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
3541 ">{$watchLabel}</label>";
3542 }
3543 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3544 return $checkboxes;
3545 }
3546
3547 /**
3548 * Returns an array of html code of the following buttons:
3549 * save, diff, preview and live
3550 *
3551 * @param int $tabindex Current tabindex
3552 *
3553 * @return array
3554 */
3555 public function getEditButtons( &$tabindex ) {
3556 $buttons = array();
3557
3558 $temp = array(
3559 'id' => 'wpSave',
3560 'name' => 'wpSave',
3561 'type' => 'submit',
3562 'tabindex' => ++$tabindex,
3563 'value' => wfMessage( 'savearticle' )->text(),
3564 'accesskey' => wfMessage( 'accesskey-save' )->text(),
3565 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
3566 );
3567 $buttons['save'] = Xml::element( 'input', $temp, '' );
3568
3569 ++$tabindex; // use the same for preview and live preview
3570 $temp = array(
3571 'id' => 'wpPreview',
3572 'name' => 'wpPreview',
3573 'type' => 'submit',
3574 'tabindex' => $tabindex,
3575 'value' => wfMessage( 'showpreview' )->text(),
3576 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
3577 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
3578 );
3579 $buttons['preview'] = Xml::element( 'input', $temp, '' );
3580 $buttons['live'] = '';
3581
3582 $temp = array(
3583 'id' => 'wpDiff',
3584 'name' => 'wpDiff',
3585 'type' => 'submit',
3586 'tabindex' => ++$tabindex,
3587 'value' => wfMessage( 'showdiff' )->text(),
3588 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
3589 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
3590 );
3591 $buttons['diff'] = Xml::element( 'input', $temp, '' );
3592
3593 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3594 return $buttons;
3595 }
3596
3597 /**
3598 * Output preview text only. This can be sucked into the edit page
3599 * via JavaScript, and saves the server time rendering the skin as
3600 * well as theoretically being more robust on the client (doesn't
3601 * disturb the edit box's undo history, won't eat your text on
3602 * failure, etc).
3603 *
3604 * @todo This doesn't include category or interlanguage links.
3605 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3606 * or something...</s>" that might also require more skin
3607 * initialization, so check whether that's a problem.
3608 */
3609 function livePreview() {
3610 global $wgOut;
3611 $wgOut->disable();
3612 header( 'Content-type: text/xml; charset=utf-8' );
3613 header( 'Cache-control: no-cache' );
3614
3615 $previewText = $this->getPreviewText();
3616 #$categories = $skin->getCategoryLinks();
3617
3618 $s =
3619 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3620 Xml::tags( 'livepreview', null,
3621 Xml::element( 'preview', null, $previewText )
3622 #. Xml::element( 'category', null, $categories )
3623 );
3624 echo $s;
3625 }
3626
3627 /**
3628 * Call the stock "user is blocked" page
3629 *
3630 * @deprecated in 1.19; throw an exception directly instead
3631 */
3632 function blockedPage() {
3633 wfDeprecated( __METHOD__, '1.19' );
3634 global $wgUser;
3635
3636 throw new UserBlockedError( $wgUser->getBlock() );
3637 }
3638
3639 /**
3640 * Produce the stock "please login to edit pages" page
3641 *
3642 * @deprecated in 1.19; throw an exception directly instead
3643 */
3644 function userNotLoggedInPage() {
3645 wfDeprecated( __METHOD__, '1.19' );
3646 throw new PermissionsError( 'edit' );
3647 }
3648
3649 /**
3650 * Show an error page saying to the user that he has insufficient permissions
3651 * to create a new page
3652 *
3653 * @deprecated in 1.19; throw an exception directly instead
3654 */
3655 function noCreatePermission() {
3656 wfDeprecated( __METHOD__, '1.19' );
3657 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
3658 throw new PermissionsError( $permission );
3659 }
3660
3661 /**
3662 * Creates a basic error page which informs the user that
3663 * they have attempted to edit a nonexistent section.
3664 */
3665 function noSuchSectionPage() {
3666 global $wgOut;
3667
3668 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3669
3670 $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
3671 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3672 $wgOut->addHTML( $res );
3673
3674 $wgOut->returnToMain( false, $this->mTitle );
3675 }
3676
3677 /**
3678 * Show "your edit contains spam" page with your diff and text
3679 *
3680 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3681 */
3682 public function spamPageWithContent( $match = false ) {
3683 global $wgOut, $wgLang;
3684 $this->textbox2 = $this->textbox1;
3685
3686 if ( is_array( $match ) ) {
3687 $match = $wgLang->listToText( $match );
3688 }
3689 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3690
3691 $wgOut->addHTML( '<div id="spamprotected">' );
3692 $wgOut->addWikiMsg( 'spamprotectiontext' );
3693 if ( $match ) {
3694 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3695 }
3696 $wgOut->addHTML( '</div>' );
3697
3698 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3699 $this->showDiff();
3700
3701 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3702 $this->showTextbox2();
3703
3704 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3705 }
3706
3707 /**
3708 * Check if the browser is on a blacklist of user-agents known to
3709 * mangle UTF-8 data on form submission. Returns true if Unicode
3710 * should make it through, false if it's known to be a problem.
3711 * @return bool
3712 */
3713 private function checkUnicodeCompliantBrowser() {
3714 global $wgBrowserBlackList, $wgRequest;
3715
3716 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3717 if ( $currentbrowser === false ) {
3718 // No User-Agent header sent? Trust it by default...
3719 return true;
3720 }
3721
3722 foreach ( $wgBrowserBlackList as $browser ) {
3723 if ( preg_match( $browser, $currentbrowser ) ) {
3724 return false;
3725 }
3726 }
3727 return true;
3728 }
3729
3730 /**
3731 * Filter an input field through a Unicode de-armoring process if it
3732 * came from an old browser with known broken Unicode editing issues.
3733 *
3734 * @param WebRequest $request
3735 * @param string $field
3736 * @return string
3737 */
3738 protected function safeUnicodeInput( $request, $field ) {
3739 $text = rtrim( $request->getText( $field ) );
3740 return $request->getBool( 'safemode' )
3741 ? $this->unmakeSafe( $text )
3742 : $text;
3743 }
3744
3745 /**
3746 * Filter an output field through a Unicode armoring process if it is
3747 * going to an old browser with known broken Unicode editing issues.
3748 *
3749 * @param string $text
3750 * @return string
3751 */
3752 protected function safeUnicodeOutput( $text ) {
3753 global $wgContLang;
3754 $codedText = $wgContLang->recodeForEdit( $text );
3755 return $this->checkUnicodeCompliantBrowser()
3756 ? $codedText
3757 : $this->makeSafe( $codedText );
3758 }
3759
3760 /**
3761 * A number of web browsers are known to corrupt non-ASCII characters
3762 * in a UTF-8 text editing environment. To protect against this,
3763 * detected browsers will be served an armored version of the text,
3764 * with non-ASCII chars converted to numeric HTML character references.
3765 *
3766 * Preexisting such character references will have a 0 added to them
3767 * to ensure that round-trips do not alter the original data.
3768 *
3769 * @param string $invalue
3770 * @return string
3771 */
3772 private function makeSafe( $invalue ) {
3773 // Armor existing references for reversibility.
3774 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
3775
3776 $bytesleft = 0;
3777 $result = "";
3778 $working = 0;
3779 for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
3780 $bytevalue = ord( $invalue[$i] );
3781 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3782 $result .= chr( $bytevalue );
3783 $bytesleft = 0;
3784 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3785 $working = $working << 6;
3786 $working += ( $bytevalue & 0x3F );
3787 $bytesleft--;
3788 if ( $bytesleft <= 0 ) {
3789 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3790 }
3791 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3792 $working = $bytevalue & 0x1F;
3793 $bytesleft = 1;
3794 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3795 $working = $bytevalue & 0x0F;
3796 $bytesleft = 2;
3797 } else { // 1111 0xxx
3798 $working = $bytevalue & 0x07;
3799 $bytesleft = 3;
3800 }
3801 }
3802 return $result;
3803 }
3804
3805 /**
3806 * Reverse the previously applied transliteration of non-ASCII characters
3807 * back to UTF-8. Used to protect data from corruption by broken web browsers
3808 * as listed in $wgBrowserBlackList.
3809 *
3810 * @param string $invalue
3811 * @return string
3812 */
3813 private function unmakeSafe( $invalue ) {
3814 $result = "";
3815 $valueLength = strlen( $invalue );
3816 for ( $i = 0; $i < $valueLength; $i++ ) {
3817 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
3818 $i += 3;
3819 $hexstring = "";
3820 do {
3821 $hexstring .= $invalue[$i];
3822 $i++;
3823 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3824
3825 // Do some sanity checks. These aren't needed for reversibility,
3826 // but should help keep the breakage down if the editor
3827 // breaks one of the entities whilst editing.
3828 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3829 $codepoint = hexdec( $hexstring );
3830 $result .= codepointToUtf8( $codepoint );
3831 } else {
3832 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3833 }
3834 } else {
3835 $result .= substr( $invalue, $i, 1 );
3836 }
3837 }
3838 // reverse the transform that we made for reversibility reasons.
3839 return strtr( $result, array( "&#x0" => "&#x" ) );
3840 }
3841 }