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