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