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