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