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