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