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