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