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