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