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