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