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