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