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