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