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