Merge "Added protocol option to Linker and OutputPage::addReturnTo."
[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' ) ) {
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' ) ) {
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' ) ) {
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->commitWatch();
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 * Commit the change of watch status
1483 */
1484 protected function commitWatch() {
1485 global $wgUser;
1486 if ( $wgUser->isLoggedIn() && $this->watchthis != $wgUser->isWatched( $this->mTitle ) ) {
1487 $dbw = wfGetDB( DB_MASTER );
1488 $dbw->begin( __METHOD__ );
1489 if ( $this->watchthis ) {
1490 WatchAction::doWatch( $this->mTitle, $wgUser );
1491 } else {
1492 WatchAction::doUnwatch( $this->mTitle, $wgUser );
1493 }
1494 $dbw->commit( __METHOD__ );
1495 }
1496 }
1497
1498 /**
1499 * @private
1500 * @todo document
1501 *
1502 * @param $editText string
1503 *
1504 * @return bool
1505 */
1506 function mergeChangesInto( &$editText ) {
1507 wfProfileIn( __METHOD__ );
1508
1509 $db = wfGetDB( DB_MASTER );
1510
1511 // This is the revision the editor started from
1512 $baseRevision = $this->getBaseRevision();
1513 if ( is_null( $baseRevision ) ) {
1514 wfProfileOut( __METHOD__ );
1515 return false;
1516 }
1517 $baseText = $baseRevision->getText();
1518
1519 // The current state, we want to merge updates into it
1520 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
1521 if ( is_null( $currentRevision ) ) {
1522 wfProfileOut( __METHOD__ );
1523 return false;
1524 }
1525 $currentText = $currentRevision->getText();
1526
1527 $result = '';
1528 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1529 $editText = $result;
1530 wfProfileOut( __METHOD__ );
1531 return true;
1532 } else {
1533 wfProfileOut( __METHOD__ );
1534 return false;
1535 }
1536 }
1537
1538 /**
1539 * @return Revision
1540 */
1541 function getBaseRevision() {
1542 if ( !$this->mBaseRevision ) {
1543 $db = wfGetDB( DB_MASTER );
1544 $baseRevision = Revision::loadFromTimestamp(
1545 $db, $this->mTitle, $this->edittime );
1546 return $this->mBaseRevision = $baseRevision;
1547 } else {
1548 return $this->mBaseRevision;
1549 }
1550 }
1551
1552 /**
1553 * Check given input text against $wgSpamRegex, and return the text of the first match.
1554 *
1555 * @param $text string
1556 *
1557 * @return string|bool matching string or false
1558 */
1559 public static function matchSpamRegex( $text ) {
1560 global $wgSpamRegex;
1561 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1562 $regexes = (array)$wgSpamRegex;
1563 return self::matchSpamRegexInternal( $text, $regexes );
1564 }
1565
1566 /**
1567 * Check given input text against $wgSpamRegex, and return the text of the first match.
1568 *
1569 * @param $text string
1570 *
1571 * @return string|bool matching string or false
1572 */
1573 public static function matchSummarySpamRegex( $text ) {
1574 global $wgSummarySpamRegex;
1575 $regexes = (array)$wgSummarySpamRegex;
1576 return self::matchSpamRegexInternal( $text, $regexes );
1577 }
1578
1579 /**
1580 * @param $text string
1581 * @param $regexes array
1582 * @return bool|string
1583 */
1584 protected static function matchSpamRegexInternal( $text, $regexes ) {
1585 foreach ( $regexes as $regex ) {
1586 $matches = array();
1587 if ( preg_match( $regex, $text, $matches ) ) {
1588 return $matches[0];
1589 }
1590 }
1591 return false;
1592 }
1593
1594 function setHeaders() {
1595 global $wgOut, $wgUser;
1596
1597 $wgOut->addModules( 'mediawiki.action.edit' );
1598
1599 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
1600 $wgOut->addModules( 'mediawiki.action.edit.preview' );
1601 }
1602 // Bug #19334: textarea jumps when editing articles in IE8
1603 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
1604
1605 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1606
1607 # Enabled article-related sidebar, toplinks, etc.
1608 $wgOut->setArticleRelated( true );
1609
1610 $contextTitle = $this->getContextTitle();
1611 if ( $this->isConflict ) {
1612 $msg = 'editconflict';
1613 } elseif ( $contextTitle->exists() && $this->section != '' ) {
1614 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
1615 } else {
1616 $msg = $contextTitle->exists() || ( $contextTitle->getNamespace() == NS_MEDIAWIKI && $contextTitle->getDefaultMessageText() !== false ) ?
1617 'editing' : 'creating';
1618 }
1619 # Use the title defined by DISPLAYTITLE magic word when present
1620 $displayTitle = isset( $this->mParserOutput ) ? $this->mParserOutput->getDisplayTitle() : false;
1621 if ( $displayTitle === false ) {
1622 $displayTitle = $contextTitle->getPrefixedText();
1623 }
1624 $wgOut->setPageTitle( wfMessage( $msg, $displayTitle ) );
1625 }
1626
1627 /**
1628 * Show all applicable editing introductions
1629 */
1630 protected function showIntro() {
1631 global $wgOut, $wgUser;
1632 if ( $this->suppressIntro ) {
1633 return;
1634 }
1635
1636 $namespace = $this->mTitle->getNamespace();
1637
1638 if ( $namespace == NS_MEDIAWIKI ) {
1639 # Show a warning if editing an interface message
1640 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1641 } else if( $namespace == NS_FILE ) {
1642 # Show a hint to shared repo
1643 $file = wfFindFile( $this->mTitle );
1644 if( $file && !$file->isLocal() ) {
1645 $descUrl = $file->getDescriptionUrl();
1646 # there must be a description url to show a hint to shared repo
1647 if( $descUrl ) {
1648 if( !$this->mTitle->exists() ) {
1649 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-create\">\n$1\n</div>", array (
1650 'sharedupload-desc-create', $file->getRepo()->getDisplayName(), $descUrl
1651 ) );
1652 } else {
1653 $wgOut->wrapWikiMsg( "<div class=\"mw-sharedupload-desc-edit\">\n$1\n</div>", array(
1654 'sharedupload-desc-edit', $file->getRepo()->getDisplayName(), $descUrl
1655 ) );
1656 }
1657 }
1658 }
1659 }
1660
1661 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1662 # Show log extract when the user is currently blocked
1663 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
1664 $parts = explode( '/', $this->mTitle->getText(), 2 );
1665 $username = $parts[0];
1666 $user = User::newFromName( $username, false /* allow IP users*/ );
1667 $ip = User::isIP( $username );
1668 if ( !( $user && $user->isLoggedIn() ) && !$ip ) { # User does not exist
1669 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1670 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1671 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1672 LogEventsList::showLogExtract(
1673 $wgOut,
1674 'block',
1675 $user->getUserPage(),
1676 '',
1677 array(
1678 'lim' => 1,
1679 'showIfEmpty' => false,
1680 'msgKey' => array(
1681 'blocked-notice-logextract',
1682 $user->getName() # Support GENDER in notice
1683 )
1684 )
1685 );
1686 }
1687 }
1688 # Try to add a custom edit intro, or use the standard one if this is not possible.
1689 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
1690 if ( $wgUser->isLoggedIn() ) {
1691 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1692 } else {
1693 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1694 }
1695 }
1696 # Give a notice if the user is editing a deleted/moved page...
1697 if ( !$this->mTitle->exists() ) {
1698 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
1699 '', array( 'lim' => 10,
1700 'conds' => array( "log_action != 'revision'" ),
1701 'showIfEmpty' => false,
1702 'msgKey' => array( 'recreate-moveddeleted-warn' ) )
1703 );
1704 }
1705 }
1706
1707 /**
1708 * Attempt to show a custom editing introduction, if supplied
1709 *
1710 * @return bool
1711 */
1712 protected function showCustomIntro() {
1713 if ( $this->editintro ) {
1714 $title = Title::newFromText( $this->editintro );
1715 if ( $title instanceof Title && $title->exists() && $title->userCan( 'read' ) ) {
1716 global $wgOut;
1717 // Added using template syntax, to take <noinclude>'s into account.
1718 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle );
1719 return true;
1720 } else {
1721 return false;
1722 }
1723 } else {
1724 return false;
1725 }
1726 }
1727
1728 /**
1729 * Send the edit form and related headers to $wgOut
1730 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1731 * during form output near the top, for captchas and the like.
1732 */
1733 function showEditForm( $formCallback = null ) {
1734 global $wgOut, $wgUser;
1735
1736 wfProfileIn( __METHOD__ );
1737
1738 # need to parse the preview early so that we know which templates are used,
1739 # otherwise users with "show preview after edit box" will get a blank list
1740 # we parse this near the beginning so that setHeaders can do the title
1741 # setting work instead of leaving it in getPreviewText
1742 $previewOutput = '';
1743 if ( $this->formtype == 'preview' ) {
1744 $previewOutput = $this->getPreviewText();
1745 }
1746
1747 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this, &$wgOut ) );
1748
1749 $this->setHeaders();
1750
1751 if ( $this->showHeader() === false ) {
1752 wfProfileOut( __METHOD__ );
1753 return;
1754 }
1755
1756 $wgOut->addHTML( $this->editFormPageTop );
1757
1758 if ( $wgUser->getOption( 'previewontop' ) ) {
1759 $this->displayPreviewArea( $previewOutput, true );
1760 }
1761
1762 $wgOut->addHTML( $this->editFormTextTop );
1763
1764 $showToolbar = true;
1765 if ( $this->wasDeletedSinceLastEdit() ) {
1766 if ( $this->formtype == 'save' ) {
1767 // Hide the toolbar and edit area, user can click preview to get it back
1768 // Add an confirmation checkbox and explanation.
1769 $showToolbar = false;
1770 } else {
1771 $wgOut->wrapWikiMsg( "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1772 'deletedwhileediting' );
1773 }
1774 }
1775
1776 $wgOut->addHTML( Html::openElement( 'form', array( 'id' => self::EDITFORM_ID, 'name' => self::EDITFORM_ID,
1777 'method' => 'post', 'action' => $this->getActionURL( $this->getContextTitle() ),
1778 'enctype' => 'multipart/form-data' ) ) );
1779
1780 if ( is_callable( $formCallback ) ) {
1781 call_user_func_array( $formCallback, array( &$wgOut ) );
1782 }
1783
1784 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1785
1786 // Put these up at the top to ensure they aren't lost on early form submission
1787 $this->showFormBeforeText();
1788
1789 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
1790 $username = $this->lastDelete->user_name;
1791 $comment = $this->lastDelete->log_comment;
1792
1793 // It is better to not parse the comment at all than to have templates expanded in the middle
1794 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1795 $key = $comment === ''
1796 ? 'confirmrecreate-noreason'
1797 : 'confirmrecreate';
1798 $wgOut->addHTML(
1799 '<div class="mw-confirm-recreate">' .
1800 wfMessage( $key, $username, "<nowiki>$comment</nowiki>" )->parse() .
1801 Xml::checkLabel( wfMessage( 'recreate' )->text(), 'wpRecreate', 'wpRecreate', false,
1802 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1803 ) .
1804 '</div>'
1805 );
1806 }
1807
1808 # When the summary is hidden, also hide them on preview/show changes
1809 if( $this->nosummary ) {
1810 $wgOut->addHTML( Html::hidden( 'nosummary', true ) );
1811 }
1812
1813 # If a blank edit summary was previously provided, and the appropriate
1814 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1815 # user being bounced back more than once in the event that a summary
1816 # is not required.
1817 #####
1818 # For a bit more sophisticated detection of blank summaries, hash the
1819 # automatic one and pass that in the hidden field wpAutoSummary.
1820 if ( $this->missingSummary || ( $this->section == 'new' && $this->nosummary ) ) {
1821 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
1822 }
1823
1824 if ( $this->undidRev ) {
1825 $wgOut->addHTML( Html::hidden( 'wpUndidRevision', $this->undidRev ) );
1826 }
1827
1828 if ( $this->hasPresetSummary ) {
1829 // If a summary has been preset using &summary= we dont want to prompt for
1830 // a different summary. Only prompt for a summary if the summary is blanked.
1831 // (Bug 17416)
1832 $this->autoSumm = md5( '' );
1833 }
1834
1835 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1836 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
1837
1838 $wgOut->addHTML( Html::hidden( 'oldid', $this->oldid ) );
1839
1840 if ( $this->section == 'new' ) {
1841 $this->showSummaryInput( true, $this->summary );
1842 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
1843 }
1844
1845 $wgOut->addHTML( $this->editFormTextBeforeContent );
1846
1847 if ( !$this->isCssJsSubpage && $showToolbar && $wgUser->getOption( 'showtoolbar' ) ) {
1848 $wgOut->addHTML( EditPage::getEditToolbar() );
1849 }
1850
1851 if ( $this->isConflict ) {
1852 // In an edit conflict bypass the overrideable content form method
1853 // and fallback to the raw wpTextbox1 since editconflicts can't be
1854 // resolved between page source edits and custom ui edits using the
1855 // custom edit ui.
1856 $this->textbox2 = $this->textbox1;
1857 $this->textbox1 = $this->getCurrentText();
1858
1859 $this->showTextbox1();
1860 } else {
1861 $this->showContentForm();
1862 }
1863
1864 $wgOut->addHTML( $this->editFormTextAfterContent );
1865
1866 $this->showStandardInputs();
1867
1868 $this->showFormAfterText();
1869
1870 $this->showTosSummary();
1871
1872 $this->showEditTools();
1873
1874 $wgOut->addHTML( $this->editFormTextAfterTools . "\n" );
1875
1876 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'templatesUsed' ),
1877 Linker::formatTemplates( $this->getTemplates(), $this->preview, $this->section != '' ) ) );
1878
1879 $wgOut->addHTML( Html::rawElement( 'div', array( 'class' => 'hiddencats' ),
1880 Linker::formatHiddenCategories( $this->mArticle->getHiddenCategories() ) ) );
1881
1882 if ( $this->isConflict ) {
1883 $this->showConflict();
1884 }
1885
1886 $wgOut->addHTML( $this->editFormTextBottom . "\n</form>\n" );
1887
1888 if ( !$wgUser->getOption( 'previewontop' ) ) {
1889 $this->displayPreviewArea( $previewOutput, false );
1890 }
1891
1892 wfProfileOut( __METHOD__ );
1893 }
1894
1895 /**
1896 * Extract the section title from current section text, if any.
1897 *
1898 * @param string $text
1899 * @return Mixed|string or false
1900 */
1901 public static function extractSectionTitle( $text ) {
1902 preg_match( "/^(=+)(.+)\\1\\s*(\n|$)/i", $text, $matches );
1903 if ( !empty( $matches[2] ) ) {
1904 global $wgParser;
1905 return $wgParser->stripSectionName( trim( $matches[2] ) );
1906 } else {
1907 return false;
1908 }
1909 }
1910
1911 protected function showHeader() {
1912 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1913
1914 if ( $this->mTitle->isTalkPage() ) {
1915 $wgOut->addWikiMsg( 'talkpagetext' );
1916 }
1917
1918 # Optional notices on a per-namespace and per-page basis
1919 $editnotice_ns = 'editnotice-' . $this->mTitle->getNamespace();
1920 $editnotice_ns_message = wfMessage( $editnotice_ns );
1921 if ( $editnotice_ns_message->exists() ) {
1922 $wgOut->addWikiText( $editnotice_ns_message->plain() );
1923 }
1924 if ( MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
1925 $parts = explode( '/', $this->mTitle->getDBkey() );
1926 $editnotice_base = $editnotice_ns;
1927 while ( count( $parts ) > 0 ) {
1928 $editnotice_base .= '-' . array_shift( $parts );
1929 $editnotice_base_msg = wfMessage( $editnotice_base );
1930 if ( $editnotice_base_msg->exists() ) {
1931 $wgOut->addWikiText( $editnotice_base_msg->plain() );
1932 }
1933 }
1934 } else {
1935 # Even if there are no subpages in namespace, we still don't want / in MW ns.
1936 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle->getDBkey() );
1937 $editnoticeMsg = wfMessage( $editnoticeText );
1938 if ( $editnoticeMsg->exists() ) {
1939 $wgOut->addWikiText( $editnoticeMsg->plain() );
1940 }
1941 }
1942
1943 if ( $this->isConflict ) {
1944 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1945 $this->edittime = $this->mArticle->getTimestamp();
1946 } else {
1947 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
1948 // We use $this->section to much before this and getVal('wgSection') directly in other places
1949 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1950 // Someone is welcome to try refactoring though
1951 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1952 return false;
1953 }
1954
1955 if ( $this->section != '' && $this->section != 'new' ) {
1956 if ( !$this->summary && !$this->preview && !$this->diff ) {
1957 $sectionTitle = self::extractSectionTitle( $this->textbox1 );
1958 if ( $sectionTitle !== false ) {
1959 $this->summary = "/* $sectionTitle */ ";
1960 }
1961 }
1962 }
1963
1964 if ( $this->missingComment ) {
1965 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1966 }
1967
1968 if ( $this->missingSummary && $this->section != 'new' ) {
1969 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1970 }
1971
1972 if ( $this->missingSummary && $this->section == 'new' ) {
1973 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1974 }
1975
1976 if ( $this->hookError !== '' ) {
1977 $wgOut->addWikiText( $this->hookError );
1978 }
1979
1980 if ( !$this->checkUnicodeCompliantBrowser() ) {
1981 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1982 }
1983
1984 if ( $this->section != 'new' ) {
1985 $revision = $this->mArticle->getRevisionFetched();
1986 if ( $revision ) {
1987 // Let sysop know that this will make private content public if saved
1988
1989 if ( !$revision->userCan( Revision::DELETED_TEXT ) ) {
1990 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1991 } elseif ( $revision->isDeleted( Revision::DELETED_TEXT ) ) {
1992 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1993 }
1994
1995 if ( !$revision->isCurrent() ) {
1996 $this->mArticle->setOldSubtitle( $revision->getId() );
1997 $wgOut->addWikiMsg( 'editingold' );
1998 }
1999 } elseif ( $this->mTitle->exists() ) {
2000 // Something went wrong
2001
2002 $wgOut->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>\n",
2003 array( 'missing-revision', $this->oldid ) );
2004 }
2005 }
2006 }
2007
2008 if ( wfReadOnly() ) {
2009 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
2010 } elseif ( $wgUser->isAnon() ) {
2011 if ( $this->formtype != 'preview' ) {
2012 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
2013 } else {
2014 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
2015 }
2016 } else {
2017 if ( $this->isCssJsSubpage ) {
2018 # Check the skin exists
2019 if ( $this->isWrongCaseCssJsPage ) {
2020 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
2021 }
2022 if ( $this->formtype !== 'preview' ) {
2023 if ( $this->isCssSubpage ) {
2024 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
2025 }
2026
2027 if ( $this->isJsSubpage ) {
2028 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
2029 }
2030 }
2031 }
2032 }
2033
2034 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
2035 # Is the title semi-protected?
2036 if ( $this->mTitle->isSemiProtected() ) {
2037 $noticeMsg = 'semiprotectedpagewarning';
2038 } else {
2039 # Then it must be protected based on static groups (regular)
2040 $noticeMsg = 'protectedpagewarning';
2041 }
2042 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2043 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
2044 }
2045 if ( $this->mTitle->isCascadeProtected() ) {
2046 # Is this page under cascading protection from some source pages?
2047 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
2048 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
2049 $cascadeSourcesCount = count( $cascadeSources );
2050 if ( $cascadeSourcesCount > 0 ) {
2051 # Explain, and list the titles responsible
2052 foreach ( $cascadeSources as $page ) {
2053 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
2054 }
2055 }
2056 $notice .= '</div>';
2057 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
2058 }
2059 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
2060 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
2061 array( 'lim' => 1,
2062 'showIfEmpty' => false,
2063 'msgKey' => array( 'titleprotectedwarning' ),
2064 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
2065 }
2066
2067 if ( $this->kblength === false ) {
2068 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
2069 }
2070
2071 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
2072 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
2073 array( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ) );
2074 } else {
2075 if ( !wfMessage( 'longpage-hint' )->isDisabled() ) {
2076 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
2077 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 ) )
2078 );
2079 }
2080 }
2081 # Add header copyright warning
2082 $this->showHeaderCopyrightWarning();
2083 }
2084
2085
2086 /**
2087 * Standard summary input and label (wgSummary), abstracted so EditPage
2088 * subclasses may reorganize the form.
2089 * Note that you do not need to worry about the label's for=, it will be
2090 * inferred by the id given to the input. You can remove them both by
2091 * passing array( 'id' => false ) to $userInputAttrs.
2092 *
2093 * @param $summary string The value of the summary input
2094 * @param $labelText string The html to place inside the label
2095 * @param $inputAttrs array of attrs to use on the input
2096 * @param $spanLabelAttrs array of attrs to use on the span inside the label
2097 *
2098 * @return array An array in the format array( $label, $input )
2099 */
2100 function getSummaryInput( $summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null ) {
2101 // Note: the maxlength is overriden in JS to 255 and to make it use UTF-8 bytes, not characters.
2102 $inputAttrs = ( is_array( $inputAttrs ) ? $inputAttrs : array() ) + array(
2103 'id' => 'wpSummary',
2104 'maxlength' => '200',
2105 'tabindex' => '1',
2106 'size' => 60,
2107 'spellcheck' => 'true',
2108 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
2109
2110 $spanLabelAttrs = ( is_array( $spanLabelAttrs ) ? $spanLabelAttrs : array() ) + array(
2111 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
2112 'id' => "wpSummaryLabel"
2113 );
2114
2115 $label = null;
2116 if ( $labelText ) {
2117 $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
2118 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
2119 }
2120
2121 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
2122
2123 return array( $label, $input );
2124 }
2125
2126 /**
2127 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2128 * up top, or false if this is the comment summary
2129 * down below the textarea
2130 * @param $summary String: The text of the summary to display
2131 * @return String
2132 */
2133 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
2134 global $wgOut, $wgContLang;
2135 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
2136 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
2137 if ( $isSubjectPreview ) {
2138 if ( $this->nosummary ) {
2139 return;
2140 }
2141 } else {
2142 if ( !$this->mShowSummaryField ) {
2143 return;
2144 }
2145 }
2146 $summary = $wgContLang->recodeForEdit( $summary );
2147 $labelText = wfMessage( $isSubjectPreview ? 'subject' : 'summary' )->parse();
2148 list( $label, $input ) = $this->getSummaryInput( $summary, $labelText, array( 'class' => $summaryClass ), array() );
2149 $wgOut->addHTML( "{$label} {$input}" );
2150 }
2151
2152 /**
2153 * @param $isSubjectPreview Boolean: true if this is the section subject/title
2154 * up top, or false if this is the comment summary
2155 * down below the textarea
2156 * @param $summary String: the text of the summary to display
2157 * @return String
2158 */
2159 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
2160 if ( !$summary || ( !$this->preview && !$this->diff ) ) {
2161 return "";
2162 }
2163
2164 global $wgParser;
2165
2166 if ( $isSubjectPreview ) {
2167 $summary = wfMessage( 'newsectionsummary', $wgParser->stripSectionName( $summary ) )
2168 ->inContentLanguage()->text();
2169 }
2170
2171 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
2172
2173 $summary = wfMessage( $message )->parse() . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
2174 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
2175 }
2176
2177 protected function showFormBeforeText() {
2178 global $wgOut;
2179 $section = htmlspecialchars( $this->section );
2180 $wgOut->addHTML( <<<HTML
2181 <input type='hidden' value="{$section}" name="wpSection" />
2182 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
2183 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
2184 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
2185
2186 HTML
2187 );
2188 if ( !$this->checkUnicodeCompliantBrowser() ) {
2189 $wgOut->addHTML( Html::hidden( 'safemode', '1' ) );
2190 }
2191 }
2192
2193 protected function showFormAfterText() {
2194 global $wgOut, $wgUser;
2195 /**
2196 * To make it harder for someone to slip a user a page
2197 * which submits an edit form to the wiki without their
2198 * knowledge, a random token is associated with the login
2199 * session. If it's not passed back with the submission,
2200 * we won't save the page, or render user JavaScript and
2201 * CSS previews.
2202 *
2203 * For anon editors, who may not have a session, we just
2204 * include the constant suffix to prevent editing from
2205 * broken text-mangling proxies.
2206 */
2207 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
2208 }
2209
2210 /**
2211 * Subpage overridable method for printing the form for page content editing
2212 * By default this simply outputs wpTextbox1
2213 * Subclasses can override this to provide a custom UI for editing;
2214 * be it a form, or simply wpTextbox1 with a modified content that will be
2215 * reverse modified when extracted from the post data.
2216 * Note that this is basically the inverse for importContentFormData
2217 */
2218 protected function showContentForm() {
2219 $this->showTextbox1();
2220 }
2221
2222 /**
2223 * Method to output wpTextbox1
2224 * The $textoverride method can be used by subclasses overriding showContentForm
2225 * to pass back to this method.
2226 *
2227 * @param $customAttribs array of html attributes to use in the textarea
2228 * @param $textoverride String: optional text to override $this->textarea1 with
2229 */
2230 protected function showTextbox1( $customAttribs = null, $textoverride = null ) {
2231 if ( $this->wasDeletedSinceLastEdit() && $this->formtype == 'save' ) {
2232 $attribs = array( 'style' => 'display:none;' );
2233 } else {
2234 $classes = array(); // Textarea CSS
2235 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
2236 # Is the title semi-protected?
2237 if ( $this->mTitle->isSemiProtected() ) {
2238 $classes[] = 'mw-textarea-sprotected';
2239 } else {
2240 # Then it must be protected based on static groups (regular)
2241 $classes[] = 'mw-textarea-protected';
2242 }
2243 # Is the title cascade-protected?
2244 if ( $this->mTitle->isCascadeProtected() ) {
2245 $classes[] = 'mw-textarea-cprotected';
2246 }
2247 }
2248
2249 $attribs = array( 'tabindex' => 1 );
2250
2251 if ( is_array( $customAttribs ) ) {
2252 $attribs += $customAttribs;
2253 }
2254
2255 if ( count( $classes ) ) {
2256 if ( isset( $attribs['class'] ) ) {
2257 $classes[] = $attribs['class'];
2258 }
2259 $attribs['class'] = implode( ' ', $classes );
2260 }
2261 }
2262
2263 $this->showTextbox( $textoverride !== null ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
2264 }
2265
2266 protected function showTextbox2() {
2267 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2268 }
2269
2270 protected function showTextbox( $content, $name, $customAttribs = array() ) {
2271 global $wgOut, $wgUser;
2272
2273 $wikitext = $this->safeUnicodeOutput( $content );
2274 if ( strval( $wikitext ) !== '' ) {
2275 // Ensure there's a newline at the end, otherwise adding lines
2276 // is awkward.
2277 // But don't add a newline if the ext is empty, or Firefox in XHTML
2278 // mode will show an extra newline. A bit annoying.
2279 $wikitext .= "\n";
2280 }
2281
2282 $attribs = $customAttribs + array(
2283 'accesskey' => ',',
2284 'id' => $name,
2285 'cols' => $wgUser->getIntOption( 'cols' ),
2286 'rows' => $wgUser->getIntOption( 'rows' ),
2287 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2288 );
2289
2290 $pageLang = $this->mTitle->getPageLanguage();
2291 $attribs['lang'] = $pageLang->getCode();
2292 $attribs['dir'] = $pageLang->getDir();
2293
2294 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
2295 }
2296
2297 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2298 global $wgOut;
2299 $classes = array();
2300 if ( $isOnTop ) {
2301 $classes[] = 'ontop';
2302 }
2303
2304 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2305
2306 if ( $this->formtype != 'preview' ) {
2307 $attribs['style'] = 'display: none;';
2308 }
2309
2310 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
2311
2312 if ( $this->formtype == 'preview' ) {
2313 $this->showPreview( $previewOutput );
2314 }
2315
2316 $wgOut->addHTML( '</div>' );
2317
2318 if ( $this->formtype == 'diff' ) {
2319 $this->showDiff();
2320 }
2321 }
2322
2323 /**
2324 * Append preview output to $wgOut.
2325 * Includes category rendering if this is a category page.
2326 *
2327 * @param $text String: the HTML to be output for the preview.
2328 */
2329 protected function showPreview( $text ) {
2330 global $wgOut;
2331 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2332 $this->mArticle->openShowCategory();
2333 }
2334 # This hook seems slightly odd here, but makes things more
2335 # consistent for extensions.
2336 wfRunHooks( 'OutputPageBeforeHTML', array( &$wgOut, &$text ) );
2337 $wgOut->addHTML( $text );
2338 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2339 $this->mArticle->closeShowCategory();
2340 }
2341 }
2342
2343 /**
2344 * Get a diff between the current contents of the edit box and the
2345 * version of the page we're editing from.
2346 *
2347 * If this is a section edit, we'll replace the section as for final
2348 * save and then make a comparison.
2349 */
2350 function showDiff() {
2351 global $wgUser, $wgContLang, $wgParser, $wgOut;
2352
2353 $oldtitlemsg = 'currentrev';
2354 # if message does not exist, show diff against the preloaded default
2355 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI && !$this->mTitle->exists() ) {
2356 $oldtext = $this->mTitle->getDefaultMessageText();
2357 if( $oldtext !== false ) {
2358 $oldtitlemsg = 'defaultmessagetext';
2359 }
2360 } else {
2361 $oldtext = $this->mArticle->getRawText();
2362 }
2363 $newtext = $this->mArticle->replaceSection(
2364 $this->section, $this->textbox1, $this->summary, $this->edittime );
2365
2366 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2367
2368 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
2369 $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle, $wgUser, $popts );
2370
2371 if ( $oldtext !== false || $newtext != '' ) {
2372 $oldtitle = wfMessage( $oldtitlemsg )->parse();
2373 $newtitle = wfMessage( 'yourtext' )->parse();
2374
2375 $de = new DifferenceEngine( $this->mArticle->getContext() );
2376 $de->setText( $oldtext, $newtext );
2377 $difftext = $de->getDiff( $oldtitle, $newtitle );
2378 $de->showDiffStyle();
2379 } else {
2380 $difftext = '';
2381 }
2382
2383 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2384 }
2385
2386 /**
2387 * Show the header copyright warning.
2388 */
2389 protected function showHeaderCopyrightWarning() {
2390 $msg = 'editpage-head-copy-warn';
2391 if ( !wfMessage( $msg )->isDisabled() ) {
2392 global $wgOut;
2393 $wgOut->wrapWikiMsg( "<div class='editpage-head-copywarn'>\n$1\n</div>",
2394 'editpage-head-copy-warn' );
2395 }
2396 }
2397
2398 /**
2399 * Give a chance for site and per-namespace customizations of
2400 * terms of service summary link that might exist separately
2401 * from the copyright notice.
2402 *
2403 * This will display between the save button and the edit tools,
2404 * so should remain short!
2405 */
2406 protected function showTosSummary() {
2407 $msg = 'editpage-tos-summary';
2408 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
2409 if ( !wfMessage( $msg )->isDisabled() ) {
2410 global $wgOut;
2411 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2412 $wgOut->addWikiMsg( $msg );
2413 $wgOut->addHTML( '</div>' );
2414 }
2415 }
2416
2417 protected function showEditTools() {
2418 global $wgOut;
2419 $wgOut->addHTML( '<div class="mw-editTools">' .
2420 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2421 '</div>' );
2422 }
2423
2424 /**
2425 * Get the copyright warning
2426 *
2427 * Renamed to getCopyrightWarning(), old name kept around for backwards compatibility
2428 */
2429 protected function getCopywarn() {
2430 return self::getCopyrightWarning( $this->mTitle );
2431 }
2432
2433 public static function getCopyrightWarning( $title ) {
2434 global $wgRightsText;
2435 if ( $wgRightsText ) {
2436 $copywarnMsg = array( 'copyrightwarning',
2437 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]',
2438 $wgRightsText );
2439 } else {
2440 $copywarnMsg = array( 'copyrightwarning2',
2441 '[[' . wfMessage( 'copyrightpage' )->inContentLanguage()->text() . ']]' );
2442 }
2443 // Allow for site and per-namespace customization of contribution/copyright notice.
2444 wfRunHooks( 'EditPageCopyrightWarning', array( $title, &$copywarnMsg ) );
2445
2446 return "<div id=\"editpage-copywarn\">\n" .
2447 call_user_func_array( 'wfMessage', $copywarnMsg )->plain() . "\n</div>";
2448 }
2449
2450 protected function showStandardInputs( &$tabindex = 2 ) {
2451 global $wgOut;
2452 $wgOut->addHTML( "<div class='editOptions'>\n" );
2453
2454 if ( $this->section != 'new' ) {
2455 $this->showSummaryInput( false, $this->summary );
2456 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
2457 }
2458
2459 $checkboxes = $this->getCheckboxes( $tabindex,
2460 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
2461 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2462
2463 // Show copyright warning.
2464 $wgOut->addWikiText( $this->getCopywarn() );
2465 $wgOut->addHTML( $this->editFormTextAfterWarn );
2466
2467 $wgOut->addHTML( "<div class='editButtons'>\n" );
2468 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2469
2470 $cancel = $this->getCancelLink();
2471 if ( $cancel !== '' ) {
2472 $cancel .= wfMessage( 'pipe-separator' )->text();
2473 }
2474 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMessage( 'edithelppage' )->inContentLanguage()->text() );
2475 $edithelp = '<a target="helpwindow" href="' . $edithelpurl . '">' .
2476 wfMessage( 'edithelp' )->escaped() . '</a> ' .
2477 wfMessage( 'newwindow' )->parse();
2478 $wgOut->addHTML( " <span class='cancelLink'>{$cancel}</span>\n" );
2479 $wgOut->addHTML( " <span class='editHelp'>{$edithelp}</span>\n" );
2480 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2481 }
2482
2483 /**
2484 * Show an edit conflict. textbox1 is already shown in showEditForm().
2485 * If you want to use another entry point to this function, be careful.
2486 */
2487 protected function showConflict() {
2488 global $wgOut;
2489
2490 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2491 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2492
2493 $de = new DifferenceEngine( $this->mArticle->getContext() );
2494 $de->setText( $this->textbox2, $this->textbox1 );
2495 $de->showDiff(
2496 wfMessage( 'yourtext' )->parse(),
2497 wfMessage( 'storedversion' )->text()
2498 );
2499
2500 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2501 $this->showTextbox2();
2502 }
2503 }
2504
2505 /**
2506 * @return string
2507 */
2508 public function getCancelLink() {
2509 $cancelParams = array();
2510 if ( !$this->isConflict && $this->oldid > 0 ) {
2511 $cancelParams['oldid'] = $this->oldid;
2512 }
2513
2514 return Linker::linkKnown(
2515 $this->getContextTitle(),
2516 wfMessage( 'cancel' )->parse(),
2517 array( 'id' => 'mw-editform-cancel' ),
2518 $cancelParams
2519 );
2520 }
2521
2522 /**
2523 * Returns the URL to use in the form's action attribute.
2524 * This is used by EditPage subclasses when simply customizing the action
2525 * variable in the constructor is not enough. This can be used when the
2526 * EditPage lives inside of a Special page rather than a custom page action.
2527 *
2528 * @param $title Title object for which is being edited (where we go to for &action= links)
2529 * @return string
2530 */
2531 protected function getActionURL( Title $title ) {
2532 return $title->getLocalURL( array( 'action' => $this->action ) );
2533 }
2534
2535 /**
2536 * Check if a page was deleted while the user was editing it, before submit.
2537 * Note that we rely on the logging table, which hasn't been always there,
2538 * but that doesn't matter, because this only applies to brand new
2539 * deletes.
2540 */
2541 protected function wasDeletedSinceLastEdit() {
2542 if ( $this->deletedSinceEdit !== null ) {
2543 return $this->deletedSinceEdit;
2544 }
2545
2546 $this->deletedSinceEdit = false;
2547
2548 if ( $this->mTitle->isDeletedQuick() ) {
2549 $this->lastDelete = $this->getLastDelete();
2550 if ( $this->lastDelete ) {
2551 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
2552 if ( $deleteTime > $this->starttime ) {
2553 $this->deletedSinceEdit = true;
2554 }
2555 }
2556 }
2557
2558 return $this->deletedSinceEdit;
2559 }
2560
2561 protected function getLastDelete() {
2562 $dbr = wfGetDB( DB_SLAVE );
2563 $data = $dbr->selectRow(
2564 array( 'logging', 'user' ),
2565 array( 'log_type',
2566 'log_action',
2567 'log_timestamp',
2568 'log_user',
2569 'log_namespace',
2570 'log_title',
2571 'log_comment',
2572 'log_params',
2573 'log_deleted',
2574 'user_name' ),
2575 array( 'log_namespace' => $this->mTitle->getNamespace(),
2576 'log_title' => $this->mTitle->getDBkey(),
2577 'log_type' => 'delete',
2578 'log_action' => 'delete',
2579 'user_id=log_user' ),
2580 __METHOD__,
2581 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2582 );
2583 // Quick paranoid permission checks...
2584 if ( is_object( $data ) ) {
2585 if ( $data->log_deleted & LogPage::DELETED_USER ) {
2586 $data->user_name = wfMessage( 'rev-deleted-user' )->escaped();
2587 }
2588
2589 if ( $data->log_deleted & LogPage::DELETED_COMMENT ) {
2590 $data->log_comment = wfMessage( 'rev-deleted-comment' )->escaped();
2591 }
2592 }
2593 return $data;
2594 }
2595
2596 /**
2597 * Get the rendered text for previewing.
2598 * @return string
2599 */
2600 function getPreviewText() {
2601 global $wgOut, $wgUser, $wgParser, $wgRawHtml, $wgLang;
2602
2603 wfProfileIn( __METHOD__ );
2604
2605 if ( $wgRawHtml && !$this->mTokenOk ) {
2606 // Could be an offsite preview attempt. This is very unsafe if
2607 // HTML is enabled, as it could be an attack.
2608 $parsedNote = '';
2609 if ( $this->textbox1 !== '' ) {
2610 // Do not put big scary notice, if previewing the empty
2611 // string, which happens when you initially edit
2612 // a category page, due to automatic preview-on-open.
2613 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2614 wfMessage( 'session_fail_preview_html' )->text() . "</div>", true, /* interface */true );
2615 }
2616 wfProfileOut( __METHOD__ );
2617 return $parsedNote;
2618 }
2619
2620 if ( $this->mTriedSave && !$this->mTokenOk ) {
2621 if ( $this->mTokenOkExceptSuffix ) {
2622 $note = wfMessage( 'token_suffix_mismatch' )->plain();
2623 } else {
2624 $note = wfMessage( 'session_fail_preview' )->plain();
2625 }
2626 } elseif ( $this->incompleteForm ) {
2627 $note = wfMessage( 'edit_form_incomplete' )->plain();
2628 } else {
2629 $note = wfMessage( 'previewnote' )->plain() .
2630 ' [[#' . self::EDITFORM_ID . '|' . $wgLang->getArrow() . ' ' . wfMessage( 'continue-editing' )->text() . ']]';
2631 }
2632
2633 $parserOptions = $this->mArticle->makeParserOptions( $this->mArticle->getContext() );
2634
2635 $parserOptions->setEditSection( false );
2636 $parserOptions->setIsPreview( true );
2637 $parserOptions->setIsSectionPreview( !is_null( $this->section ) && $this->section !== '' );
2638
2639 # don't parse non-wikitext pages, show message about preview
2640 if ( $this->mTitle->isCssJsSubpage() || !$this->mTitle->isWikitextPage() ) {
2641 if ( $this->mTitle->isCssJsSubpage() ) {
2642 $level = 'user';
2643 } elseif ( $this->mTitle->isCssOrJsPage() ) {
2644 $level = 'site';
2645 } else {
2646 $level = false;
2647 }
2648
2649 # Used messages to make sure grep find them:
2650 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2651 $class = 'mw-code';
2652 if ( $level ) {
2653 if ( preg_match( "/\\.css$/", $this->mTitle->getText() ) ) {
2654 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMessage( "{$level}csspreview" )->text() . "\n</div>";
2655 $class .= " mw-css";
2656 } elseif ( preg_match( "/\\.js$/", $this->mTitle->getText() ) ) {
2657 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMessage( "{$level}jspreview" )->text() . "\n</div>";
2658 $class .= " mw-js";
2659 } else {
2660 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2661 }
2662 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
2663 $previewHTML = $parserOutput->getText();
2664 } else {
2665 $previewHTML = '';
2666 }
2667
2668 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1 ) . "\n</pre>\n";
2669 } else {
2670 $toparse = $this->textbox1;
2671
2672 # If we're adding a comment, we need to show the
2673 # summary as the headline
2674 if ( $this->section == "new" && $this->summary != "" ) {
2675 $toparse = wfMessage( 'newsectionheaderdefaultlevel', $this->summary )->inContentLanguage()->text() . "\n\n" . $toparse;
2676 }
2677
2678 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2679
2680 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle, $wgUser, $parserOptions );
2681 $parserOutput = $wgParser->parse( $toparse, $this->mTitle, $parserOptions );
2682
2683 $rt = Title::newFromRedirectArray( $this->textbox1 );
2684 if ( $rt ) {
2685 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
2686 } else {
2687 $previewHTML = $parserOutput->getText();
2688 }
2689
2690 $this->mParserOutput = $parserOutput;
2691 $wgOut->addParserOutputNoText( $parserOutput );
2692
2693 if ( count( $parserOutput->getWarnings() ) ) {
2694 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2695 }
2696 }
2697
2698 if ( $this->isConflict ) {
2699 $conflict = '<h2 id="mw-previewconflict">' . wfMessage( 'previewconflict' )->escaped() . "</h2>\n";
2700 } else {
2701 $conflict = '<hr />';
2702 }
2703
2704 $previewhead = "<div class='previewnote'>\n" .
2705 '<h2 id="mw-previewheader">' . wfMessage( 'preview' )->escaped() . "</h2>" .
2706 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2707
2708 $pageLang = $this->mTitle->getPageLanguage();
2709 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2710 'class' => 'mw-content-' . $pageLang->getDir() );
2711 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
2712
2713 wfProfileOut( __METHOD__ );
2714 return $previewhead . $previewHTML . $this->previewTextAfterContent;
2715 }
2716
2717 /**
2718 * @return Array
2719 */
2720 function getTemplates() {
2721 if ( $this->preview || $this->section != '' ) {
2722 $templates = array();
2723 if ( !isset( $this->mParserOutput ) ) {
2724 return $templates;
2725 }
2726 foreach ( $this->mParserOutput->getTemplates() as $ns => $template ) {
2727 foreach ( array_keys( $template ) as $dbk ) {
2728 $templates[] = Title::makeTitle( $ns, $dbk );
2729 }
2730 }
2731 return $templates;
2732 } else {
2733 return $this->mTitle->getTemplateLinksFrom();
2734 }
2735 }
2736
2737 /**
2738 * Shows a bulletin board style toolbar for common editing functions.
2739 * It can be disabled in the user preferences.
2740 * The necessary JavaScript code can be found in skins/common/edit.js.
2741 *
2742 * @return string
2743 */
2744 static function getEditToolbar() {
2745 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2746 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2747
2748 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
2749
2750 /**
2751 * $toolarray is an array of arrays each of which includes the
2752 * filename of the button image (without path), the opening
2753 * tag, the closing tag, optionally a sample text that is
2754 * inserted between the two when no selection is highlighted
2755 * and. The tip text is shown when the user moves the mouse
2756 * over the button.
2757 *
2758 * Also here: accesskeys (key), which are not used yet until
2759 * someone can figure out a way to make them work in
2760 * IE. However, we should make sure these keys are not defined
2761 * on the edit page.
2762 */
2763 $toolarray = array(
2764 array(
2765 'image' => $wgLang->getImageFile( 'button-bold' ),
2766 'id' => 'mw-editbutton-bold',
2767 'open' => '\'\'\'',
2768 'close' => '\'\'\'',
2769 'sample' => wfMessage( 'bold_sample' )->text(),
2770 'tip' => wfMessage( 'bold_tip' )->text(),
2771 'key' => 'B'
2772 ),
2773 array(
2774 'image' => $wgLang->getImageFile( 'button-italic' ),
2775 'id' => 'mw-editbutton-italic',
2776 'open' => '\'\'',
2777 'close' => '\'\'',
2778 'sample' => wfMessage( 'italic_sample' )->text(),
2779 'tip' => wfMessage( 'italic_tip' )->text(),
2780 'key' => 'I'
2781 ),
2782 array(
2783 'image' => $wgLang->getImageFile( 'button-link' ),
2784 'id' => 'mw-editbutton-link',
2785 'open' => '[[',
2786 'close' => ']]',
2787 'sample' => wfMessage( 'link_sample' )->text(),
2788 'tip' => wfMessage( 'link_tip' )->text(),
2789 'key' => 'L'
2790 ),
2791 array(
2792 'image' => $wgLang->getImageFile( 'button-extlink' ),
2793 'id' => 'mw-editbutton-extlink',
2794 'open' => '[',
2795 'close' => ']',
2796 'sample' => wfMessage( 'extlink_sample' )->text(),
2797 'tip' => wfMessage( 'extlink_tip' )->text(),
2798 'key' => 'X'
2799 ),
2800 array(
2801 'image' => $wgLang->getImageFile( 'button-headline' ),
2802 'id' => 'mw-editbutton-headline',
2803 'open' => "\n== ",
2804 'close' => " ==\n",
2805 'sample' => wfMessage( 'headline_sample' )->text(),
2806 'tip' => wfMessage( 'headline_tip' )->text(),
2807 'key' => 'H'
2808 ),
2809 $imagesAvailable ? array(
2810 'image' => $wgLang->getImageFile( 'button-image' ),
2811 'id' => 'mw-editbutton-image',
2812 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
2813 'close' => ']]',
2814 'sample' => wfMessage( 'image_sample' )->text(),
2815 'tip' => wfMessage( 'image_tip' )->text(),
2816 'key' => 'D',
2817 ) : false,
2818 $imagesAvailable ? array(
2819 'image' => $wgLang->getImageFile( 'button-media' ),
2820 'id' => 'mw-editbutton-media',
2821 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
2822 'close' => ']]',
2823 'sample' => wfMessage( 'media_sample' )->text(),
2824 'tip' => wfMessage( 'media_tip' )->text(),
2825 'key' => 'M'
2826 ) : false,
2827 $wgUseTeX ? array(
2828 'image' => $wgLang->getImageFile( 'button-math' ),
2829 'id' => 'mw-editbutton-math',
2830 'open' => "<math>",
2831 'close' => "</math>",
2832 'sample' => wfMessage( 'math_sample' )->text(),
2833 'tip' => wfMessage( 'math_tip' )->text(),
2834 'key' => 'C'
2835 ) : false,
2836 array(
2837 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2838 'id' => 'mw-editbutton-nowiki',
2839 'open' => "<nowiki>",
2840 'close' => "</nowiki>",
2841 'sample' => wfMessage( 'nowiki_sample' )->text(),
2842 'tip' => wfMessage( 'nowiki_tip' )->text(),
2843 'key' => 'N'
2844 ),
2845 array(
2846 'image' => $wgLang->getImageFile( 'button-sig' ),
2847 'id' => 'mw-editbutton-signature',
2848 'open' => '--~~~~',
2849 'close' => '',
2850 'sample' => '',
2851 'tip' => wfMessage( 'sig_tip' )->text(),
2852 'key' => 'Y'
2853 ),
2854 array(
2855 'image' => $wgLang->getImageFile( 'button-hr' ),
2856 'id' => 'mw-editbutton-hr',
2857 'open' => "\n----\n",
2858 'close' => '',
2859 'sample' => '',
2860 'tip' => wfMessage( 'hr_tip' )->text(),
2861 'key' => 'R'
2862 )
2863 );
2864
2865 $script = 'mw.loader.using("mediawiki.action.edit", function() {';
2866 foreach ( $toolarray as $tool ) {
2867 if ( !$tool ) {
2868 continue;
2869 }
2870
2871 $params = array(
2872 $image = $wgStylePath . '/common/images/' . $tool['image'],
2873 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2874 // Older browsers show a "speedtip" type message only for ALT.
2875 // Ideally these should be different, realistically they
2876 // probably don't need to be.
2877 $tip = $tool['tip'],
2878 $open = $tool['open'],
2879 $close = $tool['close'],
2880 $sample = $tool['sample'],
2881 $cssId = $tool['id'],
2882 );
2883
2884 $script .= Xml::encodeJsCall( 'mw.toolbar.addButton', $params );
2885 }
2886
2887 // This used to be called on DOMReady from mediawiki.action.edit, which
2888 // ended up causing race conditions with the setup code above.
2889 $script .= "\n" .
2890 "// Create button bar\n" .
2891 "$(function() { mw.toolbar.init(); } );\n";
2892
2893 $script .= '});';
2894 $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
2895
2896 $toolbar = '<div id="toolbar"></div>';
2897
2898 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2899
2900 return $toolbar;
2901 }
2902
2903 /**
2904 * Returns an array of html code of the following checkboxes:
2905 * minor and watch
2906 *
2907 * @param $tabindex int Current tabindex
2908 * @param $checked Array of checkbox => bool, where bool indicates the checked
2909 * status of the checkbox
2910 *
2911 * @return array
2912 */
2913 public function getCheckboxes( &$tabindex, $checked ) {
2914 global $wgUser;
2915
2916 $checkboxes = array();
2917
2918 // don't show the minor edit checkbox if it's a new page or section
2919 if ( !$this->isNew ) {
2920 $checkboxes['minor'] = '';
2921 $minorLabel = wfMessage( 'minoredit' )->parse();
2922 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2923 $attribs = array(
2924 'tabindex' => ++$tabindex,
2925 'accesskey' => wfMessage( 'accesskey-minoredit' )->text(),
2926 'id' => 'wpMinoredit',
2927 );
2928 $checkboxes['minor'] =
2929 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2930 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
2931 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2932 ">{$minorLabel}</label>";
2933 }
2934 }
2935
2936 $watchLabel = wfMessage( 'watchthis' )->parse();
2937 $checkboxes['watch'] = '';
2938 if ( $wgUser->isLoggedIn() ) {
2939 $attribs = array(
2940 'tabindex' => ++$tabindex,
2941 'accesskey' => wfMessage( 'accesskey-watch' )->text(),
2942 'id' => 'wpWatchthis',
2943 );
2944 $checkboxes['watch'] =
2945 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2946 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
2947 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
2948 ">{$watchLabel}</label>";
2949 }
2950 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2951 return $checkboxes;
2952 }
2953
2954 /**
2955 * Returns an array of html code of the following buttons:
2956 * save, diff, preview and live
2957 *
2958 * @param $tabindex int Current tabindex
2959 *
2960 * @return array
2961 */
2962 public function getEditButtons( &$tabindex ) {
2963 $buttons = array();
2964
2965 $temp = array(
2966 'id' => 'wpSave',
2967 'name' => 'wpSave',
2968 'type' => 'submit',
2969 'tabindex' => ++$tabindex,
2970 'value' => wfMessage( 'savearticle' )->text(),
2971 'accesskey' => wfMessage( 'accesskey-save' )->text(),
2972 'title' => wfMessage( 'tooltip-save' )->text() . ' [' . wfMessage( 'accesskey-save' )->text() . ']',
2973 );
2974 $buttons['save'] = Xml::element( 'input', $temp, '' );
2975
2976 ++$tabindex; // use the same for preview and live preview
2977 $temp = array(
2978 'id' => 'wpPreview',
2979 'name' => 'wpPreview',
2980 'type' => 'submit',
2981 'tabindex' => $tabindex,
2982 'value' => wfMessage( 'showpreview' )->text(),
2983 'accesskey' => wfMessage( 'accesskey-preview' )->text(),
2984 'title' => wfMessage( 'tooltip-preview' )->text() . ' [' . wfMessage( 'accesskey-preview' )->text() . ']',
2985 );
2986 $buttons['preview'] = Xml::element( 'input', $temp, '' );
2987 $buttons['live'] = '';
2988
2989 $temp = array(
2990 'id' => 'wpDiff',
2991 'name' => 'wpDiff',
2992 'type' => 'submit',
2993 'tabindex' => ++$tabindex,
2994 'value' => wfMessage( 'showdiff' )->text(),
2995 'accesskey' => wfMessage( 'accesskey-diff' )->text(),
2996 'title' => wfMessage( 'tooltip-diff' )->text() . ' [' . wfMessage( 'accesskey-diff' )->text() . ']',
2997 );
2998 $buttons['diff'] = Xml::element( 'input', $temp, '' );
2999
3000 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
3001 return $buttons;
3002 }
3003
3004 /**
3005 * Output preview text only. This can be sucked into the edit page
3006 * via JavaScript, and saves the server time rendering the skin as
3007 * well as theoretically being more robust on the client (doesn't
3008 * disturb the edit box's undo history, won't eat your text on
3009 * failure, etc).
3010 *
3011 * @todo This doesn't include category or interlanguage links.
3012 * Would need to enhance it a bit, "<s>maybe wrap them in XML
3013 * or something...</s>" that might also require more skin
3014 * initialization, so check whether that's a problem.
3015 */
3016 function livePreview() {
3017 global $wgOut;
3018 $wgOut->disable();
3019 header( 'Content-type: text/xml; charset=utf-8' );
3020 header( 'Cache-control: no-cache' );
3021
3022 $previewText = $this->getPreviewText();
3023 #$categories = $skin->getCategoryLinks();
3024
3025 $s =
3026 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
3027 Xml::tags( 'livepreview', null,
3028 Xml::element( 'preview', null, $previewText )
3029 #. Xml::element( 'category', null, $categories )
3030 );
3031 echo $s;
3032 }
3033
3034 /**
3035 * Call the stock "user is blocked" page
3036 *
3037 * @deprecated in 1.19; throw an exception directly instead
3038 */
3039 function blockedPage() {
3040 wfDeprecated( __METHOD__, '1.19' );
3041 global $wgUser;
3042
3043 throw new UserBlockedError( $wgUser->getBlock() );
3044 }
3045
3046 /**
3047 * Produce the stock "please login to edit pages" page
3048 *
3049 * @deprecated in 1.19; throw an exception directly instead
3050 */
3051 function userNotLoggedInPage() {
3052 wfDeprecated( __METHOD__, '1.19' );
3053 throw new PermissionsError( 'edit' );
3054 }
3055
3056 /**
3057 * Show an error page saying to the user that he has insufficient permissions
3058 * to create a new page
3059 *
3060 * @deprecated in 1.19; throw an exception directly instead
3061 */
3062 function noCreatePermission() {
3063 wfDeprecated( __METHOD__, '1.19' );
3064 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
3065 throw new PermissionsError( $permission );
3066 }
3067
3068 /**
3069 * Creates a basic error page which informs the user that
3070 * they have attempted to edit a nonexistent section.
3071 */
3072 function noSuchSectionPage() {
3073 global $wgOut;
3074
3075 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
3076
3077 $res = wfMessage( 'nosuchsectiontext', $this->section )->parseAsBlock();
3078 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
3079 $wgOut->addHTML( $res );
3080
3081 $wgOut->returnToMain( false, $this->mTitle );
3082 }
3083
3084 /**
3085 * Produce the stock "your edit contains spam" page
3086 *
3087 * @param $match string Text which triggered one or more filters
3088 * @deprecated since 1.17 Use method spamPageWithContent() instead
3089 */
3090 static function spamPage( $match = false ) {
3091 wfDeprecated( __METHOD__, '1.17' );
3092
3093 global $wgOut, $wgTitle;
3094
3095 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3096
3097 $wgOut->addHTML( '<div id="spamprotected">' );
3098 $wgOut->addWikiMsg( 'spamprotectiontext' );
3099 if ( $match ) {
3100 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3101 }
3102 $wgOut->addHTML( '</div>' );
3103
3104 $wgOut->returnToMain( false, $wgTitle );
3105 }
3106
3107 /**
3108 * Show "your edit contains spam" page with your diff and text
3109 *
3110 * @param $match string|Array|bool Text (or array of texts) which triggered one or more filters
3111 */
3112 public function spamPageWithContent( $match = false ) {
3113 global $wgOut, $wgLang;
3114 $this->textbox2 = $this->textbox1;
3115
3116 if( is_array( $match ) ){
3117 $match = $wgLang->listToText( $match );
3118 }
3119 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
3120
3121 $wgOut->addHTML( '<div id="spamprotected">' );
3122 $wgOut->addWikiMsg( 'spamprotectiontext' );
3123 if ( $match ) {
3124 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
3125 }
3126 $wgOut->addHTML( '</div>' );
3127
3128 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
3129 $this->showDiff();
3130
3131 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
3132 $this->showTextbox2();
3133
3134 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
3135 }
3136
3137 /**
3138 * Format an anchor fragment as it would appear for a given section name
3139 * @param $text String
3140 * @return String
3141 * @private
3142 */
3143 function sectionAnchor( $text ) {
3144 global $wgParser;
3145 return $wgParser->guessSectionNameFromWikiText( $text );
3146 }
3147
3148 /**
3149 * Check if the browser is on a blacklist of user-agents known to
3150 * mangle UTF-8 data on form submission. Returns true if Unicode
3151 * should make it through, false if it's known to be a problem.
3152 * @return bool
3153 * @private
3154 */
3155 function checkUnicodeCompliantBrowser() {
3156 global $wgBrowserBlackList, $wgRequest;
3157
3158 $currentbrowser = $wgRequest->getHeader( 'User-Agent' );
3159 if ( $currentbrowser === false ) {
3160 // No User-Agent header sent? Trust it by default...
3161 return true;
3162 }
3163
3164 foreach ( $wgBrowserBlackList as $browser ) {
3165 if ( preg_match( $browser, $currentbrowser ) ) {
3166 return false;
3167 }
3168 }
3169 return true;
3170 }
3171
3172 /**
3173 * Filter an input field through a Unicode de-armoring process if it
3174 * came from an old browser with known broken Unicode editing issues.
3175 *
3176 * @param $request WebRequest
3177 * @param $field String
3178 * @return String
3179 * @private
3180 */
3181 function safeUnicodeInput( $request, $field ) {
3182 $text = rtrim( $request->getText( $field ) );
3183 return $request->getBool( 'safemode' )
3184 ? $this->unmakesafe( $text )
3185 : $text;
3186 }
3187
3188 /**
3189 * @param $request WebRequest
3190 * @param $text string
3191 * @return string
3192 */
3193 function safeUnicodeText( $request, $text ) {
3194 $text = rtrim( $text );
3195 return $request->getBool( 'safemode' )
3196 ? $this->unmakesafe( $text )
3197 : $text;
3198 }
3199
3200 /**
3201 * Filter an output field through a Unicode armoring process if it is
3202 * going to an old browser with known broken Unicode editing issues.
3203 *
3204 * @param $text String
3205 * @return String
3206 * @private
3207 */
3208 function safeUnicodeOutput( $text ) {
3209 global $wgContLang;
3210 $codedText = $wgContLang->recodeForEdit( $text );
3211 return $this->checkUnicodeCompliantBrowser()
3212 ? $codedText
3213 : $this->makesafe( $codedText );
3214 }
3215
3216 /**
3217 * A number of web browsers are known to corrupt non-ASCII characters
3218 * in a UTF-8 text editing environment. To protect against this,
3219 * detected browsers will be served an armored version of the text,
3220 * with non-ASCII chars converted to numeric HTML character references.
3221 *
3222 * Preexisting such character references will have a 0 added to them
3223 * to ensure that round-trips do not alter the original data.
3224 *
3225 * @param $invalue String
3226 * @return String
3227 * @private
3228 */
3229 function makesafe( $invalue ) {
3230 // Armor existing references for reversability.
3231 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
3232
3233 $bytesleft = 0;
3234 $result = "";
3235 $working = 0;
3236 for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
3237 $bytevalue = ord( $invalue[$i] );
3238 if ( $bytevalue <= 0x7F ) { // 0xxx xxxx
3239 $result .= chr( $bytevalue );
3240 $bytesleft = 0;
3241 } elseif ( $bytevalue <= 0xBF ) { // 10xx xxxx
3242 $working = $working << 6;
3243 $working += ( $bytevalue & 0x3F );
3244 $bytesleft--;
3245 if ( $bytesleft <= 0 ) {
3246 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
3247 }
3248 } elseif ( $bytevalue <= 0xDF ) { // 110x xxxx
3249 $working = $bytevalue & 0x1F;
3250 $bytesleft = 1;
3251 } elseif ( $bytevalue <= 0xEF ) { // 1110 xxxx
3252 $working = $bytevalue & 0x0F;
3253 $bytesleft = 2;
3254 } else { // 1111 0xxx
3255 $working = $bytevalue & 0x07;
3256 $bytesleft = 3;
3257 }
3258 }
3259 return $result;
3260 }
3261
3262 /**
3263 * Reverse the previously applied transliteration of non-ASCII characters
3264 * back to UTF-8. Used to protect data from corruption by broken web browsers
3265 * as listed in $wgBrowserBlackList.
3266 *
3267 * @param $invalue String
3268 * @return String
3269 * @private
3270 */
3271 function unmakesafe( $invalue ) {
3272 $result = "";
3273 for ( $i = 0; $i < strlen( $invalue ); $i++ ) {
3274 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i + 3] != '0' ) ) {
3275 $i += 3;
3276 $hexstring = "";
3277 do {
3278 $hexstring .= $invalue[$i];
3279 $i++;
3280 } while ( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
3281
3282 // Do some sanity checks. These aren't needed for reversability,
3283 // but should help keep the breakage down if the editor
3284 // breaks one of the entities whilst editing.
3285 if ( ( substr( $invalue, $i, 1 ) == ";" ) and ( strlen( $hexstring ) <= 6 ) ) {
3286 $codepoint = hexdec( $hexstring );
3287 $result .= codepointToUtf8( $codepoint );
3288 } else {
3289 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
3290 }
3291 } else {
3292 $result .= substr( $invalue, $i, 1 );
3293 }
3294 }
3295 // reverse the transform that we made for reversability reasons.
3296 return strtr( $result, array( "&#x0" => "&#x" ) );
3297 }
3298 }