Remove superfluous spaces and doc tweak
[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 $this->mBaseRevision = Revision::loadFromTimestamp(
1917 $db, $this->mTitle, $this->edittime );
1918 }
1919 return $this->mBaseRevision;
1920 }
1921
1922 /**
1923 * Check given input text against $wgSpamRegex, and return the text of the first match.
1924 *
1925 * @param $text string
1926 *
1927 * @return string|bool matching string or false
1928 */
1929 public static function matchSpamRegex( $text ) {
1930 global $wgSpamRegex;
1931 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1932 $regexes = (array)$wgSpamRegex;
1933 return self::matchSpamRegexInternal( $text, $regexes );
1934 }
1935
1936 /**
1937 * Check given input text against $wgSummarySpamRegex, and return the text of the first match.
1938 *
1939 * @param $text string
1940 *
1941 * @return string|bool matching string or false
1942 */
1943 public static function matchSummarySpamRegex( $text ) {
1944 global $wgSummarySpamRegex;
1945 $regexes = (array)$wgSummarySpamRegex;
1946 return self::matchSpamRegexInternal( $text, $regexes );
1947 }
1948
1949 /**
1950 * @param $text string
1951 * @param $regexes array
1952 * @return bool|string
1953 */
1954 protected static function matchSpamRegexInternal( $text, $regexes ) {
1955 foreach ( $regexes as $regex ) {
1956 $matches = array();
1957 if ( preg_match( $regex, $text, $matches ) ) {
1958 return $matches[0];
1959 }
1960 }
1961 return false;
1962 }
1963
1964 function setHeaders() {
1965 global $wgOut, $wgUser;
1966
1967 $wgOut->addModules( 'mediawiki.action.edit' );
1968 $wgOut->addModuleStyles( 'mediawiki.action.edit.styles' );
1969
1970 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1971 $wgOut->addModules( 'mediawiki.action.edit.preview' );
1972 }
1973
1974 if ( $wgUser->getOption( 'useeditwarning', false ) ) {
1975 $wgOut->addModules( 'mediawiki.action.edit.editWarning' );
1976 }
1977
1978 // Bug #19334: textarea jumps when editing articles in IE8
1979 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1980
1981 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1982
1983 # Enabled article-related sidebar, toplinks, etc.
1984 $wgOut->setArticleRelated( true );
1985
1986 $contextTitle = $this->getContextTitle();
1987 if ( $this->isConflict ) {
1988 $msg = 'editconflict';
1989 } elseif ( $contextTitle->exists() && $this->section != '' ) {
1990 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
1991 } else {
1992 $msg = $contextTitle->exists() || ( $contextTitle->getNamespace() == NS_MEDIAWIKI && $contextTitle->getDefaultMessageText() !== false ) ?
1993 'editing' : 'creating';
1994 }
1995 # Use the title defined by DISPLAYTITLE magic word when present
1996 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
1997 if ( $displayTitle === false ) {
1998 $displayTitle = $contextTitle->getPrefixedText();
1999 }
2000 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
2001 }
2002
2003 /**
2004 * Show all applicable editing introductions
2005 */
2006 protected function showIntro() {
2007 global $wgOut, $wgUser;
2008 if ( $this->suppressIntro ) {
2009 return;
2010 }
2011
2012 $namespace = $this->mTitle->getNamespace();
2013
2014 if ( $namespace == NS_MEDIAWIKI ) {
2015 # Show a warning if editing an interface message
2016 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
2017 } elseif ( $namespace == NS_FILE ) {
2018 # Show a hint to shared repo
2019 $file = wfFindFile( $this->mTitle );
2020 if ( $file && !$file->isLocal() ) {
2021 $descUrl = $file->getDescriptionUrl();
2022 # there must be a description url to show a hint to shared repo
2023 if ( $descUrl ) {
2024 if ( !$this->mTitle->exists() ) {
2025 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array(
2026 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
2027 ) );
2028 } else {
2029 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
2030 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
2031 ) );
2032 }
2033 }
2034 }
2035 }
2036
2037 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
2038 # Show log extract when the user is currently blocked
2039 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
2040 $parts = explode( '/', $this->mTitle->getText(), 2 );
2041 $username = $parts[0];
2042 $user = User::newFromName( $username, false /* allow IP users*/ );
2043 $ip = User::isIP( $username );
2044 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
2045 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
2046 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
2047 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
2048 LogEventsList::showLogExtract(
2049 $wgOut,
2050 'block',
2051 $user->getUserPage(),
2052 '',
2053 array(
2054 'lim' => 1,
2055 'showIfEmpty' => false,
2056 'msgKey' => array(
2057 'blocked-notice-logextract',
2058 $user->getName() # Support GENDER in notice
2059 )
2060 )
2061 );
2062 }
2063 }
2064 # Try to add a custom edit intro, or use the standard one if this is not possible.
2065 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
2066 if ( $wgUser->isLoggedIn() ) {
2067 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
2068 } else {
2069 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
2070 }
2071 }
2072 # Give a notice if the user is editing a deleted/moved page...
2073 if ( !$this->mTitle->exists() ) {
2074 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
2075 '',
2076 array(
2077 'lim' => 10,
2078 'conds' => array( "log_action != 'revision'" ),
2079 'showIfEmpty' => false,
2080 'msgKey' => array( 'recreate-moveddeleted-warn' )
2081 )
2082 );
2083 }
2084 }
2085
2086 /**
2087 * Attempt to show a custom editing introduction, if supplied
2088 *
2089 * @return bool
2090 */
2091 protected function showCustomIntro() {
2092 if ( $this->editintro ) {
2093 $title = Title::newFromText( $this->editintro );
2094 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
2095 global $wgOut;
2096 // Added using template syntax, to take <noinclude>'s into account.
2097 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle );
2098 return true;
2099 }
2100 }
2101 return false;
2102 }
2103
2104 /**
2105 * Gets an editable textual representation of $content.
2106 * The textual representation can be turned by into a Content object by the
2107 * toEditContent() method.
2108 *
2109 * If $content is null or false or a string, $content is returned unchanged.
2110 *
2111 * If the given Content object is not of a type that can be edited using the text base EditPage,
2112 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2113 * content.
2114 *
2115 * @param Content|null|bool|string $content
2116 * @return String the editable text form of the content.
2117 *
2118 * @throws MWException if $content is not an instance of TextContent and $this->allowNonTextContent is not true.
2119 */
2120 protected function toEditText( $content ) {
2121 if ( $content === null || $content === false ) {
2122 return $content;
2123 }
2124
2125 if ( is_string( $content ) ) {
2126 return $content;
2127 }
2128
2129 if ( !$this->allowNonTextContent && !( $content instanceof TextContent ) ) {
2130 throw new MWException( "This content model can not be edited as text: "
2131 . ContentHandler::getLocalizedName( $content->getModel() ) );
2132 }
2133
2134 return $content->serialize( $this->contentFormat );
2135 }
2136
2137 /**
2138 * Turns the given text into a Content object by unserializing it.
2139 *
2140 * If the resulting Content object is not of a type that can be edited using the text base EditPage,
2141 * an exception will be raised. Set $this->allowNonTextContent to true to allow editing of non-textual
2142 * content.
2143 *
2144 * @param string|null|bool $text Text to unserialize
2145 * @return Content The content object created from $text. If $text was false or null, false resp. null will be
2146 * returned instead.
2147 *
2148 * @throws MWException if unserializing the text results in a Content object that is not an instance of TextContent
2149 * and $this->allowNonTextContent is not true.
2150 */
2151 protected function toEditContent( $text ) {
2152 if ( $text === false || $text === null ) {
2153 return $text;
2154 }
2155
2156 $content = ContentHandler::makeContent( $text, $this->getTitle(),
2157 $this->contentModel, $this->contentFormat );
2158
2159 if ( !$this->allowNonTextContent && !( $content instanceof TextContent ) ) {
2160 throw new MWException( "This content model can not be edited as text: "
2161 . ContentHandler::getLocalizedName( $content->getModel() ) );
2162 }
2163
2164 return $content;
2165 }
2166
2167 /**
2168 * Send the edit form and related headers to $wgOut
2169 * @param $formCallback Callback|null that takes an OutputPage parameter; will be called
2170 * during form output near the top, for captchas and the like.
2171 */
2172 function showEditForm( $formCallback = null ) {
2173 global $wgOut, $wgUser;
2174
2175 wfProfileIn( __METHOD__ );
2176
2177 # need to parse the preview early so that we know which templates are used,
2178 # otherwise users with "show preview after edit box" will get a blank list
2179 # we parse this near the beginning so that setHeaders can do the title
2180 # setting work instead of leaving it in getPreviewText
2181 $previewOutput = '';
2182 if ( $this->formtype == 'preview' ) {
2183 $previewOutput = $this->getPreviewText();
2184 }
2185
2186 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
2187
2188 $this->setHeaders();
2189
2190 if ( $this->showHeader() === false ) {
2191 wfProfileOut( __METHOD__ );
2192 return;
2193 }
2194
2195 $wgOut->addHTML( $this->editFormPageTop );
2196
2197 if ( $wgUser->getOption( 'previewontop' ) ) {
2198 $this->displayPreviewArea( $previewOutput, true );
2199 }
2200
2201 $wgOut->addHTML( $this->editFormTextTop );
2202
2203 $showToolbar = true;
2204 if ( $this->wasDeletedSinceLastEdit() ) {
2205 if ( $this->formtype == 'save' ) {
2206 // Hide the toolbar and edit area, user can click preview to get it back
2207 // Add an confirmation checkbox and explanation.
2208 $showToolbar = false;
2209 } else {
2210 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
2211 'deletedwhileediting' );
2212 }
2213 }
2214
2215 // @todo add EditForm plugin interface and use it here!
2216 // search for textarea1 and textares2, and allow EditForm to override all uses.
2217 $wgOut->addHTML( Html::openElement( 'form', array( 'id' => self::EDITFORM_ID, 'name' => self::EDITFORM_ID,
2218 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
2219 'enctype' => 'multipart/form-data' ) ) );
2220
2221 if ( is_callable( $formCallback ) ) {
2222 call_user_func_array( $formCallback, array( &$wgOut ) );
2223 }
2224
2225 // Add an empty field to trip up spambots
2226 $wgOut->addHTML(
2227 Xml::openElement( 'div', array( 'id' => 'antispam-container', 'style' => 'display: none;' ) )
2228 . Html::rawElement( 'label', array( 'for' => 'wpAntiSpam' ), wfMessage( 'simpleantispam-label' )->parse() )
2229 . Xml::element( 'input', array( 'type' => 'text', 'name' => 'wpAntispam', 'id' => 'wpAntispam', 'value' => '' ) )
2230 . Xml::closeElement( 'div' )
2231 );
2232
2233 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
2234
2235 // Put these up at the top to ensure they aren't lost on early form submission
2236 $this->showFormBeforeText();
2237
2238 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
2239 $username = $this->lastDelete->user_name;
2240 $comment = $this->lastDelete->log_comment;
2241
2242 // It is better to not parse the comment at all than to have templates expanded in the middle
2243 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
2244 $key = $comment === ''
2245 ? 'confirmrecreate-noreason'
2246 : 'confirmrecreate';
2247 $wgOut->addHTML(
2248 '<div class="mw-confirm-recreate">' .
2249 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
2250 Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
2251 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
2252 ) .
2253 '</div>'
2254 );
2255 }
2256
2257 # When the summary is hidden, also hide them on preview/show changes
2258 if ( $this->nosummary ) {
2259 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
2260 }
2261
2262 # If a blank edit summary was previously provided, and the appropriate
2263 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
2264 # user being bounced back more than once in the event that a summary
2265 # is not required.
2266 #####
2267 # For a bit more sophisticated detection of blank summaries, hash the
2268 # automatic one and pass that in the hidden field wpAutoSummary.
2269 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
2270 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
2271 }
2272
2273 if ( $this->undidRev ) {
2274 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
2275 }
2276
2277 if ( $this->hasPresetSummary ) {
2278 // If a summary has been preset using &summary= we don't want to prompt for
2279 // a different summary. Only prompt for a summary if the summary is blanked.
2280 // (Bug 17416)
2281 $this->autoSumm = md5( '' );
2282 }
2283
2284 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
2285 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
2286
2287 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
2288
2289 $wgOut->addHTML( Html::hidden( 'format', $this->contentFormat ) );
2290 $wgOut->addHTML( Html::hidden( 'model', $this->contentModel ) );
2291
2292 if ( $this->section == 'new' ) {
2293 $this->showSummaryInput( true, $this->summary );
2294 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
2295 }
2296
2297 $wgOut->addHTML( $this->editFormTextBeforeContent );
2298
2299 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
2300 $wgOut->addHTML( EditPage::getEditToolbar() );
2301 }
2302
2303 if ( $this->isConflict ) {
2304 // In an edit conflict bypass the overridable content form method
2305 // and fallback to the raw wpTextbox1 since editconflicts can't be
2306 // resolved between page source edits and custom ui edits using the
2307 // custom edit ui.
2308 $this->textbox2 = $this->textbox1;
2309
2310 $content = $this->getCurrentContent();
2311 $this->textbox1 = $this->toEditText( $content );
2312
2313 $this->showTextbox1();
2314 } else {
2315 $this->showContentForm();
2316 }
2317
2318 $wgOut->addHTML( $this->editFormTextAfterContent );
2319
2320 $this->showStandardInputs();
2321
2322 $this->showFormAfterText();
2323
2324 $this->showTosSummary();
2325
2326 $this->showEditTools();
2327
2328 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
2329
2330 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
2331 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
2332
2333 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
2334 Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
2335
2336 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'limitreport' ),
2337 self::getPreviewLimitReport( $this->mParserOutput ) ) );
2338
2339 $wgOut->addModules( 'mediawiki.action.edit.collapsibleFooter' );
2340
2341 if ( $this->isConflict ) {
2342 try {
2343 $this->showConflict();
2344 } catch ( MWContentSerializationException $ex ) {
2345 // this can't really happen, but be nice if it does.
2346 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
2347 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2348 }
2349 }
2350
2351 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
2352
2353 if ( !$wgUser->getOption( 'previewontop' ) ) {
2354 $this->displayPreviewArea( $previewOutput, false );
2355 }
2356
2357 wfProfileOut( __METHOD__ );
2358 }
2359
2360 /**
2361 * Extract the section title from current section text, if any.
2362 *
2363 * @param string $text
2364 * @return Mixed|string or false
2365 */
2366 public static function extractSectionTitle( $text ) {
2367 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
2368 if ( !empty( $matches[2] ) ) {
2369 global $wgParser;
2370 return $wgParser->stripSectionName( trim( $matches[2] ) );
2371 } else {
2372 return false;
2373 }
2374 }
2375
2376 protected function showHeader() {
2377 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
2378
2379 if ( $this->mTitle->isTalkPage() ) {
2380 $wgOut->addWikiMsg( 'talkpagetext' );
2381 }
2382
2383 // Add edit notices
2384 $wgOut->addHTML( implode( "\n", $this->mTitle->getEditNotices( $this->oldid ) ) );
2385
2386 if ( $this->isConflict ) {
2387 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
2388 $this->edittime = $this->mArticle->getTimestamp();
2389 } else {
2390 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
2391 // We use $this->section to much before this and getVal('wgSection') directly in other places
2392 // at this point we can't reset $this->section to '' to fallback to non-section editing.
2393 // Someone is welcome to try refactoring though
2394 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
2395 return false;
2396 }
2397
2398 if ( $this->section != '' && $this->section != 'new' ) {
2399 if ( !$this->summary && !$this->preview && !$this->diff ) {
2400 $sectionTitle = self::extractSectionTitle( $this->textbox1 ); //FIXME: use Content object
2401 if ( $sectionTitle !== false ) {
2402 $this->summary = "/* $sectionTitle */ ";
2403 }
2404 }
2405 }
2406
2407 if ( $this->missingComment ) {
2408 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
2409 }
2410
2411 if ( $this->missingSummary && $this->section != 'new' ) {
2412 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
2413 }
2414
2415 if ( $this->missingSummary && $this->section == 'new' ) {
2416 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
2417 }
2418
2419 if ( $this->hookError !== '' ) {
2420 $wgOut->addWikiText( $this->hookError );
2421 }
2422
2423 if ( !$this->checkUnicodeCompliantBrowser() ) {
2424 $wgOut->addWikiMsg( 'nonunicodebrowser' );
2425 }
2426
2427 if ( $this->section != 'new' ) {
2428 $revision = $this->mArticle->getRevisionFetched();
2429 if ( $revision ) {
2430 // Let sysop know that this will make private content public if saved
2431
2432 if ( !$revision->userCan( Revision::DELETED_TEXT, $wgUser ) ) {
2433 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
2434 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
2435 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
2436 }
2437
2438 if ( !$revision->isCurrent() ) {
2439 $this->mArticle->setOldSubtitle( $revision->getId() );
2440 $wgOut->addWikiMsg( 'editingold' );
2441 }
2442 } elseif ( $this->mTitle->exists() ) {
2443 // Something went wrong
2444
2445 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2446 array( 'missing-revision', $this->oldid ) );
2447 }
2448 }
2449 }
2450
2451 if ( wfReadOnly() ) {
2452 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2453 } elseif ( $wgUser->isAnon() ) {
2454 if ( $this->formtype != 'preview' ) {
2455 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2456 } else {
2457 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2458 }
2459 } else {
2460 if ( $this->isCssJsSubpage ) {
2461 # Check the skin exists
2462 if ( $this->isWrongCaseCssJsPage ) {
2463 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
2464 }
2465 if ( $this->formtype !== 'preview' ) {
2466 if ( $this->isCssSubpage ) {
2467 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2468 }
2469
2470 if ( $this->isJsSubpage ) {
2471 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2472 }
2473 }
2474 }
2475 }
2476
2477 if ( $this->mTitle->isProtected( 'edit' ) &&
2478 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2479 ) {
2480 # Is the title semi-protected?
2481 if ( $this->mTitle->isSemiProtected() ) {
2482 $noticeMsg = 'semiprotectedpagewarning';
2483 } else {
2484 # Then it must be protected based on static groups (regular)
2485 $noticeMsg = 'protectedpagewarning';
2486 }
2487 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2488 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2489 }
2490 if ( $this->mTitle->isCascadeProtected() ) {
2491 # Is this page under cascading protection from some source pages?
2492 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2493 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2494 $cascadeSourcesCount = count( $cascadeSources );
2495 if ( $cascadeSourcesCount > 0 ) {
2496 # Explain, and list the titles responsible
2497 foreach ( $cascadeSources as $page ) {
2498 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2499 }
2500 }
2501 $notice .= '</div>';
2502 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2503 }
2504 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2505 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2506 array( 'lim' => 1,
2507 'showIfEmpty' => false,
2508 'msgKey' => array( 'titleprotectedwarning' ),
2509 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2510 }
2511
2512 if ( $this->kblength === false ) {
2513 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2514 }
2515
2516 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2517 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2518 array( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2519 } else {
2520 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2521 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2522 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 ) )
2523 );
2524 }
2525 }
2526 # Add header copyright warning
2527 $this->showHeaderCopyrightWarning();
2528 }
2529
2530 /**
2531 * Standard summary input and label (wgSummary), abstracted so EditPage
2532 * subclasses may reorganize the form.
2533 * Note that you do not need to worry about the label's for=, it will be
2534 * inferred by the id given to the input. You can remove them both by
2535 * passing array( 'id' => false ) to $userInputAttrs.
2536 *
2537 * @param string $summary The value of the summary input
2538 * @param string $labelText The html to place inside the label
2539 * @param array $inputAttrs of attrs to use on the input
2540 * @param array $spanLabelAttrs of attrs to use on the span inside the label
2541 *
2542 * @return array An array in the format array( $label, $input )
2543 */
2544 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2545 // Note: the maxlength is overridden in JS to 255 and to make it use UTF-8 bytes, not characters.
2546 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2547 'id' => 'wpSummary',
2548 'maxlength' => '200',
2549 'tabindex' => '1',
2550 'size' => 60,
2551 'spellcheck' => 'true',
2552 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2553
2554 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2555 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2556 'id' => "wpSummaryLabel"
2557 );
2558
2559 $label = null;
2560 if ( $labelText ) {
2561 $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2562 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2563 }
2564
2565 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2566
2567 return array( $label, $input );
2568 }
2569
2570 /**
2571 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2572 * up top, or false if this is the comment summary
2573 * down below the textarea
2574 * @param string $summary The text of the summary to display
2575 * @return String
2576 */
2577 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2578 global $wgOut, $wgContLang;
2579 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2580 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2581 if ( $isSubjectPreview ) {
2582 if ( $this->nosummary ) {
2583 return;
2584 }
2585 } else {
2586 if ( !$this->mShowSummaryField ) {
2587 return;
2588 }
2589 }
2590 $summary = $wgContLang->recodeForEdit( $summary );
2591 $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
2592 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2593 $wgOut->addHTML( "{$label} {$input}" );
2594 }
2595
2596 /**
2597 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2598 * up top, or false if this is the comment summary
2599 * down below the textarea
2600 * @param string $summary the text of the summary to display
2601 * @return String
2602 */
2603 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2604 // avoid spaces in preview, gets always trimmed on save
2605 $summary = trim( $summary );
2606 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
2607 return "";
2608 }
2609
2610 global $wgParser;
2611
2612 if ( $isSubjectPreview ) {
2613 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
2614 ->inContentLanguage()->text();
2615 }
2616
2617 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
2618
2619 $summary = wfMessage( $message )->parse() . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
2620 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2621 }
2622
2623 protected function showFormBeforeText() {
2624 global $wgOut;
2625 $section = htmlspecialchars( $this->section );
2626 $wgOut->addHTML( <<<HTML
2627 <input type='hidden' value="{$section}" name="wpSection" />
2628 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2629 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2630 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2631
2632 HTML
2633 );
2634 if ( !$this->checkUnicodeCompliantBrowser() ) {
2635 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
2636 }
2637 }
2638
2639 protected function showFormAfterText() {
2640 global $wgOut, $wgUser;
2641 /**
2642 * To make it harder for someone to slip a user a page
2643 * which submits an edit form to the wiki without their
2644 * knowledge, a random token is associated with the login
2645 * session. If it's not passed back with the submission,
2646 * we won't save the page, or render user JavaScript and
2647 * CSS previews.
2648 *
2649 * For anon editors, who may not have a session, we just
2650 * include the constant suffix to prevent editing from
2651 * broken text-mangling proxies.
2652 */
2653 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2654 }
2655
2656 /**
2657 * Subpage overridable method for printing the form for page content editing
2658 * By default this simply outputs wpTextbox1
2659 * Subclasses can override this to provide a custom UI for editing;
2660 * be it a form, or simply wpTextbox1 with a modified content that will be
2661 * reverse modified when extracted from the post data.
2662 * Note that this is basically the inverse for importContentFormData
2663 */
2664 protected function showContentForm() {
2665 $this->showTextbox1();
2666 }
2667
2668 /**
2669 * Method to output wpTextbox1
2670 * The $textoverride method can be used by subclasses overriding showContentForm
2671 * to pass back to this method.
2672 *
2673 * @param array $customAttribs of html attributes to use in the textarea
2674 * @param string $textoverride optional text to override $this->textarea1 with
2675 */
2676 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2677 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2678 $attribs = array( 'style' => 'display:none;' );
2679 } else {
2680 $classes = array(); // Textarea CSS
2681 if ( $this->mTitle->isProtected( 'edit' ) &&
2682 MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) !== array( '' )
2683 ) {
2684 # Is the title semi-protected?
2685 if ( $this->mTitle->isSemiProtected() ) {
2686 $classes[] = 'mw-textarea-sprotected';
2687 } else {
2688 # Then it must be protected based on static groups (regular)
2689 $classes[] = 'mw-textarea-protected';
2690 }
2691 # Is the title cascade-protected?
2692 if ( $this->mTitle->isCascadeProtected() ) {
2693 $classes[] = 'mw-textarea-cprotected';
2694 }
2695 }
2696
2697 $attribs = array( 'tabindex' => 1 );
2698
2699 if ( is_array( $customAttribs ) ) {
2700 $attribs += $customAttribs;
2701 }
2702
2703 if ( count( $classes ) ) {
2704 if ( isset( $attribs['class'] ) ) {
2705 $classes[] = $attribs['class'];
2706 }
2707 $attribs['class'] = implode( ' ', $classes );
2708 }
2709 }
2710
2711 $this->showTextbox( $textoverride !== null ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
2712 }
2713
2714 protected function showTextbox2() {
2715 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2716 }
2717
2718 protected function showTextbox( $text, $name, $customAttribs = array() ) {
2719 global $wgOut, $wgUser;
2720
2721 $wikitext = $this->safeUnicodeOutput( $text );
2722 if ( strval( $wikitext ) !== '' ) {
2723 // Ensure there's a newline at the end, otherwise adding lines
2724 // is awkward.
2725 // But don't add a newline if the ext is empty, or Firefox in XHTML
2726 // mode will show an extra newline. A bit annoying.
2727 $wikitext .= "\n";
2728 }
2729
2730 $attribs = $customAttribs + array(
2731 'accesskey' => ',',
2732 'id' => $name,
2733 'cols' => $wgUser->getIntOption( 'cols' ),
2734 'rows' => $wgUser->getIntOption( 'rows' ),
2735 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2736 );
2737
2738 $pageLang = $this->mTitle->getPageLanguage();
2739 $attribs['lang'] = $pageLang->getCode();
2740 $attribs['dir'] = $pageLang->getDir();
2741
2742 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
2743 }
2744
2745 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2746 global $wgOut;
2747 $classes = array();
2748 if ( $isOnTop ) {
2749 $classes[] = 'ontop';
2750 }
2751
2752 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2753
2754 if ( $this->formtype != 'preview' ) {
2755 $attribs['style'] = 'display: none;';
2756 }
2757
2758 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
2759
2760 if ( $this->formtype == 'preview' ) {
2761 $this->showPreview( $previewOutput );
2762 }
2763
2764 $wgOut->addHTML( '</div>' );
2765
2766 if ( $this->formtype == 'diff' ) {
2767 try {
2768 $this->showDiff();
2769 } catch ( MWContentSerializationException $ex ) {
2770 $msg = wfMessage( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
2771 $wgOut->addWikiText( '<div class="error">' . $msg->text() . '</div>' );
2772 }
2773 }
2774 }
2775
2776 /**
2777 * Append preview output to $wgOut.
2778 * Includes category rendering if this is a category page.
2779 *
2780 * @param string $text the HTML to be output for the preview.
2781 */
2782 protected function showPreview( $text ) {
2783 global $wgOut;
2784 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2785 $this->mArticle->openShowCategory();
2786 }
2787 # This hook seems slightly odd here, but makes things more
2788 # consistent for extensions.
2789 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2790 $wgOut->addHTML( $text );
2791 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2792 $this->mArticle->closeShowCategory();
2793 }
2794 }
2795
2796 /**
2797 * Get a diff between the current contents of the edit box and the
2798 * version of the page we're editing from.
2799 *
2800 * If this is a section edit, we'll replace the section as for final
2801 * save and then make a comparison.
2802 */
2803 function showDiff() {
2804 global $wgUser, $wgContLang, $wgOut;
2805
2806 $oldtitlemsg = 'currentrev';
2807 # if message does not exist, show diff against the preloaded default
2808 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
2809 $oldtext = $this->mTitle->getDefaultMessageText();
2810 if ( $oldtext !== false ) {
2811 $oldtitlemsg = 'defaultmessagetext';
2812 $oldContent = $this->toEditContent( $oldtext );
2813 } else {
2814 $oldContent = null;
2815 }
2816 } else {
2817 $oldContent = $this->getCurrentContent();
2818 }
2819
2820 $textboxContent = $this->toEditContent( $this->textbox1 );
2821
2822 $newContent = $this->mArticle->replaceSectionContent(
2823 $this->section, $textboxContent,
2824 $this->summary, $this->edittime );
2825
2826 if ( $newContent ) {
2827 ContentHandler::runLegacyHooks( 'EditPageGetDiffText', array( $this, &$newContent ) );
2828 wfRunHooks( 'EditPageGetDiffContent', array( $this, &$newContent ) );
2829
2830 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
2831 $newContent = $newContent->preSaveTransform( $this->mTitle, $wgUser, $popts );
2832 }
2833
2834 if ( ( $oldContent && !$oldContent->isEmpty() ) || ( $newContent && !$newContent->isEmpty() ) ) {
2835 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2836 $newtitle = wfMessage( 'yourtext' )->parse();
2837
2838 if ( !$oldContent ) {
2839 $oldContent = $newContent->getContentHandler()->makeEmptyContent();
2840 }
2841
2842 if ( !$newContent ) {
2843 $newContent = $oldContent->getContentHandler()->makeEmptyContent();
2844 }
2845
2846 $de = $oldContent->getContentHandler()->createDifferenceEngine( $this->mArticle->getContext() );
2847 $de->setContent( $oldContent, $newContent );
2848
2849 $difftext = $de->getDiff( $oldtitle, $newtitle );
2850 $de->showDiffStyle();
2851 } else {
2852 $difftext = '';
2853 }
2854
2855 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2856 }
2857
2858 /**
2859 * Show the header copyright warning.
2860 */
2861 protected function showHeaderCopyrightWarning() {
2862 $msg = 'editpage-head-copy-warn';
2863 if ( !wfMessage( $msg )->isDisabled() ) {
2864 global $wgOut;
2865 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2866 'editpage-head-copy-warn' );
2867 }
2868 }
2869
2870 /**
2871 * Give a chance for site and per-namespace customizations of
2872 * terms of service summary link that might exist separately
2873 * from the copyright notice.
2874 *
2875 * This will display between the save button and the edit tools,
2876 * so should remain short!
2877 */
2878 protected function showTosSummary() {
2879 $msg = 'editpage-tos-summary';
2880 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
2881 if ( !wfMessage( $msg )->isDisabled() ) {
2882 global $wgOut;
2883 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2884 $wgOut->addWikiMsg( $msg );
2885 $wgOut->addHTML( '</div>' );
2886 }
2887 }
2888
2889 protected function showEditTools() {
2890 global $wgOut;
2891 $wgOut->addHTML( '<div class="mw-editTools">' .
2892 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2893 '</div>' );
2894 }
2895
2896 /**
2897 * Get the copyright warning
2898 *
2899 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2900 */
2901 protected function getCopywarn() {
2902 return self::getCopyrightWarning( $this->mTitle );
2903 }
2904
2905 /**
2906 * Get the copyright warning, by default returns wikitext
2907 *
2908 * @param Title $title
2909 * @param string $format output format, valid values are any function of
2910 * a Message object
2911 * @return string
2912 */
2913 public static function getCopyrightWarning( $title, $format = 'plain' ) {
2914 global $wgRightsText;
2915 if ( $wgRightsText ) {
2916 $copywarnMsg = array( 'copyrightwarning',
2917 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2918 $wgRightsText );
2919 } else {
2920 $copywarnMsg = array( 'copyrightwarning2',
2921 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2922 }
2923 // Allow for site and per-namespace customization of contribution/copyright notice.
2924 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2925
2926 return "<div id=\"editpage-copywarn\">\n" .
2927 call_user_func_array( 'wfMessage', $copywarnMsg )->$format() . "\n</div>";
2928 }
2929
2930 /**
2931 * Get the Limit report for page previews
2932 *
2933 * @since 1.22
2934 * @param ParserOutput $output ParserOutput object from the parse
2935 * @return string HTML
2936 */
2937 public static function getPreviewLimitReport( $output ) {
2938 if ( !$output || !$output->getLimitReportData() ) {
2939 return '';
2940 }
2941
2942 wfProfileIn( __METHOD__ );
2943
2944 $limitReport = Html::rawElement( 'div', array( 'class' => 'mw-limitReportExplanation' ),
2945 wfMessage( 'limitreport-title' )->parseAsBlock()
2946 );
2947
2948 // Show/hide animation doesn't work correctly on a table, so wrap it in a div.
2949 $limitReport .= Html::openElement( 'div', array( 'class' => 'preview-limit-report-wrapper' ) );
2950
2951 $limitReport .= Html::openElement( 'table', array(
2952 'class' => 'preview-limit-report wikitable'
2953 ) ) .
2954 Html::openElement( 'tbody' );
2955
2956 foreach ( $output->getLimitReportData() as $key => $value ) {
2957 if ( wfRunHooks( 'ParserLimitReportFormat',
2958 array( $key, &$value, &$limitReport, true, true )
2959 ) ) {
2960 $keyMsg = wfMessage( $key );
2961 $valueMsg = wfMessage( array( "$key-value-html", "$key-value" ) );
2962 if ( !$valueMsg->exists() ) {
2963 $valueMsg = new RawMessage( '$1' );
2964 }
2965 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
2966 $limitReport .= Html::openElement( 'tr' ) .
2967 Html::rawElement( 'th', null, $keyMsg->parse() ) .
2968 Html::rawElement( 'td', null, $valueMsg->params( $value )->parse() ) .
2969 Html::closeElement( 'tr' );
2970 }
2971 }
2972 }
2973
2974 $limitReport .= Html::closeElement( 'tbody' ) .
2975 Html::closeElement( 'table' ) .
2976 Html::closeElement( 'div' );
2977
2978 wfProfileOut( __METHOD__ );
2979
2980 return $limitReport;
2981 }
2982
2983 protected function showStandardInputs( &$tabindex = 2 ) {
2984 global $wgOut;
2985 $wgOut->addHTML( "<div class='editOptions'>\n" );
2986
2987 if ( $this->section != 'new' ) {
2988 $this->showSummaryInput( false, $this->summary );
2989 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
2990 }
2991
2992 $checkboxes = $this->getCheckboxes( $tabindex,
2993 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
2994 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2995
2996 // Show copyright warning.
2997 $wgOut->addWikiText( $this->getCopywarn() );
2998 $wgOut->addHTML( $this->editFormTextAfterWarn );
2999
3000 $wgOut->addHTML( "<div class='editButtons'>\n" );
3001 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
3002
3003 $cancel = $this->getCancelLink();
3004 if ( $cancel !== '' ) {
3005 $cancel .= Html::element( 'span',
3006 array( 'class' => 'mw-editButtons-pipe-separator' ),
3007 wfMessage( 'pipe-separator' )->text() );
3008 }
3009 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
3010 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
3011 wfMessage( 'edithelp' )->escaped() . '</a> ' .
3012 wfMessage( 'newwindow' )->parse();
3013 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
3014 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
3015 $wgOut->addHTML( "</div><!-- editButtons -->\n" );
3016 wfRunHooks( 'EditPage::showStandardInputs:options', array( $this, $wgOut, &$tabindex ) );
3017 $wgOut->addHTML( "</div><!-- editOptions -->\n" );
3018 }
3019
3020 /**
3021 * Show an edit conflict. textbox1 is already shown in showEditForm().
3022 * If you want to use another entry point to this function, be careful.
3023 */
3024 protected function showConflict() {
3025 global $wgOut;
3026
3027 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
3028 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3029
3030 $content1 = $this->toEditContent( $this->textbox1 );
3031 $content2 = $this->toEditContent( $this->textbox2 );
3032
3033 $handler = ContentHandler::getForModelID( $this->contentModel );
3034 $de = $handler->createDifferenceEngine( $this->mArticle->getContext() );
3035 $de->setContent( $content2, $content1 );
3036 $de->showDiff(
3037 wfMessage( 'yourtext' )->parse(),
3038 wfMessage( 'storedversion' )->text()
3039 );
3040
3041 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3042 $this->showTextbox2();
3043 }
3044 }
3045
3046 /**
3047 * @return string
3048 */
3049 public function getCancelLink() {
3050 $cancelParams = array();
3051 if ( !$this->isConflict && $this->oldid > 0 ) {
3052 $cancelParams['oldid'] = $this->oldid;
3053 }
3054
3055 return Linker::linkKnown(
3056 $this->getContextTitle(),
3057 wfMessage( 'cancel' )->parse(),
3058 array( 'id' => 'mw-editform-cancel' ),
3059 $cancelParams
3060 );
3061 }
3062
3063 /**
3064 * Returns the URL to use in the form's action attribute.
3065 * This is used by EditPage subclasses when simply customizing the action
3066 * variable in the constructor is not enough. This can be used when the
3067 * EditPage lives inside of a Special page rather than a custom page action.
3068 *
3069 * @param $title Title object for which is being edited (where we go to for &action= links)
3070 * @return string
3071 */
3072 protected function getActionURL( Title $title ) {
3073 return $title->getLocalURL( array( 'action' => $this->action ) );
3074 }
3075
3076 /**
3077 * Check if a page was deleted while the user was editing it, before submit.
3078 * Note that we rely on the logging table, which hasn't been always there,
3079 * but that doesn't matter, because this only applies to brand new
3080 * deletes.
3081 */
3082 protected function wasDeletedSinceLastEdit() {
3083 if ( $this->deletedSinceEdit !== null ) {
3084 return $this->deletedSinceEdit;
3085 }
3086
3087 $this->deletedSinceEdit = false;
3088
3089 if ( $this->mTitle->isDeletedQuick() ) {
3090 $this->lastDelete = $this->getLastDelete();
3091 if ( $this->lastDelete ) {
3092 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
3093 if ( $deleteTime > $this->starttime ) {
3094 $this->deletedSinceEdit = true;
3095 }
3096 }
3097 }
3098
3099 return $this->deletedSinceEdit;
3100 }
3101
3102 protected function getLastDelete() {
3103 $dbr = wfGetDB( DB_SLAVE );
3104 $data = $dbr->selectRow(
3105 array( 'logging', 'user' ),
3106 array(
3107 'log_type',
3108 'log_action',
3109 'log_timestamp',
3110 'log_user',
3111 'log_namespace',
3112 'log_title',
3113 'log_comment',
3114 'log_params',
3115 'log_deleted',
3116 'user_name'
3117 ), array(
3118 'log_namespace' => $this->mTitle->getNamespace(),
3119 'log_title' => $this->mTitle->getDBkey(),
3120 'log_type' => 'delete',
3121 'log_action' => 'delete',
3122 'user_id=log_user'
3123 ),
3124 __METHOD__,
3125 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
3126 );
3127 // Quick paranoid permission checks...
3128 if ( is_object( $data ) ) {
3129 if ( $data->log_deleted & LogPage::DELETED_USER ) {
3130 $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
3131 }
3132
3133 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
3134 $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
3135 }
3136 }
3137 return $data;
3138 }
3139
3140 /**
3141 * Get the rendered text for previewing.
3142 * @throws MWException
3143 * @return string
3144 */
3145 function getPreviewText() {
3146 global $wgOut, $wgUser, $wgRawHtml, $wgLang;
3147
3148 wfProfileIn( __METHOD__ );
3149
3150 if ( $wgRawHtml && !$this->mTokenOk ) {
3151 // Could be an offsite preview attempt. This is very unsafe if
3152 // HTML is enabled, as it could be an attack.
3153 $parsedNote = '';
3154 if ( $this->textbox1 !== '' ) {
3155 // Do not put big scary notice, if previewing the empty
3156 // string, which happens when you initially edit
3157 // a category page, due to automatic preview-on-open.
3158 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
3159 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
3160 }
3161 wfProfileOut( __METHOD__ );
3162 return $parsedNote;
3163 }
3164
3165 $note = '';
3166
3167 try {
3168 $content = $this->toEditContent( $this->textbox1 );
3169
3170 $previewHTML = '';
3171 if ( !wfRunHooks( 'AlternateEditPreview', array( $this, &$content, &$previewHTML, &$this->mParserOutput ) ) ) {
3172 wfProfileOut( __METHOD__ );
3173 return $previewHTML;
3174 }
3175
3176 # provide a anchor link to the editform
3177 $continueEditing = '<span class="mw-continue-editing">' .
3178 '[[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' .
3179 wfMessage( 'continue-editing' )->text() . ']]</span>';
3180 if ( $this->mTriedSave && !$this->mTokenOk ) {
3181 if ( $this->mTokenOkExceptSuffix ) {
3182 $note = wfMessage( 'token_suffix_mismatch' )->plain();
3183
3184 } else {
3185 $note = wfMessage( 'session_fail_preview' )->plain();
3186 }
3187 } elseif ( $this->incompleteForm ) {
3188 $note = wfMessage( 'edit_form_incomplete' )->plain();
3189 } else {
3190 $note = wfMessage( 'previewnote' )->plain() . ' ' . $continueEditing;
3191 }
3192
3193 $parserOptions = $this->mArticle->makeParserOptions( $this->mArticle->getContext() );
3194 $parserOptions->setEditSection( false );
3195 $parserOptions->setIsPreview( true );
3196 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
3197
3198 # don't parse non-wikitext pages, show message about preview
3199 if ( $this->mTitle->isCssJsSubpage() || $this->mTitle->isCssOrJsPage() ) {
3200 if ( $this->mTitle->isCssJsSubpage() ) {
3201 $level = 'user';
3202 } elseif ( $this->mTitle->isCssOrJsPage() ) {
3203 $level = 'site';
3204 } else {
3205 $level = false;
3206 }
3207
3208 if ( $content->getModel() == CONTENT_MODEL_CSS ) {
3209 $format = 'css';
3210 } elseif ( $content->getModel() == CONTENT_MODEL_JAVASCRIPT ) {
3211 $format = 'js';
3212 } else {
3213 $format = false;
3214 }
3215
3216 # Used messages to make sure grep find them:
3217 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
3218 if ( $level && $format ) {
3219 $note = "<div id='mw-{$level}{$format}preview'>" .
3220 wfMessage( "{$level}{$format}preview" )->text() .
3221 ' ' . $continueEditing . "</div>";
3222 }
3223 }
3224
3225 $rt = $content->getRedirectChain();
3226 if ( $rt ) {
3227 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
3228 } else {
3229
3230 # If we're adding a comment, we need to show the
3231 # summary as the headline
3232 if ( $this->section === "new" && $this->summary !== "" ) {
3233 $content = $content->addSectionHeader( $this->summary );
3234 }
3235
3236 $hook_args = array( $this, &$content );
3237 ContentHandler::runLegacyHooks( 'EditPageGetPreviewText', $hook_args );
3238 wfRunHooks( 'EditPageGetPreviewContent', $hook_args );
3239
3240 $parserOptions->enableLimitReport();
3241
3242 # For CSS/JS pages, we should have called the ShowRawCssJs hook here.
3243 # But it's now deprecated, so never mind
3244
3245 $content = $content->preSaveTransform( $this->mTitle, $wgUser, $parserOptions );
3246 $parserOutput = $content->getParserOutput( $this->getArticle()->getTitle(), null, $parserOptions );
3247
3248 $previewHTML = $parserOutput->getText();
3249 $this->mParserOutput = $parserOutput;
3250 $wgOut->addParserOutputNoText( $parserOutput );
3251
3252 if ( count( $parserOutput->getWarnings() ) ) {
3253 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
3254 }
3255 }
3256 } catch ( MWContentSerializationException $ex ) {
3257 $m = wfMessage( 'content-failed-to-parse', $this->contentModel, $this->contentFormat, $ex->getMessage() );
3258 $note .= "\n\n" . $m->parse();
3259 $previewHTML = '';
3260 }
3261
3262 if ( $this->isConflict ) {
3263 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
3264 } else {
3265 $conflict = '<hr />';
3266 }
3267
3268 $previewhead = "<div class='previewnote'>\n" .
3269 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
3270 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
3271
3272 $pageViewLang = $this->mTitle->getPageViewLanguage();
3273 $attribs = array( 'lang' => $pageViewLang->getHtmlCode(), 'dir' => $pageViewLang->getDir(),
3274 'class' => 'mw-content-' . $pageViewLang->getDir() );
3275 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
3276
3277 wfProfileOut( __METHOD__ );
3278 return $previewhead . $previewHTML . $this->previewTextAfterContent;
3279 }
3280
3281 /**
3282 * @return Array
3283 */
3284 function getTemplates() {
3285 if ( $this->preview || $this->section != '' ) {
3286 $templates = array();
3287 if ( !isset( $this->mParserOutput ) ) {
3288 return $templates;
3289 }
3290 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
3291 foreach ( array_keys( $template ) as $dbk ) {
3292 $templates[] = Title::makeTitle( $ns, $dbk );
3293 }
3294 }
3295 return $templates;
3296 } else {
3297 return $this->mTitle->getTemplateLinksFrom();
3298 }
3299 }
3300
3301 /**
3302 * Shows a bulletin board style toolbar for common editing functions.
3303 * It can be disabled in the user preferences.
3304 * The necessary JavaScript code can be found in skins/common/edit.js.
3305 *
3306 * @return string
3307 */
3308 static function getEditToolbar() {
3309 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
3310 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
3311
3312 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
3313
3314 /**
3315 * $toolarray is an array of arrays each of which includes the
3316 * filename of the button image (without path), the opening
3317 * tag, the closing tag, optionally a sample text that is
3318 * inserted between the two when no selection is highlighted
3319 * and. The tip text is shown when the user moves the mouse
3320 * over the button.
3321 *
3322 * Also here: accesskeys (key), which are not used yet until
3323 * someone can figure out a way to make them work in
3324 * IE. However, we should make sure these keys are not defined
3325 * on the edit page.
3326 */
3327 $toolarray = array(
3328 array(
3329 'image' => $wgLang->getImageFile( 'button-bold' ),
3330 'id' => 'mw-editbutton-bold',
3331 'open' => '\'\'\'',
3332 'close' => '\'\'\'',
3333 'sample' => wfMessage( 'bold_sample' )->text(),
3334 'tip' => wfMessage( 'bold_tip' )->text(),
3335 'key' => 'B'
3336 ),
3337 array(
3338 'image' => $wgLang->getImageFile( 'button-italic' ),
3339 'id' => 'mw-editbutton-italic',
3340 'open' => '\'\'',
3341 'close' => '\'\'',
3342 'sample' => wfMessage( 'italic_sample' )->text(),
3343 'tip' => wfMessage( 'italic_tip' )->text(),
3344 'key' => 'I'
3345 ),
3346 array(
3347 'image' => $wgLang->getImageFile( 'button-link' ),
3348 'id' => 'mw-editbutton-link',
3349 'open' => '[[',
3350 'close' => ']]',
3351 'sample' => wfMessage( 'link_sample' )->text(),
3352 'tip' => wfMessage( 'link_tip' )->text(),
3353 'key' => 'L'
3354 ),
3355 array(
3356 'image' => $wgLang->getImageFile( 'button-extlink' ),
3357 'id' => 'mw-editbutton-extlink',
3358 'open' => '[',
3359 'close' => ']',
3360 'sample' => wfMessage( 'extlink_sample' )->text(),
3361 'tip' => wfMessage( 'extlink_tip' )->text(),
3362 'key' => 'X'
3363 ),
3364 array(
3365 'image' => $wgLang->getImageFile( 'button-headline' ),
3366 'id' => 'mw-editbutton-headline',
3367 'open' => "\n== ",
3368 'close' => " ==\n",
3369 'sample' => wfMessage( 'headline_sample' )->text(),
3370 'tip' => wfMessage( 'headline_tip' )->text(),
3371 'key' => 'H'
3372 ),
3373 $imagesAvailable ? array(
3374 'image' => $wgLang->getImageFile( 'button-image' ),
3375 'id' => 'mw-editbutton-image',
3376 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
3377 'close' => ']]',
3378 'sample' => wfMessage( 'image_sample' )->text(),
3379 'tip' => wfMessage( 'image_tip' )->text(),
3380 'key' => 'D',
3381 ) : false,
3382 $imagesAvailable ? array(
3383 'image' => $wgLang->getImageFile( 'button-media' ),
3384 'id' => 'mw-editbutton-media',
3385 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
3386 'close' => ']]',
3387 'sample' => wfMessage( 'media_sample' )->text(),
3388 'tip' => wfMessage( 'media_tip' )->text(),
3389 'key' => 'M'
3390 ) : false,
3391 $wgUseTeX ? array(
3392 'image' => $wgLang->getImageFile( 'button-math' ),
3393 'id' => 'mw-editbutton-math',
3394 'open' => "<math>",
3395 'close' => "</math>",
3396 'sample' => wfMessage( 'math_sample' )->text(),
3397 'tip' => wfMessage( 'math_tip' )->text(),
3398 'key' => 'C'
3399 ) : false,
3400 array(
3401 'image' => $wgLang->getImageFile( 'button-nowiki' ),
3402 'id' => 'mw-editbutton-nowiki',
3403 'open' => "<nowiki>",
3404 'close' => "</nowiki>",
3405 'sample' => wfMessage( 'nowiki_sample' )->text(),
3406 'tip' => wfMessage( 'nowiki_tip' )->text(),
3407 'key' => 'N'
3408 ),
3409 array(
3410 'image' => $wgLang->getImageFile( 'button-sig' ),
3411 'id' => 'mw-editbutton-signature',
3412 'open' => '--~~~~',
3413 'close' => '',
3414 'sample' => '',
3415 'tip' => wfMessage( 'sig_tip' )->text(),
3416 'key' => 'Y'
3417 ),
3418 array(
3419 'image' => $wgLang->getImageFile( 'button-hr' ),
3420 'id' => 'mw-editbutton-hr',
3421 'open' => "\n----\n",
3422 'close' => '',
3423 'sample' => '',
3424 'tip' => wfMessage( 'hr_tip' )->text(),
3425 'key' => 'R'
3426 )
3427 );
3428
3429 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
3430 foreach ( $toolarray as $tool ) {
3431 if ( !$tool ) {
3432 continue;
3433 }
3434
3435 $params = array(
3436 $image = $wgStylePath . '/common/images/' . $tool['image'],
3437 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
3438 // Older browsers show a "speedtip" type message only for ALT.
3439 // Ideally these should be different, realistically they
3440 // probably don't need to be.
3441 $tip = $tool['tip'],
3442 $open = $tool['open'],
3443 $close = $tool['close'],
3444 $sample = $tool['sample'],
3445 $cssId = $tool['id'],
3446 );
3447
3448 $script .= Xml::encodeJsCall( 'mw.toolbar.addButton', $params );
3449 }
3450
3451 // This used to be called on DOMReady from mediawiki.action.edit, which
3452 // ended up causing race conditions with the setup code above.
3453 $script .= "\n" .
3454 "// Create button bar\n" .
3455 "$(function() { mw.toolbar.init(); } );\n";
3456
3457 $script .= '});';
3458 $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
3459
3460 $toolbar = '<div id="toolbar"></div>';
3461
3462 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
3463
3464 return $toolbar;
3465 }
3466
3467 /**
3468 * Returns an array of html code of the following checkboxes:
3469 * minor and watch
3470 *
3471 * @param int $tabindex Current tabindex
3472 * @param array $checked of checkbox => bool, where bool indicates the checked
3473 * status of the checkbox
3474 *
3475 * @return array
3476 */
3477 public function getCheckboxes( &$tabindex, $checked ) {
3478 global $wgUser;
3479
3480 $checkboxes = array();
3481
3482 // don't show the minor edit checkbox if it's a new page or section
3483 if ( !$this->isNew ) {
3484 $checkboxes['minor'] = '';
3485 $minorLabel = wfMessage( 'minoredit' )->parse();
3486 if ( $wgUser->isAllowed( 'minoredit' ) ) {
3487 $attribs = array(
3488 'tabindex' => ++$tabindex,
3489 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
3490 'id' => 'wpMinoredit',
3491 );
3492 $checkboxes['minor'] =
3493 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
3494 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
3495 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
3496 ">{$minorLabel}</label>";
3497 }
3498 }
3499
3500 $watchLabel = wfMessage( 'watchthis' )->parse();
3501 $checkboxes['watch'] = '';
3502 if ( $wgUser->isLoggedIn() ) {
3503 $attribs = array(
3504 'tabindex' => ++$tabindex,
3505 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
3506 'id' => 'wpWatchthis',
3507 );
3508 $checkboxes['watch'] =
3509 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
3510 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
3511 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
3512 ">{$watchLabel}</label>";
3513 }
3514 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
3515 return $checkboxes;
3516 }
3517
3518 /**
3519 * Returns an array of html code of the following buttons:
3520 * save, diff, preview and live
3521 *
3522 * @param int $tabindex Current tabindex
3523 *
3524 * @return array
3525 */
3526 public function getEditButtons( &$tabindex ) {
3527 $buttons = array();
3528
3529 $temp = array(
3530 'id' => 'wpSave',
3531 'name' => 'wpSave',
3532 'type' => 'submit',
3533 'tabindex' => ++$tabindex,
3534 'value' => wfMessage( 'savearticle' )->text(),
3535 'accesskey' => wfMessage( 'accesskey-save' )->text(),
3536 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
3537 );
3538 $buttons['save'] = Xml::element( 'input', $temp, '' );
3539
3540 ++$tabindex; // use the same for preview and live preview
3541 $temp = array(
3542 'id' => 'wpPreview',
3543 'name' => 'wpPreview',
3544 'type' => 'submit',
3545 'tabindex' => $tabindex,
3546 'value' => wfMessage( 'showpreview' )->text(),
3547 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
3548 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
3549 );
3550 $buttons['preview'] = Xml::element( 'input', $temp, '' );
3551 $buttons['live'] = '';
3552
3553 $temp = array(
3554 'id' => 'wpDiff',
3555 'name' => 'wpDiff',
3556 'type' => 'submit',
3557 'tabindex' => ++$tabindex,
3558 'value' => wfMessage( 'showdiff' )->text(),
3559 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
3560 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
3561 );
3562 $buttons['diff'] = Xml::element( 'input', $temp, '' );
3563
3564 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3565 return $buttons;
3566 }
3567
3568 /**
3569 * Output preview text only. This can be sucked into the edit page
3570 * via JavaScript, and saves the server time rendering the skin as
3571 * well as theoretically being more robust on the client (doesn't
3572 * disturb the edit box's undo history, won't eat your text on
3573 * failure, etc).
3574 *
3575 * @todo This doesn't include category or interlanguage links.
3576 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3577 * or something...</s>" that might also require more skin
3578 * initialization, so check whether that's a problem.
3579 */
3580 function livePreview() {
3581 global $wgOut;
3582 $wgOut->disable();
3583 header( 'Content-type: text/xml; charset=utf-8' );
3584 header( 'Cache-control: no-cache' );
3585
3586 $previewText = $this->getPreviewText();
3587 #$categories = $skin->getCategoryLinks();
3588
3589 $s =
3590 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3591 Xml::tags( 'livepreview', null,
3592 Xml::element( 'preview', null, $previewText )
3593 #. Xml::element( 'category', null, $categories )
3594 );
3595 echo $s;
3596 }
3597
3598 /**
3599 * Call the stock "user is blocked" page
3600 *
3601 * @deprecated in 1.19; throw an exception directly instead
3602 */
3603 function blockedPage() {
3604 wfDeprecated( __METHOD__, '1.19' );
3605 global $wgUser;
3606
3607 throw new UserBlockedError( $wgUser->getBlock() );
3608 }
3609
3610 /**
3611 * Produce the stock "please login to edit pages" page
3612 *
3613 * @deprecated in 1.19; throw an exception directly instead
3614 */
3615 function userNotLoggedInPage() {
3616 wfDeprecated( __METHOD__, '1.19' );
3617 throw new PermissionsError( 'edit' );
3618 }
3619
3620 /**
3621 * Show an error page saying to the user that he has insufficient permissions
3622 * to create a new page
3623 *
3624 * @deprecated in 1.19; throw an exception directly instead
3625 */
3626 function noCreatePermission() {
3627 wfDeprecated( __METHOD__, '1.19' );
3628 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
3629 throw new PermissionsError( $permission );
3630 }
3631
3632 /**
3633 * Creates a basic error page which informs the user that
3634 * they have attempted to edit a nonexistent section.
3635 */
3636 function noSuchSectionPage() {
3637 global $wgOut;
3638
3639 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3640
3641 $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
3642 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3643 $wgOut->addHTML( $res );
3644
3645 $wgOut->returnToMain( false, $this->mTitle );
3646 }
3647
3648 /**
3649 * Show "your edit contains spam" page with your diff and text
3650 *
3651 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3652 */
3653 public function spamPageWithContent( $match = false ) {
3654 global $wgOut, $wgLang;
3655 $this->textbox2 = $this->textbox1;
3656
3657 if ( is_array( $match ) ) {
3658 $match = $wgLang->listToText( $match );
3659 }
3660 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3661
3662 $wgOut->addHTML( '<div id="spamprotected">' );
3663 $wgOut->addWikiMsg( 'spamprotectiontext' );
3664 if ( $match ) {
3665 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3666 }
3667 $wgOut->addHTML( '</div>' );
3668
3669 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3670 $this->showDiff();
3671
3672 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3673 $this->showTextbox2();
3674
3675 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3676 }
3677
3678 /**
3679 * Format an anchor fragment as it would appear for a given section name
3680 * @param $text String
3681 * @return String
3682 * @private
3683 */
3684 function sectionAnchor( $text ) {
3685 global $wgParser;
3686 return $wgParser->guessSectionNameFromWikiText( $text );
3687 }
3688
3689 /**
3690 * Check if the browser is on a blacklist of user-agents known to
3691 * mangle UTF-8 data on form submission. Returns true if Unicode
3692 * should make it through, false if it's known to be a problem.
3693 * @return bool
3694 * @private
3695 */
3696 function checkUnicodeCompliantBrowser() {
3697 global $wgBrowserBlackList, $wgRequest;
3698
3699 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3700 if ( $currentbrowser === false ) {
3701 // No User-Agent header sent? Trust it by default...
3702 return true;
3703 }
3704
3705 foreach ( $wgBrowserBlackList as $browser ) {
3706 if ( preg_match( $browser, $currentbrowser ) ) {
3707 return false;
3708 }
3709 }
3710 return true;
3711 }
3712
3713 /**
3714 * Filter an input field through a Unicode de-armoring process if it
3715 * came from an old browser with known broken Unicode editing issues.
3716 *
3717 * @param $request WebRequest
3718 * @param $field String
3719 * @return String
3720 * @private
3721 */
3722 function safeUnicodeInput( $request, $field ) {
3723 $text = rtrim( $request->getText( $field ) );
3724 return $request->getBool( 'safemode' )
3725 ? $this->unmakesafe( $text )
3726 : $text;
3727 }
3728
3729 /**
3730 * @param $request WebRequest
3731 * @param $text string
3732 * @return string
3733 */
3734 function safeUnicodeText( $request, $text ) {
3735 $text = rtrim( $text );
3736 return $request->getBool( 'safemode' )
3737 ? $this->unmakesafe( $text )
3738 : $text;
3739 }
3740
3741 /**
3742 * Filter an output field through a Unicode armoring process if it is
3743 * going to an old browser with known broken Unicode editing issues.
3744 *
3745 * @param $text String
3746 * @return String
3747 * @private
3748 */
3749 function safeUnicodeOutput( $text ) {
3750 global $wgContLang;
3751 $codedText = $wgContLang->recodeForEdit( $text );
3752 return $this->checkUnicodeCompliantBrowser()
3753 ? $codedText
3754 : $this->makesafe( $codedText );
3755 }
3756
3757 /**
3758 * A number of web browsers are known to corrupt non-ASCII characters
3759 * in a UTF-8 text editing environment. To protect against this,
3760 * detected browsers will be served an armored version of the text,
3761 * with non-ASCII chars converted to numeric HTML character references.
3762 *
3763 * Preexisting such character references will have a 0 added to them
3764 * to ensure that round-trips do not alter the original data.
3765 *
3766 * @param $invalue String
3767 * @return String
3768 * @private
3769 */
3770 function makesafe( $invalue ) {
3771 // Armor existing references for reversibility.
3772 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
3773
3774 $bytesleft = 0;
3775 $result = "";
3776 $working = 0;
3777 for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
3778 $bytevalue = ord( $invalue[$i] );
3779 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3780 $result .= chr( $bytevalue );
3781 $bytesleft = 0;
3782 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3783 $working = $working << 6;
3784 $working += ( $bytevalue & 0x3F );
3785 $bytesleft--;
3786 if ( $bytesleft <= 0 ) {
3787 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3788 }
3789 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3790 $working = $bytevalue & 0x1F;
3791 $bytesleft = 1;
3792 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3793 $working = $bytevalue & 0x0F;
3794 $bytesleft = 2;
3795 } else { // 1111 0xxx
3796 $working = $bytevalue & 0x07;
3797 $bytesleft = 3;
3798 }
3799 }
3800 return $result;
3801 }
3802
3803 /**
3804 * Reverse the previously applied transliteration of non-ASCII characters
3805 * back to UTF-8. Used to protect data from corruption by broken web browsers
3806 * as listed in $wgBrowserBlackList.
3807 *
3808 * @param $invalue String
3809 * @return String
3810 * @private
3811 */
3812 function unmakesafe( $invalue ) {
3813 $result = "";
3814 for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
3815 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
3816 $i += 3;
3817 $hexstring = "";
3818 do {
3819 $hexstring .= $invalue[$i];
3820 $i++;
3821 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3822
3823 // Do some sanity checks. These aren't needed for reversibility,
3824 // but should help keep the breakage down if the editor
3825 // breaks one of the entities whilst editing.
3826 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3827 $codepoint = hexdec( $hexstring );
3828 $result .= codepointToUtf8( $codepoint );
3829 } else {
3830 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3831 }
3832 } else {
3833 $result .= substr( $invalue, $i, 1 );
3834 }
3835 }
3836 // reverse the transform that we made for reversibility reasons.
3837 return strtr( $result, array( "&#x0" => "&#x" ) );
3838 }
3839 }