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