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