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