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