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