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