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