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