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