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