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