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