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