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