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