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