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