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