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