Followup r104274, r104676. Fix the bug that broke fr. Forgot to rawurldecode path...
[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 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $resultDetails['sectionanchor'] );
871 return false;
872
873 case self::AS_SUCCESS_UPDATE:
874 $extraQuery = '';
875 $sectionanchor = $resultDetails['sectionanchor'];
876
877 // Give extensions a chance to modify URL query on update
878 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle, &$sectionanchor, &$extraQuery ) );
879
880 if ( $resultDetails['redirect'] ) {
881 if ( $extraQuery == '' ) {
882 $extraQuery = 'redirect=no';
883 } else {
884 $extraQuery = 'redirect=no&' . $extraQuery;
885 }
886 }
887 $wgOut->redirect( $this->mTitle->getFullURL( $extraQuery ) . $sectionanchor );
888 return false;
889
890 case self::AS_BLANK_ARTICLE:
891 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
892 return false;
893
894 case self::AS_SPAM_ERROR:
895 $this->spamPageWithContent( $resultDetails['spam'] );
896 return false;
897
898 case self::AS_BLOCKED_PAGE_FOR_USER:
899 throw new UserBlockedError( $wgUser->mBlock );
900
901 case self::AS_IMAGE_REDIRECT_ANON:
902 case self::AS_IMAGE_REDIRECT_LOGGED:
903 throw new PermissionsError( 'upload' );
904
905 case self::AS_READ_ONLY_PAGE_ANON:
906 case self::AS_READ_ONLY_PAGE_LOGGED:
907 throw new PermissionsError( 'edit' );
908
909 case self::AS_READ_ONLY_PAGE:
910 throw new ReadOnlyError;
911
912 case self::AS_RATE_LIMITED:
913 throw new ThrottledError();
914
915 case self::AS_NO_CREATE_PERMISSION:
916 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
917 throw new PermissionsError( $permission );
918
919 }
920 return false;
921 }
922
923 /**
924 * Attempt submission (no UI)
925 *
926 * @param $result
927 * @param $bot bool
928 *
929 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
930 *
931 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
932 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
933 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
934 */
935 function internalAttemptSave( &$result, $bot = false ) {
936 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
937 global $wgMaxArticleSize;
938
939 $status = Status::newGood();
940
941 wfProfileIn( __METHOD__ );
942 wfProfileIn( __METHOD__ . '-checks' );
943
944 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
945 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
946 $status->fatal( 'hookaborted' );
947 $status->value = self::AS_HOOK_ERROR;
948 wfProfileOut( __METHOD__ . '-checks' );
949 wfProfileOut( __METHOD__ );
950 return $status;
951 }
952
953 # Check image redirect
954 if ( $this->mTitle->getNamespace() == NS_FILE &&
955 Title::newFromRedirect( $this->textbox1 ) instanceof Title &&
956 !$wgUser->isAllowed( 'upload' ) ) {
957 $code = $wgUser->isAnon() ? self::AS_IMAGE_REDIRECT_ANON : self::AS_IMAGE_REDIRECT_LOGGED;
958 $status->setResult( false, $code );
959
960 wfProfileOut( __METHOD__ . '-checks' );
961 wfProfileOut( __METHOD__ );
962
963 return $status;
964 }
965
966 # Check for spam
967 $match = self::matchSummarySpamRegex( $this->summary );
968 if ( $match === false ) {
969 $match = self::matchSpamRegex( $this->textbox1 );
970 }
971 if ( $match !== false ) {
972 $result['spam'] = $match;
973 $ip = $wgRequest->getIP();
974 $pdbk = $this->mTitle->getPrefixedDBkey();
975 $match = str_replace( "\n", '', $match );
976 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
977 $status->fatal( 'spamprotectionmatch', $match );
978 $status->value = self::AS_SPAM_ERROR;
979 wfProfileOut( __METHOD__ . '-checks' );
980 wfProfileOut( __METHOD__ );
981 return $status;
982 }
983 if ( $wgFilterCallback && is_callable( $wgFilterCallback ) && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section, $this->hookError, $this->summary ) ) {
984 # Error messages or other handling should be performed by the filter function
985 $status->setResult( false, self::AS_FILTERING );
986 wfProfileOut( __METHOD__ . '-checks' );
987 wfProfileOut( __METHOD__ );
988 return $status;
989 }
990 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) ) ) {
991 # Error messages etc. could be handled within the hook...
992 $status->fatal( 'hookaborted' );
993 $status->value = self::AS_HOOK_ERROR;
994 wfProfileOut( __METHOD__ . '-checks' );
995 wfProfileOut( __METHOD__ );
996 return $status;
997 } elseif ( $this->hookError != '' ) {
998 # ...or the hook could be expecting us to produce an error
999 $status->fatal( 'hookaborted' );
1000 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1001 wfProfileOut( __METHOD__ . '-checks' );
1002 wfProfileOut( __METHOD__ );
1003 return $status;
1004 }
1005
1006 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
1007 // Auto-block user's IP if the account was "hard" blocked
1008 $wgUser->spreadAnyEditBlock();
1009 # Check block state against master, thus 'false'.
1010 $status->setResult( false, self::AS_BLOCKED_PAGE_FOR_USER );
1011 wfProfileOut( __METHOD__ . '-checks' );
1012 wfProfileOut( __METHOD__ );
1013 return $status;
1014 }
1015
1016 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1017 if ( $this->kblength > $wgMaxArticleSize ) {
1018 // Error will be displayed by showEditForm()
1019 $this->tooBig = true;
1020 $status->setResult( false, self::AS_CONTENT_TOO_BIG );
1021 wfProfileOut( __METHOD__ . '-checks' );
1022 wfProfileOut( __METHOD__ );
1023 return $status;
1024 }
1025
1026 if ( !$wgUser->isAllowed( 'edit' ) ) {
1027 if ( $wgUser->isAnon() ) {
1028 $status->setResult( false, self::AS_READ_ONLY_PAGE_ANON );
1029 wfProfileOut( __METHOD__ . '-checks' );
1030 wfProfileOut( __METHOD__ );
1031 return $status;
1032 } else {
1033 $status->fatal( 'readonlytext' );
1034 $status->value = self::AS_READ_ONLY_PAGE_LOGGED;
1035 wfProfileOut( __METHOD__ . '-checks' );
1036 wfProfileOut( __METHOD__ );
1037 return $status;
1038 }
1039 }
1040
1041 if ( wfReadOnly() ) {
1042 $status->fatal( 'readonlytext' );
1043 $status->value = self::AS_READ_ONLY_PAGE;
1044 wfProfileOut( __METHOD__ . '-checks' );
1045 wfProfileOut( __METHOD__ );
1046 return $status;
1047 }
1048 if ( $wgUser->pingLimiter() ) {
1049 $status->fatal( 'actionthrottledtext' );
1050 $status->value = self::AS_RATE_LIMITED;
1051 wfProfileOut( __METHOD__ . '-checks' );
1052 wfProfileOut( __METHOD__ );
1053 return $status;
1054 }
1055
1056 # If the article has been deleted while editing, don't save it without
1057 # confirmation
1058 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
1059 $status->setResult( false, self::AS_ARTICLE_WAS_DELETED );
1060 wfProfileOut( __METHOD__ . '-checks' );
1061 wfProfileOut( __METHOD__ );
1062 return $status;
1063 }
1064
1065 wfProfileOut( __METHOD__ . '-checks' );
1066
1067 # If article is new, insert it.
1068 $aid = $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
1069 $new = ( $aid == 0 );
1070
1071 if ( $new ) {
1072 // Late check for create permission, just in case *PARANOIA*
1073 if ( !$this->mTitle->userCan( 'create' ) ) {
1074 $status->fatal( 'nocreatetext' );
1075 $status->value = self::AS_NO_CREATE_PERMISSION;
1076 wfDebug( __METHOD__ . ": no create permission\n" );
1077 wfProfileOut( __METHOD__ );
1078 return $status;
1079 }
1080
1081 # Don't save a new article if it's blank.
1082 if ( $this->textbox1 == '' ) {
1083 $status->setResult( false, self::AS_BLANK_ARTICLE );
1084 wfProfileOut( __METHOD__ );
1085 return $status;
1086 }
1087
1088 // Run post-section-merge edit filter
1089 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1, &$this->hookError, $this->summary ) ) ) {
1090 # Error messages etc. could be handled within the hook...
1091 $status->fatal( 'hookaborted' );
1092 $status->value = self::AS_HOOK_ERROR;
1093 wfProfileOut( __METHOD__ );
1094 return $status;
1095 } elseif ( $this->hookError != '' ) {
1096 # ...or the hook could be expecting us to produce an error
1097 $status->fatal( 'hookaborted' );
1098 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1099 wfProfileOut( __METHOD__ );
1100 return $status;
1101 }
1102
1103 # Handle the user preference to force summaries here. Check if it's not a redirect.
1104 if ( !$this->allowBlankSummary && !Title::newFromRedirect( $this->textbox1 ) ) {
1105 if ( md5( $this->summary ) == $this->autoSumm ) {
1106 $this->missingSummary = true;
1107 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1108 $status->value = self::AS_SUMMARY_NEEDED;
1109 wfProfileOut( __METHOD__ );
1110 return $status;
1111 }
1112 }
1113
1114 $text = $this->textbox1;
1115 $result['sectionanchor'] == '';
1116 if ( $this->section == 'new' && $this->summary != '' ) {
1117 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary ) . "\n\n" . $text;
1118
1119 # Jump to the new section
1120 $result['sectionanchor'] = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1121
1122 # This is a new section, so create a link to the new section
1123 # in the revision summary.
1124 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1125 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
1126 }
1127
1128 $status->value = self::AS_SUCCESS_NEW_ARTICLE;
1129
1130 } else {
1131
1132 # Article exists. Check for edit conflict.
1133
1134 $this->mArticle->clear(); # Force reload of dates, etc.
1135
1136 wfDebug( "timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n" );
1137
1138 if ( $this->mArticle->getTimestamp() != $this->edittime ) {
1139 $this->isConflict = true;
1140 if ( $this->section == 'new' ) {
1141 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
1142 $this->mArticle->getComment() == $this->summary ) {
1143 // Probably a duplicate submission of a new comment.
1144 // This can happen when squid resends a request after
1145 // a timeout but the first one actually went through.
1146 wfDebug( __METHOD__ . ": duplicate new section submission; trigger edit conflict!\n" );
1147 } else {
1148 // New comment; suppress conflict.
1149 $this->isConflict = false;
1150 wfDebug( __METHOD__ .": conflict suppressed; new section\n" );
1151 }
1152 } elseif ( $this->section == '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime ) ) {
1153 # Suppress edit conflict with self, except for section edits where merging is required.
1154 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
1155 $this->isConflict = false;
1156 }
1157 }
1158
1159 if ( $this->isConflict ) {
1160 wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
1161 $this->mArticle->getTimestamp() . "')\n" );
1162 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime );
1163 } else {
1164 wfDebug( __METHOD__ . ": getting section '$this->section'\n" );
1165 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary );
1166 }
1167 if ( is_null( $text ) ) {
1168 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1169 $this->isConflict = true;
1170 $text = $this->textbox1; // do not try to merge here!
1171 } elseif ( $this->isConflict ) {
1172 # Attempt merge
1173 if ( $this->mergeChangesInto( $text ) ) {
1174 // Successful merge! Maybe we should tell the user the good news?
1175 $this->isConflict = false;
1176 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1177 } else {
1178 $this->section = '';
1179 $this->textbox1 = $text;
1180 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1181 }
1182 }
1183
1184 if ( $this->isConflict ) {
1185 $status->setResult( false, self::AS_CONFLICT_DETECTED );
1186 wfProfileOut( __METHOD__ );
1187 return $status;
1188 }
1189
1190 // Run post-section-merge edit filter
1191 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError, $this->summary ) ) ) {
1192 # Error messages etc. could be handled within the hook...
1193 $status->fatal( 'hookaborted' );
1194 $status->value = self::AS_HOOK_ERROR;
1195 wfProfileOut( __METHOD__ );
1196 return $status;
1197 } elseif ( $this->hookError != '' ) {
1198 # ...or the hook could be expecting us to produce an error
1199 $status->fatal( 'hookaborted' );
1200 $status->value = self::AS_HOOK_ERROR_EXPECTED;
1201 wfProfileOut( __METHOD__ );
1202 return $status;
1203 }
1204
1205 # Handle the user preference to force summaries here, but not for null edits
1206 if ( $this->section != 'new' && !$this->allowBlankSummary
1207 && 0 != strcmp( $this->mArticle->getContent(), $text )
1208 && !Title::newFromRedirect( $text ) ) # check if it's not a redirect
1209 {
1210 if ( md5( $this->summary ) == $this->autoSumm ) {
1211 $this->missingSummary = true;
1212 $status->fatal( 'missingsummary' );
1213 $status->value = self::AS_SUMMARY_NEEDED;
1214 wfProfileOut( __METHOD__ );
1215 return $status;
1216 }
1217 }
1218
1219 # And a similar thing for new sections
1220 if ( $this->section == 'new' && !$this->allowBlankSummary ) {
1221 if ( trim( $this->summary ) == '' ) {
1222 $this->missingSummary = true;
1223 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1224 $status->value = self::AS_SUMMARY_NEEDED;
1225 wfProfileOut( __METHOD__ );
1226 return $status;
1227 }
1228 }
1229
1230 # All's well
1231 wfProfileIn( __METHOD__ . '-sectionanchor' );
1232 $sectionanchor = '';
1233 if ( $this->section == 'new' ) {
1234 if ( $this->textbox1 == '' ) {
1235 $this->missingComment = true;
1236 $status->fatal( 'missingcommenttext' );
1237 $status->value = self::AS_TEXTBOX_EMPTY;
1238 wfProfileOut( __METHOD__ . '-sectionanchor' );
1239 wfProfileOut( __METHOD__ );
1240 return $status;
1241 }
1242 if ( $this->summary != '' ) {
1243 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary );
1244 # This is a new section, so create a link to the new section
1245 # in the revision summary.
1246 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1247 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
1248 }
1249 } elseif ( $this->section != '' ) {
1250 # Try to get a section anchor from the section source, redirect to edited section if header found
1251 # XXX: might be better to integrate this into Article::replaceSection
1252 # for duplicate heading checking and maybe parsing
1253 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1254 # we can't deal with anchors, includes, html etc in the header for now,
1255 # headline would need to be parsed to improve this
1256 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1257 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1258 }
1259 }
1260 $result['sectionanchor'] = $sectionanchor;
1261 wfProfileOut( __METHOD__ . '-sectionanchor' );
1262
1263 // Save errors may fall down to the edit form, but we've now
1264 // merged the section into full text. Clear the section field
1265 // so that later submission of conflict forms won't try to
1266 // replace that into a duplicated mess.
1267 $this->textbox1 = $text;
1268 $this->section = '';
1269
1270 $status->value = self::AS_SUCCESS_UPDATE;
1271 }
1272
1273 // Check for length errors again now that the section is merged in
1274 $this->kblength = (int)( strlen( $text ) / 1024 );
1275 if ( $this->kblength > $wgMaxArticleSize ) {
1276 $this->tooBig = true;
1277 $status->setResult( false, self::AS_MAX_ARTICLE_SIZE_EXCEEDED );
1278 wfProfileOut( __METHOD__ );
1279 return $status;
1280 }
1281
1282 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1283 ( $new ? EDIT_NEW : EDIT_UPDATE ) |
1284 ( ( $this->minoredit && !$this->isNew ) ? EDIT_MINOR : 0 ) |
1285 ( $bot ? EDIT_FORCE_BOT : 0 );
1286
1287 $doEditStatus = $this->mArticle->doEdit( $text, $this->summary, $flags );
1288
1289 if ( $doEditStatus->isOK() ) {
1290 $result['redirect'] = Title::newFromRedirect( $text ) !== null;
1291 $this->commitWatch();
1292 wfProfileOut( __METHOD__ );
1293 return $status;
1294 } else {
1295 $this->isConflict = true;
1296 $doEditStatus->value = self::AS_END; // Destroys data doEdit() put in $status->value but who cares
1297 wfProfileOut( __METHOD__ );
1298 return $doEditStatus;
1299 }
1300 }
1301
1302 /**
1303 * Commit the change of watch status
1304 */
1305 protected function commitWatch() {
1306 global $wgUser;
1307 if ( $this->watchthis xor $this->mTitle->userIsWatching() ) {
1308 $dbw = wfGetDB( DB_MASTER );
1309 $dbw->begin();
1310 if ( $this->watchthis ) {
1311 WatchAction::doWatch( $this->mTitle, $wgUser );
1312 } else {
1313 WatchAction::doUnwatch( $this->mTitle, $wgUser );
1314 }
1315 $dbw->commit();
1316 }
1317 }
1318
1319 /**
1320 * Check if no edits were made by other users since
1321 * the time a user started editing the page. Limit to
1322 * 50 revisions for the sake of performance.
1323 *
1324 * @param $id int
1325 * @param $edittime string
1326 *
1327 * @return bool
1328 */
1329 protected function userWasLastToEdit( $id, $edittime ) {
1330 if( !$id ) return false;
1331 $dbw = wfGetDB( DB_MASTER );
1332 $res = $dbw->select( 'revision',
1333 'rev_user',
1334 array(
1335 'rev_page' => $this->mArticle->getId(),
1336 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1337 ),
1338 __METHOD__,
1339 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1340 foreach ( $res as $row ) {
1341 if( $row->rev_user != $id ) {
1342 return false;
1343 }
1344 }
1345 return true;
1346 }
1347
1348 /**
1349 * @private
1350 * @todo document
1351 *
1352 * @parma $editText string
1353 *
1354 * @return bool
1355 */
1356 function mergeChangesInto( &$editText ){
1357 wfProfileIn( __METHOD__ );
1358
1359 $db = wfGetDB( DB_MASTER );
1360
1361 // This is the revision the editor started from
1362 $baseRevision = $this->getBaseRevision();
1363 if ( is_null( $baseRevision ) ) {
1364 wfProfileOut( __METHOD__ );
1365 return false;
1366 }
1367 $baseText = $baseRevision->getText();
1368
1369 // The current state, we want to merge updates into it
1370 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
1371 if ( is_null( $currentRevision ) ) {
1372 wfProfileOut( __METHOD__ );
1373 return false;
1374 }
1375 $currentText = $currentRevision->getText();
1376
1377 $result = '';
1378 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1379 $editText = $result;
1380 wfProfileOut( __METHOD__ );
1381 return true;
1382 } else {
1383 wfProfileOut( __METHOD__ );
1384 return false;
1385 }
1386 }
1387
1388 /**
1389 * @return Revision
1390 */
1391 function getBaseRevision() {
1392 if ( !$this->mBaseRevision ) {
1393 $db = wfGetDB( DB_MASTER );
1394 $baseRevision = Revision::loadFromTimestamp(
1395 $db, $this->mTitle, $this->edittime );
1396 return $this->mBaseRevision = $baseRevision;
1397 } else {
1398 return $this->mBaseRevision;
1399 }
1400 }
1401
1402 /**
1403 * Check given input text against $wgSpamRegex, and return the text of the first match.
1404 *
1405 * @param $text string
1406 *
1407 * @return string|false matching string or false
1408 */
1409 public static function matchSpamRegex( $text ) {
1410 global $wgSpamRegex;
1411 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1412 $regexes = (array)$wgSpamRegex;
1413 return self::matchSpamRegexInternal( $text, $regexes );
1414 }
1415
1416 /**
1417 * Check given input text against $wgSpamRegex, and return the text of the first match.
1418 *
1419 * @parma $text string
1420 *
1421 * @return string|false matching string or false
1422 */
1423 public static function matchSummarySpamRegex( $text ) {
1424 global $wgSummarySpamRegex;
1425 $regexes = (array)$wgSummarySpamRegex;
1426 return self::matchSpamRegexInternal( $text, $regexes );
1427 }
1428
1429 /**
1430 * @param $text string
1431 * @param $regexes array
1432 * @return bool|string
1433 */
1434 protected static function matchSpamRegexInternal( $text, $regexes ) {
1435 foreach( $regexes as $regex ) {
1436 $matches = array();
1437 if( preg_match( $regex, $text, $matches ) ) {
1438 return $matches[0];
1439 }
1440 }
1441 return false;
1442 }
1443
1444 function setHeaders() {
1445 global $wgOut;
1446 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1447 if ( $this->isConflict ) {
1448 $wgOut->setPageTitle( wfMessage( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1449 } elseif ( $this->section != '' ) {
1450 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
1451 $wgOut->setPageTitle( wfMessage( $msg, $this->getContextTitle()->getPrefixedText() ) );
1452 } else {
1453 # Use the title defined by DISPLAYTITLE magic word when present
1454 if ( isset( $this->mParserOutput )
1455 && ( $dt = $this->mParserOutput->getDisplayTitle() ) !== false ) {
1456 $title = $dt;
1457 } else {
1458 $title = $this->getContextTitle()->getPrefixedText();
1459 }
1460 $wgOut->setPageTitle( wfMessage( 'editing', $title ) );
1461 }
1462 }
1463
1464 /**
1465 * Show all applicable editing introductions
1466 */
1467 protected function showIntro() {
1468 global $wgOut, $wgUser;
1469 if ( $this->suppressIntro ) {
1470 return;
1471 }
1472
1473 $namespace = $this->mTitle->getNamespace();
1474
1475 if ( $namespace == NS_MEDIAWIKI ) {
1476 # Show a warning if editing an interface message
1477 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
1478 }
1479
1480 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
1481 # Show log extract when the user is currently blocked
1482 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
1483 $parts = explode( '/', $this->mTitle->getText(), 2 );
1484 $username = $parts[0];
1485 $user = User::newFromName( $username, false /* allow IP users*/ );
1486 $ip = User::isIP( $username );
1487 if ( !($user && $user->isLoggedIn()) && !$ip ) { # User does not exist
1488 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
1489 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
1490 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1491 LogEventsList::showLogExtract(
1492 $wgOut,
1493 'block',
1494 $user->getUserPage(),
1495 '',
1496 array(
1497 'lim' => 1,
1498 'showIfEmpty' => false,
1499 'msgKey' => array(
1500 'blocked-notice-logextract',
1501 $user->getName() # Support GENDER in notice
1502 )
1503 )
1504 );
1505 }
1506 }
1507 # Try to add a custom edit intro, or use the standard one if this is not possible.
1508 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
1509 if ( $wgUser->isLoggedIn() ) {
1510 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
1511 } else {
1512 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
1513 }
1514 }
1515 # Give a notice if the user is editing a deleted/moved page...
1516 if ( !$this->mTitle->exists() ) {
1517 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle,
1518 '', array( 'lim' => 10,
1519 'conds' => array( "log_action != 'revision'" ),
1520 'showIfEmpty' => false,
1521 'msgKey' => array( 'recreate-moveddeleted-warn') )
1522 );
1523 }
1524 }
1525
1526 /**
1527 * Attempt to show a custom editing introduction, if supplied
1528 *
1529 * @return bool
1530 */
1531 protected function showCustomIntro() {
1532 if ( $this->editintro ) {
1533 $title = Title::newFromText( $this->editintro );
1534 if ( $title instanceof Title && $title->exists() && $title->userCanRead() ) {
1535 global $wgOut;
1536 // Added using template syntax, to take <noinclude>'s into account.
1537 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle );
1538 return true;
1539 } else {
1540 return false;
1541 }
1542 } else {
1543 return false;
1544 }
1545 }
1546
1547 /**
1548 * Send the edit form and related headers to $wgOut
1549 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1550 * during form output near the top, for captchas and the like.
1551 */
1552 function showEditForm( $formCallback = null ) {
1553 global $wgOut, $wgUser;
1554
1555 wfProfileIn( __METHOD__ );
1556
1557 #need to parse the preview early so that we know which templates are used,
1558 #otherwise users with "show preview after edit box" will get a blank list
1559 #we parse this near the beginning so that setHeaders can do the title
1560 #setting work instead of leaving it in getPreviewText
1561 $previewOutput = '';
1562 if ( $this->formtype == 'preview' ) {
1563 $previewOutput = $this->getPreviewText();
1564 }
1565
1566 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1567
1568 $this->setHeaders();
1569
1570 # Enabled article-related sidebar, toplinks, etc.
1571 $wgOut->setArticleRelated( true );
1572
1573 if ( $this->showHeader() === false ) {
1574 wfProfileOut( __METHOD__ );
1575 return;
1576 }
1577
1578 $action = htmlspecialchars( $this->getActionURL( $this->getContextTitle() ) );
1579
1580 if ( $wgUser->getOption( 'showtoolbar' ) and !$this->isCssJsSubpage ) {
1581 # prepare toolbar for edit buttons
1582 $toolbar = EditPage::getEditToolbar();
1583 } else {
1584 $toolbar = '';
1585 }
1586
1587
1588 $wgOut->addHTML( $this->editFormPageTop );
1589
1590 if ( $wgUser->getOption( 'previewontop' ) ) {
1591 $this->displayPreviewArea( $previewOutput, true );
1592 }
1593
1594 $wgOut->addHTML( $this->editFormTextTop );
1595
1596 $templates = $this->getTemplates();
1597 $formattedtemplates = Linker::formatTemplates( $templates, $this->preview, $this->section != '');
1598
1599 $hiddencats = $this->mArticle->getHiddenCategories();
1600 $formattedhiddencats = Linker::formatHiddenCategories( $hiddencats );
1601
1602 if ( $this->wasDeletedSinceLastEdit() && 'save' != $this->formtype ) {
1603 $wgOut->wrapWikiMsg(
1604 "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1605 'deletedwhileediting' );
1606 } elseif ( $this->wasDeletedSinceLastEdit() ) {
1607 // Hide the toolbar and edit area, user can click preview to get it back
1608 // Add an confirmation checkbox and explanation.
1609 $toolbar = '';
1610 // @todo move this to a cleaner conditional instead of blanking a variable
1611 }
1612 $wgOut->addHTML( <<<HTML
1613 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1614 HTML
1615 );
1616
1617 if ( is_callable( $formCallback ) ) {
1618 call_user_func_array( $formCallback, array( &$wgOut ) );
1619 }
1620
1621 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1622
1623 // Put these up at the top to ensure they aren't lost on early form submission
1624 $this->showFormBeforeText();
1625
1626 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
1627 $username = $this->lastDelete->user_name;
1628 $comment = $this->lastDelete->log_comment;
1629
1630 // It is better to not parse the comment at all than to have templates expanded in the middle
1631 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1632 $key = $comment === ''
1633 ? 'confirmrecreate-noreason'
1634 : 'confirmrecreate';
1635 $wgOut->addHTML(
1636 '<div class="mw-confirm-recreate">' .
1637 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1638 Xml::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1639 array( 'title' => Linker::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1640 ) .
1641 '</div>'
1642 );
1643 }
1644
1645 # If a blank edit summary was previously provided, and the appropriate
1646 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1647 # user being bounced back more than once in the event that a summary
1648 # is not required.
1649 #####
1650 # For a bit more sophisticated detection of blank summaries, hash the
1651 # automatic one and pass that in the hidden field wpAutoSummary.
1652 if ( $this->missingSummary ||
1653 ( $this->section == 'new' && $this->nosummary ) )
1654 $wgOut->addHTML( Html::hidden( 'wpIgnoreBlankSummary', true ) );
1655 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1656 $wgOut->addHTML( Html::hidden( 'wpAutoSummary', $autosumm ) );
1657
1658 $wgOut->addHTML( Html::hidden( 'oldid', $this->mArticle->getOldID() ) );
1659
1660 if ( $this->section == 'new' ) {
1661 $this->showSummaryInput( true, $this->summary );
1662 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
1663 }
1664
1665 $wgOut->addHTML( $this->editFormTextBeforeContent );
1666
1667 $wgOut->addHTML( $toolbar );
1668
1669 if ( $this->isConflict ) {
1670 // In an edit conflict bypass the overrideable content form method
1671 // and fallback to the raw wpTextbox1 since editconflicts can't be
1672 // resolved between page source edits and custom ui edits using the
1673 // custom edit ui.
1674 $this->showTextbox1( null, $this->getContent() );
1675 } else {
1676 $this->showContentForm();
1677 }
1678
1679 $wgOut->addHTML( $this->editFormTextAfterContent );
1680
1681 $wgOut->addWikiText( $this->getCopywarn() );
1682 if ( isset($this->editFormTextAfterWarn) && $this->editFormTextAfterWarn !== '' )
1683 $wgOut->addHTML( $this->editFormTextAfterWarn );
1684
1685 $this->showStandardInputs();
1686
1687 $this->showFormAfterText();
1688
1689 $this->showTosSummary();
1690 $this->showEditTools();
1691
1692 $wgOut->addHTML( <<<HTML
1693 {$this->editFormTextAfterTools}
1694 <div class='templatesUsed'>
1695 {$formattedtemplates}
1696 </div>
1697 <div class='hiddencats'>
1698 {$formattedhiddencats}
1699 </div>
1700 HTML
1701 );
1702
1703 if ( $this->isConflict )
1704 $this->showConflict();
1705
1706 $wgOut->addHTML( $this->editFormTextBottom );
1707 $wgOut->addHTML( "</form>\n" );
1708 if ( !$wgUser->getOption( 'previewontop' ) ) {
1709 $this->displayPreviewArea( $previewOutput, false );
1710 }
1711
1712 wfProfileOut( __METHOD__ );
1713 }
1714
1715 protected function showHeader() {
1716 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1717 if ( $this->isConflict ) {
1718 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1719 $this->edittime = $this->mArticle->getTimestamp();
1720 } else {
1721 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
1722 // We use $this->section to much before this and getVal('wgSection') directly in other places
1723 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1724 // Someone is welcome to try refactoring though
1725 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1726 return false;
1727 }
1728
1729 if ( $this->section != '' && $this->section != 'new' ) {
1730 $matches = array();
1731 if ( !$this->summary && !$this->preview && !$this->diff ) {
1732 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1, $matches );
1733 if ( !empty( $matches[2] ) ) {
1734 global $wgParser;
1735 $this->summary = "/* " .
1736 $wgParser->stripSectionName(trim($matches[2])) .
1737 " */ ";
1738 }
1739 }
1740 }
1741
1742 if ( $this->missingComment ) {
1743 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1744 }
1745
1746 if ( $this->missingSummary && $this->section != 'new' ) {
1747 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1748 }
1749
1750 if ( $this->missingSummary && $this->section == 'new' ) {
1751 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1752 }
1753
1754 if ( $this->hookError !== '' ) {
1755 $wgOut->addWikiText( $this->hookError );
1756 }
1757
1758 if ( !$this->checkUnicodeCompliantBrowser() ) {
1759 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1760 }
1761
1762 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
1763 // Let sysop know that this will make private content public if saved
1764
1765 if ( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1766 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1767 } elseif ( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1768 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1769 }
1770
1771 if ( !$this->mArticle->mRevision->isCurrent() ) {
1772 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
1773 $wgOut->addWikiMsg( 'editingold' );
1774 }
1775 }
1776 }
1777
1778 if ( wfReadOnly() ) {
1779 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1780 } elseif ( $wgUser->isAnon() ) {
1781 if ( $this->formtype != 'preview' ) {
1782 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
1783 } else {
1784 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
1785 }
1786 } else {
1787 if ( $this->isCssJsSubpage ) {
1788 # Check the skin exists
1789 if ( $this->isWrongCaseCssJsPage ) {
1790 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
1791 }
1792 if ( $this->formtype !== 'preview' ) {
1793 if ( $this->isCssSubpage )
1794 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
1795 if ( $this->isJsSubpage )
1796 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
1797 }
1798 }
1799 }
1800
1801 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
1802 # Is the title semi-protected?
1803 if ( $this->mTitle->isSemiProtected() ) {
1804 $noticeMsg = 'semiprotectedpagewarning';
1805 } else {
1806 # Then it must be protected based on static groups (regular)
1807 $noticeMsg = 'protectedpagewarning';
1808 }
1809 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
1810 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1811 }
1812 if ( $this->mTitle->isCascadeProtected() ) {
1813 # Is this page under cascading protection from some source pages?
1814 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1815 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
1816 $cascadeSourcesCount = count( $cascadeSources );
1817 if ( $cascadeSourcesCount > 0 ) {
1818 # Explain, and list the titles responsible
1819 foreach( $cascadeSources as $page ) {
1820 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1821 }
1822 }
1823 $notice .= '</div>';
1824 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1825 }
1826 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
1827 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle, '',
1828 array( 'lim' => 1,
1829 'showIfEmpty' => false,
1830 'msgKey' => array( 'titleprotectedwarning' ),
1831 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
1832 }
1833
1834 if ( $this->kblength === false ) {
1835 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1836 }
1837
1838 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1839 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
1840 array( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) ) );
1841 } else {
1842 if( !wfMessage('longpage-hint')->isDisabled() ) {
1843 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
1844 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1 ) ), strlen( $this->textbox1 ) )
1845 );
1846 }
1847 }
1848 }
1849
1850 /**
1851 * Standard summary input and label (wgSummary), abstracted so EditPage
1852 * subclasses may reorganize the form.
1853 * Note that you do not need to worry about the label's for=, it will be
1854 * inferred by the id given to the input. You can remove them both by
1855 * passing array( 'id' => false ) to $userInputAttrs.
1856 *
1857 * @param $summary string The value of the summary input
1858 * @param $labelText string The html to place inside the label
1859 * @param $inputAttrs array of attrs to use on the input
1860 * @param $spanLabelAttrs array of attrs to use on the span inside the label
1861 *
1862 * @return array An array in the format array( $label, $input )
1863 */
1864 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
1865 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
1866 $inputAttrs = ( is_array($inputAttrs) ? $inputAttrs : array() ) + array(
1867 'id' => 'wpSummary',
1868 'maxlength' => '200',
1869 'tabindex' => '1',
1870 'size' => 60,
1871 'spellcheck' => 'true',
1872 ) + Linker::tooltipAndAccesskeyAttribs( 'summary' );
1873
1874 $spanLabelAttrs = ( is_array($spanLabelAttrs) ? $spanLabelAttrs : array() ) + array(
1875 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
1876 'id' => "wpSummaryLabel"
1877 );
1878
1879 $label = null;
1880 if ( $labelText ) {
1881 $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
1882 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
1883 }
1884
1885 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
1886
1887 return array( $label, $input );
1888 }
1889
1890 /**
1891 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1892 * up top, or false if this is the comment summary
1893 * down below the textarea
1894 * @param $summary String: The text of the summary to display
1895 * @return String
1896 */
1897 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
1898 global $wgOut, $wgContLang;
1899 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1900 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
1901 if ( $isSubjectPreview ) {
1902 if ( $this->nosummary ) {
1903 return;
1904 }
1905 } else {
1906 if ( !$this->mShowSummaryField ) {
1907 return;
1908 }
1909 }
1910 $summary = $wgContLang->recodeForEdit( $summary );
1911 $labelText = wfMsgExt( $isSubjectPreview ? 'subject' : 'summary', 'parseinline' );
1912 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
1913 $wgOut->addHTML("{$label} {$input}");
1914 }
1915
1916 /**
1917 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1918 * up top, or false if this is the comment summary
1919 * down below the textarea
1920 * @param $summary String: the text of the summary to display
1921 * @return String
1922 */
1923 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
1924 if ( !$summary || ( !$this->preview && !$this->diff ) )
1925 return "";
1926
1927 global $wgParser;
1928
1929 if ( $isSubjectPreview )
1930 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
1931
1932 $message = $isSubjectPreview ? 'subject-preview' : 'summary-preview';
1933
1934 $summary = wfMsgExt( $message, 'parseinline' ) . Linker::commentBlock( $summary, $this->mTitle, $isSubjectPreview );
1935 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
1936 }
1937
1938 protected function showFormBeforeText() {
1939 global $wgOut;
1940 $section = htmlspecialchars( $this->section );
1941 $wgOut->addHTML( <<<HTML
1942 <input type='hidden' value="{$section}" name="wpSection" />
1943 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
1944 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
1945 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
1946
1947 HTML
1948 );
1949 if ( !$this->checkUnicodeCompliantBrowser() )
1950 $wgOut->addHTML(Html::hidden( 'safemode', '1' ));
1951 }
1952
1953 protected function showFormAfterText() {
1954 global $wgOut, $wgUser;
1955 /**
1956 * To make it harder for someone to slip a user a page
1957 * which submits an edit form to the wiki without their
1958 * knowledge, a random token is associated with the login
1959 * session. If it's not passed back with the submission,
1960 * we won't save the page, or render user JavaScript and
1961 * CSS previews.
1962 *
1963 * For anon editors, who may not have a session, we just
1964 * include the constant suffix to prevent editing from
1965 * broken text-mangling proxies.
1966 */
1967 $wgOut->addHTML( "\n" . Html::hidden( "wpEditToken", $wgUser->getEditToken() ) . "\n" );
1968 }
1969
1970 /**
1971 * Subpage overridable method for printing the form for page content editing
1972 * By default this simply outputs wpTextbox1
1973 * Subclasses can override this to provide a custom UI for editing;
1974 * be it a form, or simply wpTextbox1 with a modified content that will be
1975 * reverse modified when extracted from the post data.
1976 * Note that this is basically the inverse for importContentFormData
1977 */
1978 protected function showContentForm() {
1979 $this->showTextbox1();
1980 }
1981
1982 /**
1983 * Method to output wpTextbox1
1984 * The $textoverride method can be used by subclasses overriding showContentForm
1985 * to pass back to this method.
1986 *
1987 * @param $customAttribs An array of html attributes to use in the textarea
1988 * @param $textoverride String: optional text to override $this->textarea1 with
1989 */
1990 protected function showTextbox1($customAttribs = null, $textoverride = null) {
1991 $classes = array(); // Textarea CSS
1992 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
1993 # Is the title semi-protected?
1994 if ( $this->mTitle->isSemiProtected() ) {
1995 $classes[] = 'mw-textarea-sprotected';
1996 } else {
1997 # Then it must be protected based on static groups (regular)
1998 $classes[] = 'mw-textarea-protected';
1999 }
2000 # Is the title cascade-protected?
2001 if ( $this->mTitle->isCascadeProtected() ) {
2002 $classes[] = 'mw-textarea-cprotected';
2003 }
2004 }
2005 $attribs = array( 'tabindex' => 1 );
2006 if ( is_array($customAttribs) )
2007 $attribs += $customAttribs;
2008
2009 if ( $this->wasDeletedSinceLastEdit() )
2010 $attribs['type'] = 'hidden';
2011 if ( !empty( $classes ) ) {
2012 if ( isset($attribs['class']) )
2013 $classes[] = $attribs['class'];
2014 $attribs['class'] = implode( ' ', $classes );
2015 }
2016
2017 $this->showTextbox( isset($textoverride) ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
2018 }
2019
2020 protected function showTextbox2() {
2021 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
2022 }
2023
2024 protected function showTextbox( $content, $name, $customAttribs = array() ) {
2025 global $wgOut, $wgUser;
2026
2027 $wikitext = $this->safeUnicodeOutput( $content );
2028 if ( strval($wikitext) !== '' ) {
2029 // Ensure there's a newline at the end, otherwise adding lines
2030 // is awkward.
2031 // But don't add a newline if the ext is empty, or Firefox in XHTML
2032 // mode will show an extra newline. A bit annoying.
2033 $wikitext .= "\n";
2034 }
2035
2036 $attribs = $customAttribs + array(
2037 'accesskey' => ',',
2038 'id' => $name,
2039 'cols' => $wgUser->getIntOption( 'cols' ),
2040 'rows' => $wgUser->getIntOption( 'rows' ),
2041 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
2042 );
2043
2044 $pageLang = $this->mTitle->getPageLanguage();
2045 $attribs['lang'] = $pageLang->getCode();
2046 $attribs['dir'] = $pageLang->getDir();
2047
2048 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
2049 }
2050
2051 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
2052 global $wgOut;
2053 $classes = array();
2054 if ( $isOnTop )
2055 $classes[] = 'ontop';
2056
2057 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
2058
2059 if ( $this->formtype != 'preview' )
2060 $attribs['style'] = 'display: none;';
2061
2062 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
2063
2064 if ( $this->formtype == 'preview' ) {
2065 $this->showPreview( $previewOutput );
2066 }
2067
2068 $wgOut->addHTML( '</div>' );
2069
2070 if ( $this->formtype == 'diff') {
2071 $this->showDiff();
2072 }
2073 }
2074
2075 /**
2076 * Append preview output to $wgOut.
2077 * Includes category rendering if this is a category page.
2078 *
2079 * @param $text String: the HTML to be output for the preview.
2080 */
2081 protected function showPreview( $text ) {
2082 global $wgOut;
2083 if ( $this->mTitle->getNamespace() == NS_CATEGORY) {
2084 $this->mArticle->openShowCategory();
2085 }
2086 # This hook seems slightly odd here, but makes things more
2087 # consistent for extensions.
2088 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
2089 $wgOut->addHTML( $text );
2090 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
2091 $this->mArticle->closeShowCategory();
2092 }
2093 }
2094
2095 /**
2096 * Get a diff between the current contents of the edit box and the
2097 * version of the page we're editing from.
2098 *
2099 * If this is a section edit, we'll replace the section as for final
2100 * save and then make a comparison.
2101 */
2102 function showDiff() {
2103 global $wgUser, $wgContLang, $wgParser;
2104
2105 $oldtext = $this->mArticle->fetchContent();
2106 $newtext = $this->mArticle->replaceSection(
2107 $this->section, $this->textbox1, $this->summary, $this->edittime );
2108
2109 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2110
2111 $popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang );
2112 $newtext = $wgParser->preSaveTransform( $newtext, $this->mTitle, $wgUser, $popts );
2113 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2114 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2115 if ( $oldtext !== false || $newtext != '' ) {
2116 $de = new DifferenceEngine( $this->mArticle->getContext() );
2117 $de->setText( $oldtext, $newtext );
2118 $difftext = $de->getDiff( $oldtitle, $newtitle );
2119 $de->showDiffStyle();
2120 } else {
2121 $difftext = '';
2122 }
2123
2124 global $wgOut;
2125 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2126 }
2127
2128 /**
2129 * Give a chance for site and per-namespace customizations of
2130 * terms of service summary link that might exist separately
2131 * from the copyright notice.
2132 *
2133 * This will display between the save button and the edit tools,
2134 * so should remain short!
2135 */
2136 protected function showTosSummary() {
2137 $msg = 'editpage-tos-summary';
2138 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
2139 if( !wfMessage( $msg )->isDisabled() ) {
2140 global $wgOut;
2141 $wgOut->addHTML( '<div class="mw-tos-summary">' );
2142 $wgOut->addWikiMsg( $msg );
2143 $wgOut->addHTML( '</div>' );
2144 }
2145 }
2146
2147 protected function showEditTools() {
2148 global $wgOut;
2149 $wgOut->addHTML( '<div class="mw-editTools">' .
2150 wfMessage( 'edittools' )->inContentLanguage()->parse() .
2151 '</div>' );
2152 }
2153
2154 protected function getCopywarn() {
2155 global $wgRightsText;
2156 if ( $wgRightsText ) {
2157 $copywarnMsg = array( 'copyrightwarning',
2158 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
2159 $wgRightsText );
2160 } else {
2161 $copywarnMsg = array( 'copyrightwarning2',
2162 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
2163 }
2164 // Allow for site and per-namespace customization of contribution/copyright notice.
2165 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle, &$copywarnMsg ) );
2166
2167 return "<div id=\"editpage-copywarn\">\n" .
2168 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
2169 }
2170
2171 protected function showStandardInputs( &$tabindex = 2 ) {
2172 global $wgOut;
2173 $wgOut->addHTML( "<div class='editOptions'>\n" );
2174
2175 if ( $this->section != 'new' ) {
2176 $this->showSummaryInput( false, $this->summary );
2177 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
2178 }
2179
2180 $checkboxes = $this->getCheckboxes( $tabindex,
2181 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
2182 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
2183 $wgOut->addHTML( "<div class='editButtons'>\n" );
2184 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
2185
2186 $cancel = $this->getCancelLink();
2187 if ( $cancel !== '' ) {
2188 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
2189 }
2190 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
2191 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
2192 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
2193 htmlspecialchars( wfMsg( 'newwindow' ) );
2194 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
2195 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
2196 }
2197
2198 /**
2199 * Show an edit conflict. textbox1 is already shown in showEditForm().
2200 * If you want to use another entry point to this function, be careful.
2201 */
2202 protected function showConflict() {
2203 global $wgOut;
2204 $this->textbox2 = $this->textbox1;
2205 $this->textbox1 = $this->getContent();
2206 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2207 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2208
2209 $de = new DifferenceEngine( $this->mArticle->getContext() );
2210 $de->setText( $this->textbox2, $this->textbox1 );
2211 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2212
2213 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2214 $this->showTextbox2();
2215 }
2216 }
2217
2218 /**
2219 * @return string
2220 */
2221 public function getCancelLink() {
2222 $cancelParams = array();
2223 if ( !$this->isConflict && $this->mArticle->getOldID() > 0 ) {
2224 $cancelParams['oldid'] = $this->mArticle->getOldID();
2225 }
2226
2227 return Linker::linkKnown(
2228 $this->getContextTitle(),
2229 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2230 array( 'id' => 'mw-editform-cancel' ),
2231 $cancelParams
2232 );
2233 }
2234
2235 /**
2236 * Returns the URL to use in the form's action attribute.
2237 * This is used by EditPage subclasses when simply customizing the action
2238 * variable in the constructor is not enough. This can be used when the
2239 * EditPage lives inside of a Special page rather than a custom page action.
2240 *
2241 * @param $title Title object for which is being edited (where we go to for &action= links)
2242 * @return string
2243 */
2244 protected function getActionURL( Title $title ) {
2245 return $title->getLocalURL( array( 'action' => $this->action ) );
2246 }
2247
2248 /**
2249 * Check if a page was deleted while the user was editing it, before submit.
2250 * Note that we rely on the logging table, which hasn't been always there,
2251 * but that doesn't matter, because this only applies to brand new
2252 * deletes.
2253 */
2254 protected function wasDeletedSinceLastEdit() {
2255 if ( $this->deletedSinceEdit !== null ) {
2256 return $this->deletedSinceEdit;
2257 }
2258
2259 $this->deletedSinceEdit = false;
2260
2261 if ( $this->mTitle->isDeletedQuick() ) {
2262 $this->lastDelete = $this->getLastDelete();
2263 if ( $this->lastDelete ) {
2264 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
2265 if ( $deleteTime > $this->starttime ) {
2266 $this->deletedSinceEdit = true;
2267 }
2268 }
2269 }
2270
2271 return $this->deletedSinceEdit;
2272 }
2273
2274 protected function getLastDelete() {
2275 $dbr = wfGetDB( DB_SLAVE );
2276 $data = $dbr->selectRow(
2277 array( 'logging', 'user' ),
2278 array( 'log_type',
2279 'log_action',
2280 'log_timestamp',
2281 'log_user',
2282 'log_namespace',
2283 'log_title',
2284 'log_comment',
2285 'log_params',
2286 'log_deleted',
2287 'user_name' ),
2288 array( 'log_namespace' => $this->mTitle->getNamespace(),
2289 'log_title' => $this->mTitle->getDBkey(),
2290 'log_type' => 'delete',
2291 'log_action' => 'delete',
2292 'user_id=log_user' ),
2293 __METHOD__,
2294 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2295 );
2296 // Quick paranoid permission checks...
2297 if( is_object( $data ) ) {
2298 if( $data->log_deleted & LogPage::DELETED_USER )
2299 $data->user_name = wfMsgHtml( 'rev-deleted-user' );
2300 if( $data->log_deleted & LogPage::DELETED_COMMENT )
2301 $data->log_comment = wfMsgHtml( 'rev-deleted-comment' );
2302 }
2303 return $data;
2304 }
2305
2306 /**
2307 * Get the rendered text for previewing.
2308 * @return string
2309 */
2310 function getPreviewText() {
2311 global $wgOut, $wgUser, $wgParser, $wgRawHtml;
2312
2313 wfProfileIn( __METHOD__ );
2314
2315 if ( $wgRawHtml && !$this->mTokenOk ) {
2316 // Could be an offsite preview attempt. This is very unsafe if
2317 // HTML is enabled, as it could be an attack.
2318 $parsedNote = '';
2319 if ( $this->textbox1 !== '' ) {
2320 // Do not put big scary notice, if previewing the empty
2321 // string, which happens when you initially edit
2322 // a category page, due to automatic preview-on-open.
2323 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2324 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2325 }
2326 wfProfileOut( __METHOD__ );
2327 return $parsedNote;
2328 }
2329
2330 if ( $this->mTriedSave && !$this->mTokenOk ) {
2331 if ( $this->mTokenOkExceptSuffix ) {
2332 $note = wfMsg( 'token_suffix_mismatch' );
2333 } else {
2334 $note = wfMsg( 'session_fail_preview' );
2335 }
2336 } elseif ( $this->incompleteForm ) {
2337 $note = wfMsg( 'edit_form_incomplete' );
2338 } else {
2339 $note = wfMsg( 'previewnote' );
2340 }
2341
2342 $parserOptions = ParserOptions::newFromUser( $wgUser );
2343 $parserOptions->setEditSection( false );
2344 $parserOptions->setTidy( true );
2345 $parserOptions->setIsPreview( true );
2346 $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' );
2347
2348 # don't parse non-wikitext pages, show message about preview
2349 # 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?
2350
2351 if ( $this->isCssJsSubpage || !$this->mTitle->isWikitextPage() ) {
2352 if( $this->mTitle->isCssJsSubpage() ) {
2353 $level = 'user';
2354 } elseif( $this->mTitle->isCssOrJsPage() ) {
2355 $level = 'site';
2356 } else {
2357 $level = false;
2358 }
2359
2360 # Used messages to make sure grep find them:
2361 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2362 if( $level ) {
2363 if (preg_match( "/\\.css$/", $this->mTitle->getText() ) ) {
2364 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2365 $class = "mw-code mw-css";
2366 } elseif (preg_match( "/\\.js$/", $this->mTitle->getText() ) ) {
2367 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2368 $class = "mw-code mw-js";
2369 } else {
2370 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2371 }
2372 }
2373
2374 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
2375 $previewHTML = $parserOutput->mText;
2376 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1 ) . "\n</pre>\n";
2377 } else {
2378 $rt = Title::newFromRedirectArray( $this->textbox1 );
2379 if ( $rt ) {
2380 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
2381 } else {
2382 $toparse = $this->textbox1;
2383
2384 # If we're adding a comment, we need to show the
2385 # summary as the headline
2386 if ( $this->section == "new" && $this->summary != "" ) {
2387 $toparse = "== {$this->summary} ==\n\n" . $toparse;
2388 }
2389
2390 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2391
2392 $parserOptions->enableLimitReport();
2393
2394 $toparse = $wgParser->preSaveTransform( $toparse, $this->mTitle, $wgUser, $parserOptions );
2395 $parserOutput = $wgParser->parse( $toparse, $this->mTitle, $parserOptions );
2396
2397 $previewHTML = $parserOutput->getText();
2398 $this->mParserOutput = $parserOutput;
2399 $wgOut->addParserOutputNoText( $parserOutput );
2400
2401 if ( count( $parserOutput->getWarnings() ) ) {
2402 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2403 }
2404 }
2405 }
2406
2407 if( $this->isConflict ) {
2408 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2409 } else {
2410 $conflict = '<hr />';
2411 }
2412
2413 $previewhead = "<div class='previewnote'>\n" .
2414 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2415 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2416
2417 $pageLang = $this->mTitle->getPageLanguage();
2418 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2419 'class' => 'mw-content-'.$pageLang->getDir() );
2420 $previewHTML = Html::rawElement( 'div', $attribs, $previewHTML );
2421
2422 wfProfileOut( __METHOD__ );
2423 return $previewhead . $previewHTML . $this->previewTextAfterContent;
2424 }
2425
2426 /**
2427 * @return Array
2428 */
2429 function getTemplates() {
2430 if ( $this->preview || $this->section != '' ) {
2431 $templates = array();
2432 if ( !isset( $this->mParserOutput ) ) {
2433 return $templates;
2434 }
2435 foreach( $this->mParserOutput->getTemplates() as $ns => $template) {
2436 foreach( array_keys( $template ) as $dbk ) {
2437 $templates[] = Title::makeTitle($ns, $dbk);
2438 }
2439 }
2440 return $templates;
2441 } else {
2442 return $this->mArticle->getUsedTemplates();
2443 }
2444 }
2445
2446 /**
2447 * Shows a bulletin board style toolbar for common editing functions.
2448 * It can be disabled in the user preferences.
2449 * The necessary JavaScript code can be found in skins/common/edit.js.
2450 *
2451 * @return string
2452 */
2453 static function getEditToolbar() {
2454 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2455 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2456
2457 $imagesAvailable = $wgEnableUploads || count( $wgForeignFileRepos );
2458
2459 /**
2460 * $toolarray is an array of arrays each of which includes the
2461 * filename of the button image (without path), the opening
2462 * tag, the closing tag, optionally a sample text that is
2463 * inserted between the two when no selection is highlighted
2464 * and. The tip text is shown when the user moves the mouse
2465 * over the button.
2466 *
2467 * Also here: accesskeys (key), which are not used yet until
2468 * someone can figure out a way to make them work in
2469 * IE. However, we should make sure these keys are not defined
2470 * on the edit page.
2471 */
2472 $toolarray = array(
2473 array(
2474 'image' => $wgLang->getImageFile( 'button-bold' ),
2475 'id' => 'mw-editbutton-bold',
2476 'open' => '\'\'\'',
2477 'close' => '\'\'\'',
2478 'sample' => wfMsg( 'bold_sample' ),
2479 'tip' => wfMsg( 'bold_tip' ),
2480 'key' => 'B'
2481 ),
2482 array(
2483 'image' => $wgLang->getImageFile( 'button-italic' ),
2484 'id' => 'mw-editbutton-italic',
2485 'open' => '\'\'',
2486 'close' => '\'\'',
2487 'sample' => wfMsg( 'italic_sample' ),
2488 'tip' => wfMsg( 'italic_tip' ),
2489 'key' => 'I'
2490 ),
2491 array(
2492 'image' => $wgLang->getImageFile( 'button-link' ),
2493 'id' => 'mw-editbutton-link',
2494 'open' => '[[',
2495 'close' => ']]',
2496 'sample' => wfMsg( 'link_sample' ),
2497 'tip' => wfMsg( 'link_tip' ),
2498 'key' => 'L'
2499 ),
2500 array(
2501 'image' => $wgLang->getImageFile( 'button-extlink' ),
2502 'id' => 'mw-editbutton-extlink',
2503 'open' => '[',
2504 'close' => ']',
2505 'sample' => wfMsg( 'extlink_sample' ),
2506 'tip' => wfMsg( 'extlink_tip' ),
2507 'key' => 'X'
2508 ),
2509 array(
2510 'image' => $wgLang->getImageFile( 'button-headline' ),
2511 'id' => 'mw-editbutton-headline',
2512 'open' => "\n== ",
2513 'close' => " ==\n",
2514 'sample' => wfMsg( 'headline_sample' ),
2515 'tip' => wfMsg( 'headline_tip' ),
2516 'key' => 'H'
2517 ),
2518 $imagesAvailable ? array(
2519 'image' => $wgLang->getImageFile( 'button-image' ),
2520 'id' => 'mw-editbutton-image',
2521 'open' => '[[' . $wgContLang->getNsText( NS_FILE ) . ':',
2522 'close' => ']]',
2523 'sample' => wfMsg( 'image_sample' ),
2524 'tip' => wfMsg( 'image_tip' ),
2525 'key' => 'D',
2526 ) : false,
2527 $imagesAvailable ? array(
2528 'image' => $wgLang->getImageFile( 'button-media' ),
2529 'id' => 'mw-editbutton-media',
2530 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA ) . ':',
2531 'close' => ']]',
2532 'sample' => wfMsg( 'media_sample' ),
2533 'tip' => wfMsg( 'media_tip' ),
2534 'key' => 'M'
2535 ) : false,
2536 $wgUseTeX ? array(
2537 'image' => $wgLang->getImageFile( 'button-math' ),
2538 'id' => 'mw-editbutton-math',
2539 'open' => "<math>",
2540 'close' => "</math>",
2541 'sample' => wfMsg( 'math_sample' ),
2542 'tip' => wfMsg( 'math_tip' ),
2543 'key' => 'C'
2544 ) : false,
2545 array(
2546 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2547 'id' => 'mw-editbutton-nowiki',
2548 'open' => "<nowiki>",
2549 'close' => "</nowiki>",
2550 'sample' => wfMsg( 'nowiki_sample' ),
2551 'tip' => wfMsg( 'nowiki_tip' ),
2552 'key' => 'N'
2553 ),
2554 array(
2555 'image' => $wgLang->getImageFile( 'button-sig' ),
2556 'id' => 'mw-editbutton-signature',
2557 'open' => '--~~~~',
2558 'close' => '',
2559 'sample' => '',
2560 'tip' => wfMsg( 'sig_tip' ),
2561 'key' => 'Y'
2562 ),
2563 array(
2564 'image' => $wgLang->getImageFile( 'button-hr' ),
2565 'id' => 'mw-editbutton-hr',
2566 'open' => "\n----\n",
2567 'close' => '',
2568 'sample' => '',
2569 'tip' => wfMsg( 'hr_tip' ),
2570 'key' => 'R'
2571 )
2572 );
2573
2574 $script = '';
2575 foreach ( $toolarray as $tool ) {
2576 if ( !$tool ) {
2577 continue;
2578 }
2579
2580 $params = array(
2581 $image = $wgStylePath . '/common/images/' . $tool['image'],
2582 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2583 // Older browsers show a "speedtip" type message only for ALT.
2584 // Ideally these should be different, realistically they
2585 // probably don't need to be.
2586 $tip = $tool['tip'],
2587 $open = $tool['open'],
2588 $close = $tool['close'],
2589 $sample = $tool['sample'],
2590 $cssId = $tool['id'],
2591 );
2592
2593 $script .= Xml::encodeJsCall( 'mw.toolbar.addButton', $params );
2594 }
2595 $wgOut->addScript( Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) ) );
2596
2597 $toolbar = '<div id="toolbar"></div>';
2598
2599 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2600
2601 return $toolbar;
2602 }
2603
2604 /**
2605 * Returns an array of html code of the following checkboxes:
2606 * minor and watch
2607 *
2608 * @param $tabindex Current tabindex
2609 * @param $checked Array of checkbox => bool, where bool indicates the checked
2610 * status of the checkbox
2611 *
2612 * @return array
2613 */
2614 public function getCheckboxes( &$tabindex, $checked ) {
2615 global $wgUser;
2616
2617 $checkboxes = array();
2618
2619 // don't show the minor edit checkbox if it's a new page or section
2620 if ( !$this->isNew ) {
2621 $checkboxes['minor'] = '';
2622 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2623 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2624 $attribs = array(
2625 'tabindex' => ++$tabindex,
2626 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2627 'id' => 'wpMinoredit',
2628 );
2629 $checkboxes['minor'] =
2630 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2631 "&#160;<label for='wpMinoredit' id='mw-editpage-minoredit'" .
2632 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2633 ">{$minorLabel}</label>";
2634 }
2635 }
2636
2637 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2638 $checkboxes['watch'] = '';
2639 if ( $wgUser->isLoggedIn() ) {
2640 $attribs = array(
2641 'tabindex' => ++$tabindex,
2642 'accesskey' => wfMsg( 'accesskey-watch' ),
2643 'id' => 'wpWatchthis',
2644 );
2645 $checkboxes['watch'] =
2646 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2647 "&#160;<label for='wpWatchthis' id='mw-editpage-watch'" .
2648 Xml::expandAttributes( array( 'title' => Linker::titleAttrib( 'watch', 'withaccess' ) ) ) .
2649 ">{$watchLabel}</label>";
2650 }
2651 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2652 return $checkboxes;
2653 }
2654
2655 /**
2656 * Returns an array of html code of the following buttons:
2657 * save, diff, preview and live
2658 *
2659 * @param $tabindex Current tabindex
2660 *
2661 * @return array
2662 */
2663 public function getEditButtons( &$tabindex ) {
2664 $buttons = array();
2665
2666 $temp = array(
2667 'id' => 'wpSave',
2668 'name' => 'wpSave',
2669 'type' => 'submit',
2670 'tabindex' => ++$tabindex,
2671 'value' => wfMsg( 'savearticle' ),
2672 'accesskey' => wfMsg( 'accesskey-save' ),
2673 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2674 );
2675 $buttons['save'] = Xml::element('input', $temp, '');
2676
2677 ++$tabindex; // use the same for preview and live preview
2678 $temp = array(
2679 'id' => 'wpPreview',
2680 'name' => 'wpPreview',
2681 'type' => 'submit',
2682 'tabindex' => $tabindex,
2683 'value' => wfMsg( 'showpreview' ),
2684 'accesskey' => wfMsg( 'accesskey-preview' ),
2685 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2686 );
2687 $buttons['preview'] = Xml::element( 'input', $temp, '' );
2688 $buttons['live'] = '';
2689
2690 $temp = array(
2691 'id' => 'wpDiff',
2692 'name' => 'wpDiff',
2693 'type' => 'submit',
2694 'tabindex' => ++$tabindex,
2695 'value' => wfMsg( 'showdiff' ),
2696 'accesskey' => wfMsg( 'accesskey-diff' ),
2697 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2698 );
2699 $buttons['diff'] = Xml::element( 'input', $temp, '' );
2700
2701 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2702 return $buttons;
2703 }
2704
2705 /**
2706 * Output preview text only. This can be sucked into the edit page
2707 * via JavaScript, and saves the server time rendering the skin as
2708 * well as theoretically being more robust on the client (doesn't
2709 * disturb the edit box's undo history, won't eat your text on
2710 * failure, etc).
2711 *
2712 * @todo This doesn't include category or interlanguage links.
2713 * Would need to enhance it a bit, <s>maybe wrap them in XML
2714 * or something...</s> that might also require more skin
2715 * initialization, so check whether that's a problem.
2716 */
2717 function livePreview() {
2718 global $wgOut;
2719 $wgOut->disable();
2720 header( 'Content-type: text/xml; charset=utf-8' );
2721 header( 'Cache-control: no-cache' );
2722
2723 $previewText = $this->getPreviewText();
2724 #$categories = $skin->getCategoryLinks();
2725
2726 $s =
2727 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2728 Xml::tags( 'livepreview', null,
2729 Xml::element( 'preview', null, $previewText )
2730 #. Xml::element( 'category', null, $categories )
2731 );
2732 echo $s;
2733 }
2734
2735 /**
2736 * Call the stock "user is blocked" page
2737 *
2738 * @deprecated in 1.19; throw an exception directly instead
2739 */
2740 function blockedPage() {
2741 global $wgUser;
2742
2743 throw new UserBlockedError( $wgUser->mBlock );
2744 }
2745
2746 /**
2747 * Produce the stock "please login to edit pages" page
2748 *
2749 * @deprecated in 1.19; throw an exception directly instead
2750 */
2751 function userNotLoggedInPage() {
2752 throw new PermissionsError( 'edit' );
2753 }
2754
2755 /**
2756 * Show an error page saying to the user that he has insufficient permissions
2757 * to create a new page
2758 *
2759 * @deprecated in 1.19; throw an exception directly instead
2760 */
2761 function noCreatePermission() {
2762 $permission = $this->mTitle->isTalkPage() ? 'createtalk' : 'createpage';
2763 throw new PermissionsError( $permission );
2764 }
2765
2766 /**
2767 * Creates a basic error page which informs the user that
2768 * they have attempted to edit a nonexistent section.
2769 */
2770 function noSuchSectionPage() {
2771 global $wgOut;
2772
2773 $wgOut->prepareErrorPage( wfMessage( 'nosuchsectiontitle' ) );
2774
2775 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section );
2776 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
2777 $wgOut->addHTML( $res );
2778
2779 $wgOut->returnToMain( false, $this->mTitle );
2780 }
2781
2782 /**
2783 * Produce the stock "your edit contains spam" page
2784 *
2785 * @param $match Text which triggered one or more filters
2786 * @deprecated since 1.17 Use method spamPageWithContent() instead
2787 */
2788 static function spamPage( $match = false ) {
2789 global $wgOut, $wgTitle;
2790
2791 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
2792
2793 $wgOut->addHTML( '<div id="spamprotected">' );
2794 $wgOut->addWikiMsg( 'spamprotectiontext' );
2795 if ( $match ) {
2796 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2797 }
2798 $wgOut->addHTML( '</div>' );
2799
2800 $wgOut->returnToMain( false, $wgTitle );
2801 }
2802
2803 /**
2804 * Show "your edit contains spam" page with your diff and text
2805 *
2806 * @param $match Text which triggered one or more filters
2807 */
2808 public function spamPageWithContent( $match = false ) {
2809 global $wgOut;
2810 $this->textbox2 = $this->textbox1;
2811
2812 $wgOut->prepareErrorPage( wfMessage( 'spamprotectiontitle' ) );
2813
2814 $wgOut->addHTML( '<div id="spamprotected">' );
2815 $wgOut->addWikiMsg( 'spamprotectiontext' );
2816 if ( $match ) {
2817 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2818 }
2819 $wgOut->addHTML( '</div>' );
2820
2821 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2822 $de = new DifferenceEngine( $this->mArticle->getContext() );
2823 $de->setText( $this->getContent(), $this->textbox2 );
2824 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
2825
2826 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2827 $this->showTextbox2();
2828
2829 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
2830 }
2831
2832 /**
2833 * Format an anchor fragment as it would appear for a given section name
2834 * @param $text String
2835 * @return String
2836 * @private
2837 */
2838 function sectionAnchor( $text ) {
2839 global $wgParser;
2840 return $wgParser->guessSectionNameFromWikiText( $text );
2841 }
2842
2843 /**
2844 * Check if the browser is on a blacklist of user-agents known to
2845 * mangle UTF-8 data on form submission. Returns true if Unicode
2846 * should make it through, false if it's known to be a problem.
2847 * @return bool
2848 * @private
2849 */
2850 function checkUnicodeCompliantBrowser() {
2851 global $wgBrowserBlackList;
2852 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2853 // No User-Agent header sent? Trust it by default...
2854 return true;
2855 }
2856 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2857 foreach ( $wgBrowserBlackList as $browser ) {
2858 if ( preg_match($browser, $currentbrowser) ) {
2859 return false;
2860 }
2861 }
2862 return true;
2863 }
2864
2865 /**
2866 * Filter an input field through a Unicode de-armoring process if it
2867 * came from an old browser with known broken Unicode editing issues.
2868 *
2869 * @param $request WebRequest
2870 * @param $field String
2871 * @return String
2872 * @private
2873 */
2874 function safeUnicodeInput( $request, $field ) {
2875 $text = rtrim( $request->getText( $field ) );
2876 return $request->getBool( 'safemode' )
2877 ? $this->unmakesafe( $text )
2878 : $text;
2879 }
2880
2881 /**
2882 * @param $request WebRequest
2883 * @param $text string
2884 * @return string
2885 */
2886 function safeUnicodeText( $request, $text ) {
2887 $text = rtrim( $text );
2888 return $request->getBool( 'safemode' )
2889 ? $this->unmakesafe( $text )
2890 : $text;
2891 }
2892
2893 /**
2894 * Filter an output field through a Unicode armoring process if it is
2895 * going to an old browser with known broken Unicode editing issues.
2896 *
2897 * @param $text String
2898 * @return String
2899 * @private
2900 */
2901 function safeUnicodeOutput( $text ) {
2902 global $wgContLang;
2903 $codedText = $wgContLang->recodeForEdit( $text );
2904 return $this->checkUnicodeCompliantBrowser()
2905 ? $codedText
2906 : $this->makesafe( $codedText );
2907 }
2908
2909 /**
2910 * A number of web browsers are known to corrupt non-ASCII characters
2911 * in a UTF-8 text editing environment. To protect against this,
2912 * detected browsers will be served an armored version of the text,
2913 * with non-ASCII chars converted to numeric HTML character references.
2914 *
2915 * Preexisting such character references will have a 0 added to them
2916 * to ensure that round-trips do not alter the original data.
2917 *
2918 * @param $invalue String
2919 * @return String
2920 * @private
2921 */
2922 function makesafe( $invalue ) {
2923 // Armor existing references for reversability.
2924 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
2925
2926 $bytesleft = 0;
2927 $result = "";
2928 $working = 0;
2929 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2930 $bytevalue = ord( $invalue[$i] );
2931 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2932 $result .= chr( $bytevalue );
2933 $bytesleft = 0;
2934 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2935 $working = $working << 6;
2936 $working += ($bytevalue & 0x3F);
2937 $bytesleft--;
2938 if ( $bytesleft <= 0 ) {
2939 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2940 }
2941 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2942 $working = $bytevalue & 0x1F;
2943 $bytesleft = 1;
2944 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2945 $working = $bytevalue & 0x0F;
2946 $bytesleft = 2;
2947 } else { //1111 0xxx
2948 $working = $bytevalue & 0x07;
2949 $bytesleft = 3;
2950 }
2951 }
2952 return $result;
2953 }
2954
2955 /**
2956 * Reverse the previously applied transliteration of non-ASCII characters
2957 * back to UTF-8. Used to protect data from corruption by broken web browsers
2958 * as listed in $wgBrowserBlackList.
2959 *
2960 * @param $invalue String
2961 * @return String
2962 * @private
2963 */
2964 function unmakesafe( $invalue ) {
2965 $result = "";
2966 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2967 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+3] != '0' ) ) {
2968 $i += 3;
2969 $hexstring = "";
2970 do {
2971 $hexstring .= $invalue[$i];
2972 $i++;
2973 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
2974
2975 // Do some sanity checks. These aren't needed for reversability,
2976 // but should help keep the breakage down if the editor
2977 // breaks one of the entities whilst editing.
2978 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2979 $codepoint = hexdec($hexstring);
2980 $result .= codepointToUtf8( $codepoint );
2981 } else {
2982 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2983 }
2984 } else {
2985 $result .= substr( $invalue, $i, 1 );
2986 }
2987 }
2988 // reverse the transform that we made for reversability reasons.
2989 return strtr( $result, array( "&#x0" => "&#x" ) );
2990 }
2991 }