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