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