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