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