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