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