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