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