Cleaning up some old PHP 4 object-reference usage in some edit filtering hooks.
[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( 'id' => 'mw-editform-cancel' ),
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 } else {
1413 $summaryhiddens .= Xml::hidden( 'wpIgnoreBlankSummary', true ); # bug 18699
1414 }
1415 $editsummary = "<div class='editOptions'>\n";
1416 global $wgParser;
1417 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary ) );
1418 $subjectpreview = $summarytext && ( $this->preview || $this->diff ) ?
1419 "<div class=\"mw-summary-preview\">". wfMsgExt('subject-preview', 'parseinline') . $sk->commentBlock( $formattedSummary, $this->mTitle, true )."</div>\n" : '';
1420 $summarypreview = '';
1421 } else {
1422 $commentsubject = '';
1423
1424 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1425 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
1426
1427 $editsummary = Xml::tags( 'label', array( 'for' => 'wpSummary' ), $summary );
1428 $editsummary = Xml::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1429 $editsummary ) . ' ';
1430
1431 $editsummary .= Xml::input( 'wpSummary',
1432 60,
1433 $summarytext,
1434 array(
1435 'id' => 'wpSummary',
1436 'maxlength' => '200',
1437 'tabindex' => '1'
1438 ) );
1439
1440 // No idea where this is closed.
1441 $editsummary = Xml::openElement( 'div', array( 'class' => 'editOptions' ) )
1442 . $editsummary . '<br/>';
1443
1444 $summarypreview = '';
1445 if ( $summarytext && ( $this->preview || $this->diff ) ) {
1446 $summarypreview =
1447 Xml::tags( 'div',
1448 array( 'class' => 'mw-summary-preview' ),
1449 wfMsgExt( 'summary-preview', 'parseinline' ) .
1450 $sk->commentBlock( $this->summary, $this->mTitle )
1451 );
1452 }
1453 $subjectpreview = '';
1454 }
1455 $commentsubject .= $summaryhiddens;
1456
1457 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1458 if ( !$this->preview && !$this->diff ) {
1459 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1460 }
1461 $templates = $this->getTemplates();
1462 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1463
1464 $hiddencats = $this->mArticle->getHiddenCategories();
1465 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1466
1467 global $wgUseMetadataEdit ;
1468 if ( $wgUseMetadataEdit ) {
1469 $metadata = $this->mMetaData ;
1470 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1471 $top = wfMsgWikiHtml( 'metadata_help' );
1472 /* ToDo: Replace with clean code */
1473 $ew = $wgUser->getOption( 'editwidth' );
1474 if ( $ew ) $ew = " style=\"width:100%\"";
1475 else $ew = '';
1476 $cols = $wgUser->getIntOption( 'cols' );
1477 /* /ToDo */
1478 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1479 }
1480 else $metadata = "" ;
1481
1482 $recreate = '';
1483 if ( $this->wasDeletedSinceLastEdit() ) {
1484 if ( 'save' != $this->formtype ) {
1485 $wgOut->wrapWikiMsg(
1486 "<div class='error mw-deleted-while-editing'>\n$1</div>",
1487 'deletedwhileediting' );
1488 } else {
1489 // Hide the toolbar and edit area, user can click preview to get it back
1490 // Add an confirmation checkbox and explanation.
1491 $toolbar = '';
1492 $recreate = '<div class="mw-confirm-recreate">' .
1493 $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ) ) .
1494 Xml::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1495 array( 'title' => $sk->titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1496 ) . '</div>';
1497 }
1498 }
1499
1500 $tabindex = 2;
1501
1502 $checkboxes = $this->getCheckboxes( $tabindex, $sk,
1503 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1504
1505 $checkboxhtml = implode( $checkboxes, "\n" );
1506
1507 $buttons = $this->getEditButtons( $tabindex );
1508 $buttonshtml = implode( $buttons, "\n" );
1509
1510 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1511 ? '' : Xml::hidden( 'safemode', '1' );
1512
1513 $wgOut->addHTML( <<<END
1514 {$toolbar}
1515 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1516 END
1517 );
1518
1519 if ( is_callable( $formCallback ) ) {
1520 call_user_func_array( $formCallback, array( &$wgOut ) );
1521 }
1522
1523 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1524
1525 // Put these up at the top to ensure they aren't lost on early form submission
1526 $this->showFormBeforeText();
1527
1528 $wgOut->addHTML( <<<END
1529 {$recreate}
1530 {$commentsubject}
1531 {$subjectpreview}
1532 {$this->editFormTextBeforeContent}
1533 END
1534 );
1535 $this->showTextbox1( $classes );
1536
1537 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1538 $wgOut->addHTML( <<<END
1539 {$this->editFormTextAfterWarn}
1540 {$metadata}
1541 {$editsummary}
1542 {$summarypreview}
1543 {$checkboxhtml}
1544 {$safemodehtml}
1545 END
1546 );
1547
1548 $wgOut->addHTML(
1549 "<div class='editButtons'>
1550 {$buttonshtml}
1551 <span class='editHelp'>{$cancel}{$separator}{$edithelp}</span>
1552 </div><!-- editButtons -->
1553 </div><!-- editOptions -->");
1554
1555 /**
1556 * To make it harder for someone to slip a user a page
1557 * which submits an edit form to the wiki without their
1558 * knowledge, a random token is associated with the login
1559 * session. If it's not passed back with the submission,
1560 * we won't save the page, or render user JavaScript and
1561 * CSS previews.
1562 *
1563 * For anon editors, who may not have a session, we just
1564 * include the constant suffix to prevent editing from
1565 * broken text-mangling proxies.
1566 */
1567 $token = htmlspecialchars( $wgUser->editToken() );
1568 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1569
1570 $this->showTosSummary();
1571 $this->showEditTools();
1572
1573 $wgOut->addHTML( <<<END
1574 {$this->editFormTextAfterTools}
1575 <div class='templatesUsed'>
1576 {$formattedtemplates}
1577 </div>
1578 <div class='hiddencats'>
1579 {$formattedhiddencats}
1580 </div>
1581 END
1582 );
1583
1584 if ( $this->isConflict && wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1585 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1586
1587 $de = new DifferenceEngine( $this->mTitle );
1588 $de->setText( $this->textbox2, $this->textbox1 );
1589 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1590
1591 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1592 $this->showTextbox2();
1593 }
1594 $wgOut->addHTML( $this->editFormTextBottom );
1595 $wgOut->addHTML( "</form>\n" );
1596 if ( !$wgUser->getOption( 'previewontop' ) ) {
1597 $this->displayPreviewArea( $previewOutput, false );
1598 }
1599
1600 wfProfileOut( $fname );
1601 }
1602
1603 protected function showFormBeforeText() {
1604 global $wgOut;
1605 $wgOut->addHTML( "
1606 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1607 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1608 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1609 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1610 }
1611
1612 protected function showTextbox1( $classes ) {
1613 $attribs = array( 'tabindex' => 1 );
1614
1615 if ( $this->wasDeletedSinceLastEdit() )
1616 $attribs['type'] = 'hidden';
1617 if ( !empty($classes) )
1618 $attribs['class'] = implode(' ',$classes);
1619
1620 $this->showTextbox( $this->textbox1, 'wpTextbox1', $attribs );
1621 }
1622
1623 protected function showTextbox2() {
1624 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6 ) );
1625 }
1626
1627 protected function showTextbox( $content, $name, $attribs = array() ) {
1628 global $wgOut, $wgUser;
1629
1630 $wikitext = $this->safeUnicodeOutput( $content );
1631 if ( $wikitext !== '' ) {
1632 // Ensure there's a newline at the end, otherwise adding lines
1633 // is awkward.
1634 // But don't add a newline if the ext is empty, or Firefox in XHTML
1635 // mode will show an extra newline. A bit annoying.
1636 $wikitext .= "\n";
1637 }
1638
1639 $attribs['accesskey'] = ',';
1640 $attribs['id'] = $name;
1641
1642 if ( $wgUser->getOption( 'editwidth' ) )
1643 $attribs['style'] = 'width: 100%';
1644
1645 $wgOut->addHTML( Xml::textarea(
1646 $name,
1647 $wikitext,
1648 $wgUser->getIntOption( 'cols' ), $wgUser->getIntOption( 'rows' ),
1649 $attribs ) );
1650 }
1651
1652 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1653 global $wgOut;
1654 $classes = array();
1655 if ( $isOnTop )
1656 $classes[] = 'ontop';
1657
1658 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1659
1660 if ( $this->formtype != 'preview' )
1661 $attribs['style'] = 'display: none;';
1662
1663 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
1664
1665 if ( $this->formtype == 'preview' ) {
1666 $this->showPreview( $previewOutput );
1667 }
1668
1669 $wgOut->addHTML( '</div>' );
1670
1671 if ( $this->formtype == 'diff') {
1672 $this->showDiff();
1673 }
1674 }
1675
1676 /**
1677 * Append preview output to $wgOut.
1678 * Includes category rendering if this is a category page.
1679 *
1680 * @param string $text The HTML to be output for the preview.
1681 */
1682 protected function showPreview( $text ) {
1683 global $wgOut;
1684 if ( $this->mTitle->getNamespace() == NS_CATEGORY) {
1685 $this->mArticle->openShowCategory();
1686 }
1687 # This hook seems slightly odd here, but makes things more
1688 # consistent for extensions.
1689 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1690 $wgOut->addHTML( $text );
1691 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1692 $this->mArticle->closeShowCategory();
1693 }
1694 }
1695
1696 /**
1697 * Live Preview lets us fetch rendered preview page content and
1698 * add it to the page without refreshing the whole page.
1699 * If not supported by the browser it will fall through to the normal form
1700 * submission method.
1701 *
1702 * This function outputs a script tag to support live preview, and
1703 * returns an onclick handler which should be added to the attributes
1704 * of the preview button
1705 */
1706 function doLivePreviewScript() {
1707 global $wgOut, $wgTitle;
1708 $wgOut->addScriptFile( 'preview.js' );
1709 return "";
1710 }
1711
1712 protected function showTosSummary() {
1713 $msg = 'editpage-tos-summary';
1714 // Give a chance for site and per-namespace customizations of
1715 // terms of service summary link that might exist separately
1716 // from the copyright notice.
1717 //
1718 // This will display between the save button and the edit tools,
1719 // so should remain short!
1720 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
1721 $text = wfMsg( $msg );
1722 if( !wfEmptyMsg( $msg, $text ) && $text !== '-' ) {
1723 global $wgOut;
1724 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1725 $wgOut->addWikiMsgArray( $msg, array() );
1726 $wgOut->addHTML( '</div>' );
1727 }
1728 }
1729
1730 protected function showEditTools() {
1731 global $wgOut;
1732 $wgOut->addHTML( '<div class="mw-editTools">' );
1733 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1734 $wgOut->addHTML( '</div>' );
1735 }
1736
1737 protected function getLastDelete() {
1738 $dbr = wfGetDB( DB_SLAVE );
1739 $data = $dbr->selectRow(
1740 array( 'logging', 'user' ),
1741 array( 'log_type',
1742 'log_action',
1743 'log_timestamp',
1744 'log_user',
1745 'log_namespace',
1746 'log_title',
1747 'log_comment',
1748 'log_params',
1749 'log_deleted',
1750 'user_name' ),
1751 array( 'log_namespace' => $this->mTitle->getNamespace(),
1752 'log_title' => $this->mTitle->getDBkey(),
1753 'log_type' => 'delete',
1754 'log_action' => 'delete',
1755 'user_id=log_user' ),
1756 __METHOD__,
1757 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1758 );
1759 // Quick paranoid permission checks...
1760 if( is_object($data) ) {
1761 if( $data->log_deleted & LogPage::DELETED_USER )
1762 $data->user_name = wfMsgHtml('rev-deleted-user');
1763 if( $data->log_deleted & LogPage::DELETED_COMMENT )
1764 $data->log_comment = wfMsgHtml('rev-deleted-comment');
1765 }
1766 return $data;
1767 }
1768
1769 /**
1770 * Get the rendered text for previewing.
1771 * @return string
1772 */
1773 function getPreviewText() {
1774 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang, $wgMessageCache;
1775
1776 wfProfileIn( __METHOD__ );
1777
1778 if ( $this->mTriedSave && !$this->mTokenOk ) {
1779 if ( $this->mTokenOkExceptSuffix ) {
1780 $note = wfMsg( 'token_suffix_mismatch' );
1781 } else {
1782 $note = wfMsg( 'session_fail_preview' );
1783 }
1784 } else {
1785 $note = wfMsg( 'previewnote' );
1786 }
1787
1788 $parserOptions = ParserOptions::newFromUser( $wgUser );
1789 $parserOptions->setEditSection( false );
1790 $parserOptions->setIsPreview( true );
1791 $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' );
1792
1793 global $wgRawHtml;
1794 if ( $wgRawHtml && !$this->mTokenOk ) {
1795 // Could be an offsite preview attempt. This is very unsafe if
1796 // HTML is enabled, as it could be an attack.
1797 return $wgOut->parse( "<div class='previewnote'>" .
1798 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1799 }
1800
1801 # don't parse user css/js, show message about preview
1802 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1803
1804 if ( $this->isCssJsSubpage ) {
1805 if (preg_match("/\\.css$/", $this->mTitle->getText() ) ) {
1806 $previewtext = wfMsg('usercsspreview');
1807 } else if (preg_match("/\\.js$/", $this->mTitle->getText() ) ) {
1808 $previewtext = wfMsg('userjspreview');
1809 }
1810 $parserOptions->setTidy(true);
1811 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
1812 $previewHTML = $parserOutput->mText;
1813 } elseif ( $rt = Title::newFromRedirectArray( $this->textbox1 ) ) {
1814 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
1815 } else {
1816 $toparse = $this->textbox1;
1817
1818 # If we're adding a comment, we need to show the
1819 # summary as the headline
1820 if ( $this->section=="new" && $this->summary!="" ) {
1821 $toparse="== {$this->summary} ==\n\n".$toparse;
1822 }
1823
1824 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData;
1825
1826 // Parse mediawiki messages with correct target language
1827 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1828 list( /* $unused */, $lang ) = $wgMessageCache->figureMessage( $this->mTitle->getText() );
1829 $obj = wfGetLangObj( $lang );
1830 $parserOptions->setTargetLanguage( $obj );
1831 }
1832
1833
1834 $parserOptions->setTidy(true);
1835 $parserOptions->enableLimitReport();
1836 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ),
1837 $this->mTitle, $parserOptions );
1838
1839 $previewHTML = $parserOutput->getText();
1840 $this->mParserOutput = $parserOutput;
1841 $wgOut->addParserOutputNoText( $parserOutput );
1842
1843 if ( count( $parserOutput->getWarnings() ) ) {
1844 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1845 }
1846 }
1847
1848 if( $this->isConflict ) {
1849 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1850 } else {
1851 $conflict = '<hr />';
1852 }
1853
1854 $previewhead = "<div class='previewnote'>\n" .
1855 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
1856 $wgOut->parse( $note ) . $conflict . "</div>\n";
1857
1858 wfProfileOut( __METHOD__ );
1859 return $previewhead . $previewHTML;
1860 }
1861
1862 function getTemplates() {
1863 if ( $this->preview || $this->section != '' ) {
1864 $templates = array();
1865 if ( !isset($this->mParserOutput) ) return $templates;
1866 foreach( $this->mParserOutput->getTemplates() as $ns => $template) {
1867 foreach( array_keys( $template ) as $dbk ) {
1868 $templates[] = Title::makeTitle($ns, $dbk);
1869 }
1870 }
1871 return $templates;
1872 } else {
1873 return $this->mArticle->getUsedTemplates();
1874 }
1875 }
1876
1877 /**
1878 * Call the stock "user is blocked" page
1879 */
1880 function blockedPage() {
1881 global $wgOut, $wgUser;
1882 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1883
1884 # If the user made changes, preserve them when showing the markup
1885 # (This happens when a user is blocked during edit, for instance)
1886 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1887 if ( $first ) {
1888 $source = $this->mTitle->exists() ? $this->getContent() : false;
1889 } else {
1890 $source = $this->textbox1;
1891 }
1892
1893 # Spit out the source or the user's modified version
1894 if ( $source !== false ) {
1895 $rows = $wgUser->getIntOption( 'rows' );
1896 $cols = $wgUser->getIntOption( 'cols' );
1897 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1898 $wgOut->addHTML( '<hr />' );
1899 $wgOut->addWikiMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() );
1900 # Why we don't use Xml::element here?
1901 # Is it because if $source is '', it returns <textarea />?
1902 $wgOut->addHTML( Xml::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml::closeElement( 'textarea' ) );
1903 }
1904 }
1905
1906 /**
1907 * Produce the stock "please login to edit pages" page
1908 */
1909 function userNotLoggedInPage() {
1910 global $wgUser, $wgOut, $wgTitle;
1911 $skin = $wgUser->getSkin();
1912
1913 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1914 $loginLink = $skin->link(
1915 $loginTitle,
1916 wfMsgHtml( 'loginreqlink' ),
1917 array(),
1918 array( 'returnto' => $wgTitle->getPrefixedText() ),
1919 array( 'known', 'noclasses' )
1920 );
1921
1922 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1923 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1924 $wgOut->setArticleRelated( false );
1925
1926 $wgOut->addHTML( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1927 $wgOut->returnToMain( false, $wgTitle );
1928 }
1929
1930 /**
1931 * Creates a basic error page which informs the user that
1932 * they have attempted to edit a nonexistent section.
1933 */
1934 function noSuchSectionPage() {
1935 global $wgOut, $wgTitle;
1936
1937 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1938 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1939 $wgOut->setArticleRelated( false );
1940
1941 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section );
1942 $wgOut->returnToMain( false, $wgTitle );
1943 }
1944
1945 /**
1946 * Produce the stock "your edit contains spam" page
1947 *
1948 * @param $match Text which triggered one or more filters
1949 */
1950 function spamPage( $match = false ) {
1951 global $wgOut, $wgTitle;
1952
1953 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1954 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1955 $wgOut->setArticleRelated( false );
1956
1957 $wgOut->addHTML( '<div id="spamprotected">' );
1958 $wgOut->addWikiMsg( 'spamprotectiontext' );
1959 if ( $match )
1960 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1961 $wgOut->addHTML( '</div>' );
1962
1963 $wgOut->returnToMain( false, $wgTitle );
1964 }
1965
1966 /**
1967 * @private
1968 * @todo document
1969 */
1970 function mergeChangesInto( &$editText ){
1971 $fname = 'EditPage::mergeChangesInto';
1972 wfProfileIn( $fname );
1973
1974 $db = wfGetDB( DB_MASTER );
1975
1976 // This is the revision the editor started from
1977 $baseRevision = $this->getBaseRevision();
1978 if ( is_null( $baseRevision ) ) {
1979 wfProfileOut( $fname );
1980 return false;
1981 }
1982 $baseText = $baseRevision->getText();
1983
1984 // The current state, we want to merge updates into it
1985 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
1986 if ( is_null( $currentRevision ) ) {
1987 wfProfileOut( $fname );
1988 return false;
1989 }
1990 $currentText = $currentRevision->getText();
1991
1992 $result = '';
1993 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1994 $editText = $result;
1995 wfProfileOut( $fname );
1996 return true;
1997 } else {
1998 wfProfileOut( $fname );
1999 return false;
2000 }
2001 }
2002
2003 /**
2004 * Check if the browser is on a blacklist of user-agents known to
2005 * mangle UTF-8 data on form submission. Returns true if Unicode
2006 * should make it through, false if it's known to be a problem.
2007 * @return bool
2008 * @private
2009 */
2010 function checkUnicodeCompliantBrowser() {
2011 global $wgBrowserBlackList;
2012 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2013 // No User-Agent header sent? Trust it by default...
2014 return true;
2015 }
2016 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2017 foreach ( $wgBrowserBlackList as $browser ) {
2018 if ( preg_match($browser, $currentbrowser) ) {
2019 return false;
2020 }
2021 }
2022 return true;
2023 }
2024
2025 /**
2026 * @deprecated use $wgParser->stripSectionName()
2027 */
2028 function pseudoParseSectionAnchor( $text ) {
2029 global $wgParser;
2030 return $wgParser->stripSectionName( $text );
2031 }
2032
2033 /**
2034 * Format an anchor fragment as it would appear for a given section name
2035 * @param string $text
2036 * @return string
2037 * @private
2038 */
2039 function sectionAnchor( $text ) {
2040 global $wgParser;
2041 return $wgParser->guessSectionNameFromWikiText( $text );
2042 }
2043
2044 /**
2045 * Shows a bulletin board style toolbar for common editing functions.
2046 * It can be disabled in the user preferences.
2047 * The necessary JavaScript code can be found in skins/common/edit.js.
2048 *
2049 * @return string
2050 */
2051 static function getEditToolbar() {
2052 global $wgStylePath, $wgContLang, $wgLang;
2053
2054 /**
2055 * toolarray an array of arrays which each include the filename of
2056 * the button image (without path), the opening tag, the closing tag,
2057 * and optionally a sample text that is inserted between the two when no
2058 * selection is highlighted.
2059 * The tip text is shown when the user moves the mouse over the button.
2060 *
2061 * Already here are accesskeys (key), which are not used yet until someone
2062 * can figure out a way to make them work in IE. However, we should make
2063 * sure these keys are not defined on the edit page.
2064 */
2065 $toolarray = array(
2066 array(
2067 'image' => $wgLang->getImageFile('button-bold'),
2068 'id' => 'mw-editbutton-bold',
2069 'open' => '\'\'\'',
2070 'close' => '\'\'\'',
2071 'sample' => wfMsg('bold_sample'),
2072 'tip' => wfMsg('bold_tip'),
2073 'key' => 'B'
2074 ),
2075 array(
2076 'image' => $wgLang->getImageFile('button-italic'),
2077 'id' => 'mw-editbutton-italic',
2078 'open' => '\'\'',
2079 'close' => '\'\'',
2080 'sample' => wfMsg('italic_sample'),
2081 'tip' => wfMsg('italic_tip'),
2082 'key' => 'I'
2083 ),
2084 array(
2085 'image' => $wgLang->getImageFile('button-link'),
2086 'id' => 'mw-editbutton-link',
2087 'open' => '[[',
2088 'close' => ']]',
2089 'sample' => wfMsg('link_sample'),
2090 'tip' => wfMsg('link_tip'),
2091 'key' => 'L'
2092 ),
2093 array(
2094 'image' => $wgLang->getImageFile('button-extlink'),
2095 'id' => 'mw-editbutton-extlink',
2096 'open' => '[',
2097 'close' => ']',
2098 'sample' => wfMsg('extlink_sample'),
2099 'tip' => wfMsg('extlink_tip'),
2100 'key' => 'X'
2101 ),
2102 array(
2103 'image' => $wgLang->getImageFile('button-headline'),
2104 'id' => 'mw-editbutton-headline',
2105 'open' => "\n== ",
2106 'close' => " ==\n",
2107 'sample' => wfMsg('headline_sample'),
2108 'tip' => wfMsg('headline_tip'),
2109 'key' => 'H'
2110 ),
2111 array(
2112 'image' => $wgLang->getImageFile('button-image'),
2113 'id' => 'mw-editbutton-image',
2114 'open' => '[['.$wgContLang->getNsText(NS_FILE).':',
2115 'close' => ']]',
2116 'sample' => wfMsg('image_sample'),
2117 'tip' => wfMsg('image_tip'),
2118 'key' => 'D'
2119 ),
2120 array(
2121 'image' => $wgLang->getImageFile('button-media'),
2122 'id' => 'mw-editbutton-media',
2123 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
2124 'close' => ']]',
2125 'sample' => wfMsg('media_sample'),
2126 'tip' => wfMsg('media_tip'),
2127 'key' => 'M'
2128 ),
2129 array(
2130 'image' => $wgLang->getImageFile('button-math'),
2131 'id' => 'mw-editbutton-math',
2132 'open' => "<math>",
2133 'close' => "</math>",
2134 'sample' => wfMsg('math_sample'),
2135 'tip' => wfMsg('math_tip'),
2136 'key' => 'C'
2137 ),
2138 array(
2139 'image' => $wgLang->getImageFile('button-nowiki'),
2140 'id' => 'mw-editbutton-nowiki',
2141 'open' => "<nowiki>",
2142 'close' => "</nowiki>",
2143 'sample' => wfMsg('nowiki_sample'),
2144 'tip' => wfMsg('nowiki_tip'),
2145 'key' => 'N'
2146 ),
2147 array(
2148 'image' => $wgLang->getImageFile('button-sig'),
2149 'id' => 'mw-editbutton-signature',
2150 'open' => '--~~~~',
2151 'close' => '',
2152 'sample' => '',
2153 'tip' => wfMsg('sig_tip'),
2154 'key' => 'Y'
2155 ),
2156 array(
2157 'image' => $wgLang->getImageFile('button-hr'),
2158 'id' => 'mw-editbutton-hr',
2159 'open' => "\n----\n",
2160 'close' => '',
2161 'sample' => '',
2162 'tip' => wfMsg('hr_tip'),
2163 'key' => 'R'
2164 )
2165 );
2166 $toolbar = "<div id='toolbar'>\n";
2167
2168 $script = '';
2169 foreach ( $toolarray as $tool ) {
2170 $params = array(
2171 $image = $wgStylePath.'/common/images/'.$tool['image'],
2172 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2173 // Older browsers show a "speedtip" type message only for ALT.
2174 // Ideally these should be different, realistically they
2175 // probably don't need to be.
2176 $tip = $tool['tip'],
2177 $open = $tool['open'],
2178 $close = $tool['close'],
2179 $sample = $tool['sample'],
2180 $cssId = $tool['id'],
2181 );
2182
2183 $paramList = implode( ',',
2184 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2185 $script .= "addButton($paramList);\n";
2186 }
2187 $toolbar .= Html::inlineScript( "\n$script\n" );
2188
2189 $toolbar .= "\n</div>";
2190
2191 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2192
2193 return $toolbar;
2194 }
2195
2196 /**
2197 * Returns an array of html code of the following checkboxes:
2198 * minor and watch
2199 *
2200 * @param $tabindex Current tabindex
2201 * @param $skin Skin object
2202 * @param $checked Array of checkbox => bool, where bool indicates the checked
2203 * status of the checkbox
2204 *
2205 * @return array
2206 */
2207 public function getCheckboxes( &$tabindex, $skin, $checked ) {
2208 global $wgUser;
2209
2210 $checkboxes = array();
2211
2212 $checkboxes['minor'] = '';
2213 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
2214 if ( $wgUser->isAllowed('minoredit') ) {
2215 $attribs = array(
2216 'tabindex' => ++$tabindex,
2217 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2218 'id' => 'wpMinoredit',
2219 );
2220 $checkboxes['minor'] =
2221 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2222 "&nbsp;<label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>";
2223 }
2224
2225 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
2226 $checkboxes['watch'] = '';
2227 if ( $wgUser->isLoggedIn() ) {
2228 $attribs = array(
2229 'tabindex' => ++$tabindex,
2230 'accesskey' => wfMsg( 'accesskey-watch' ),
2231 'id' => 'wpWatchthis',
2232 );
2233 $checkboxes['watch'] =
2234 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2235 "&nbsp;<label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>";
2236 }
2237 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2238 return $checkboxes;
2239 }
2240
2241 /**
2242 * Returns an array of html code of the following buttons:
2243 * save, diff, preview and live
2244 *
2245 * @param $tabindex Current tabindex
2246 *
2247 * @return array
2248 */
2249 public function getEditButtons(&$tabindex) {
2250 global $wgLivePreview, $wgUser;
2251
2252 $buttons = array();
2253
2254 $temp = array(
2255 'id' => 'wpSave',
2256 'name' => 'wpSave',
2257 'type' => 'submit',
2258 'tabindex' => ++$tabindex,
2259 'value' => wfMsg('savearticle'),
2260 'accesskey' => wfMsg('accesskey-save'),
2261 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2262 );
2263 $buttons['save'] = Xml::element('input', $temp, '');
2264
2265 ++$tabindex; // use the same for preview and live preview
2266 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
2267 $this->doLivePreviewScript(); // Add to output
2268
2269 $temp = array(
2270 'id' => 'wpPreview',
2271 'name' => 'wpPreview',
2272 'type' => 'submit',
2273 'tabindex' => $tabindex,
2274 'value' => wfMsg('showpreview'),
2275 'accesskey' => '',
2276 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2277 'style' => 'display: none;',
2278 );
2279 $buttons['preview'] = Xml::element('input', $temp, '');
2280
2281 $temp = array(
2282 'id' => 'wpLivePreview',
2283 'name' => 'wpLivePreview',
2284 'type' => 'submit',
2285 'tabindex' => $tabindex,
2286 'value' => wfMsg('showlivepreview'),
2287 'accesskey' => wfMsg('accesskey-preview'),
2288 'title' => '',
2289 );
2290
2291 $buttons['live'] = Xml::element('input', $temp, '');
2292 } else {
2293 $temp = array(
2294 'id' => 'wpPreview',
2295 'name' => 'wpPreview',
2296 'type' => 'submit',
2297 'tabindex' => $tabindex,
2298 'value' => wfMsg('showpreview'),
2299 'accesskey' => wfMsg('accesskey-preview'),
2300 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2301 );
2302 $buttons['preview'] = Xml::element('input', $temp, '');
2303 $buttons['live'] = '';
2304 }
2305
2306 $temp = array(
2307 'id' => 'wpDiff',
2308 'name' => 'wpDiff',
2309 'type' => 'submit',
2310 'tabindex' => ++$tabindex,
2311 'value' => wfMsg('showdiff'),
2312 'accesskey' => wfMsg('accesskey-diff'),
2313 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2314 );
2315 $buttons['diff'] = Xml::element('input', $temp, '');
2316
2317 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2318 return $buttons;
2319 }
2320
2321 /**
2322 * Output preview text only. This can be sucked into the edit page
2323 * via JavaScript, and saves the server time rendering the skin as
2324 * well as theoretically being more robust on the client (doesn't
2325 * disturb the edit box's undo history, won't eat your text on
2326 * failure, etc).
2327 *
2328 * @todo This doesn't include category or interlanguage links.
2329 * Would need to enhance it a bit, <s>maybe wrap them in XML
2330 * or something...</s> that might also require more skin
2331 * initialization, so check whether that's a problem.
2332 */
2333 function livePreview() {
2334 global $wgOut;
2335 $wgOut->disable();
2336 header( 'Content-type: text/xml; charset=utf-8' );
2337 header( 'Cache-control: no-cache' );
2338
2339 $previewText = $this->getPreviewText();
2340 #$categories = $skin->getCategoryLinks();
2341
2342 $s =
2343 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2344 Xml::tags( 'livepreview', null,
2345 Xml::element( 'preview', null, $previewText )
2346 #. Xml::element( 'category', null, $categories )
2347 );
2348 echo $s;
2349 }
2350
2351
2352 /**
2353 * Get a diff between the current contents of the edit box and the
2354 * version of the page we're editing from.
2355 *
2356 * If this is a section edit, we'll replace the section as for final
2357 * save and then make a comparison.
2358 */
2359 function showDiff() {
2360 $oldtext = $this->mArticle->fetchContent();
2361 $newtext = $this->mArticle->replaceSection(
2362 $this->section, $this->textbox1, $this->summary, $this->edittime );
2363 $newtext = $this->mArticle->preSaveTransform( $newtext );
2364 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2365 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2366 if ( $oldtext !== false || $newtext != '' ) {
2367 $de = new DifferenceEngine( $this->mTitle );
2368 $de->setText( $oldtext, $newtext );
2369 $difftext = $de->getDiff( $oldtitle, $newtitle );
2370 $de->showDiffStyle();
2371 } else {
2372 $difftext = '';
2373 }
2374
2375 global $wgOut;
2376 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2377 }
2378
2379 /**
2380 * Filter an input field through a Unicode de-armoring process if it
2381 * came from an old browser with known broken Unicode editing issues.
2382 *
2383 * @param WebRequest $request
2384 * @param string $field
2385 * @return string
2386 * @private
2387 */
2388 function safeUnicodeInput( $request, $field ) {
2389 $text = rtrim( $request->getText( $field ) );
2390 return $request->getBool( 'safemode' )
2391 ? $this->unmakesafe( $text )
2392 : $text;
2393 }
2394
2395 /**
2396 * Filter an output field through a Unicode armoring process if it is
2397 * going to an old browser with known broken Unicode editing issues.
2398 *
2399 * @param string $text
2400 * @return string
2401 * @private
2402 */
2403 function safeUnicodeOutput( $text ) {
2404 global $wgContLang;
2405 $codedText = $wgContLang->recodeForEdit( $text );
2406 return $this->checkUnicodeCompliantBrowser()
2407 ? $codedText
2408 : $this->makesafe( $codedText );
2409 }
2410
2411 /**
2412 * A number of web browsers are known to corrupt non-ASCII characters
2413 * in a UTF-8 text editing environment. To protect against this,
2414 * detected browsers will be served an armored version of the text,
2415 * with non-ASCII chars converted to numeric HTML character references.
2416 *
2417 * Preexisting such character references will have a 0 added to them
2418 * to ensure that round-trips do not alter the original data.
2419 *
2420 * @param string $invalue
2421 * @return string
2422 * @private
2423 */
2424 function makesafe( $invalue ) {
2425 // Armor existing references for reversability.
2426 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
2427
2428 $bytesleft = 0;
2429 $result = "";
2430 $working = 0;
2431 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2432 $bytevalue = ord( $invalue{$i} );
2433 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2434 $result .= chr( $bytevalue );
2435 $bytesleft = 0;
2436 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2437 $working = $working << 6;
2438 $working += ($bytevalue & 0x3F);
2439 $bytesleft--;
2440 if ( $bytesleft <= 0 ) {
2441 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2442 }
2443 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2444 $working = $bytevalue & 0x1F;
2445 $bytesleft = 1;
2446 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2447 $working = $bytevalue & 0x0F;
2448 $bytesleft = 2;
2449 } else { //1111 0xxx
2450 $working = $bytevalue & 0x07;
2451 $bytesleft = 3;
2452 }
2453 }
2454 return $result;
2455 }
2456
2457 /**
2458 * Reverse the previously applied transliteration of non-ASCII characters
2459 * back to UTF-8. Used to protect data from corruption by broken web browsers
2460 * as listed in $wgBrowserBlackList.
2461 *
2462 * @param string $invalue
2463 * @return string
2464 * @private
2465 */
2466 function unmakesafe( $invalue ) {
2467 $result = "";
2468 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2469 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
2470 $i += 3;
2471 $hexstring = "";
2472 do {
2473 $hexstring .= $invalue{$i};
2474 $i++;
2475 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2476
2477 // Do some sanity checks. These aren't needed for reversability,
2478 // but should help keep the breakage down if the editor
2479 // breaks one of the entities whilst editing.
2480 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2481 $codepoint = hexdec($hexstring);
2482 $result .= codepointToUtf8( $codepoint );
2483 } else {
2484 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2485 }
2486 } else {
2487 $result .= substr( $invalue, $i, 1 );
2488 }
2489 }
2490 // reverse the transform that we made for reversability reasons.
2491 return strtr( $result, array( "&#x0" => "&#x" ) );
2492 }
2493
2494 function noCreatePermission() {
2495 global $wgOut;
2496 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2497 $wgOut->addWikiMsg( 'nocreatetext' );
2498 }
2499
2500 /**
2501 * If there are rows in the deletion/move log for this page, show them,
2502 * along with a nice little note for the user
2503 *
2504 * @param OutputPage $out
2505 */
2506 protected function showLogs( $out ) {
2507 global $wgUser;
2508 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
2509 $pager = new LogPager( $loglist, array('move', 'delete'), false,
2510 $this->mTitle->getPrefixedText(), '', array( "log_action != 'revision'" ) );
2511
2512 $count = $pager->getNumRows();
2513 if ( $count > 0 ) {
2514 $pager->mLimit = 10;
2515 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
2516 $out->addWikiMsg( 'recreate-moveddeleted-warn' );
2517 $out->addHTML(
2518 $loglist->beginLogEventsList() .
2519 $pager->getBody() .
2520 $loglist->endLogEventsList()
2521 );
2522 if($count > 10){
2523 $out->addHTML( $wgUser->getSkin()->link(
2524 SpecialPage::getTitleFor( 'Log' ),
2525 wfMsgHtml( 'log-fulllog' ),
2526 array(),
2527 array( 'page' => $this->mTitle->getPrefixedText() ) ) );
2528 }
2529 $out->addHTML( '</div>' );
2530 return true;
2531 }
2532
2533 return false;
2534 }
2535
2536 /**
2537 * Attempt submission
2538 * @return bool false if output is done, true if the rest of the form should be displayed
2539 */
2540 function attemptSave() {
2541 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2542
2543 $resultDetails = false;
2544 # Allow bots to exempt some edits from bot flagging
2545 $bot = $wgUser->isAllowed('bot') && $wgRequest->getBool('bot',true);
2546 $value = $this->internalAttemptSave( $resultDetails, $bot );
2547
2548 if ( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) {
2549 $this->didSave = true;
2550 }
2551
2552 switch ($value) {
2553 case self::AS_HOOK_ERROR_EXPECTED:
2554 case self::AS_CONTENT_TOO_BIG:
2555 case self::AS_ARTICLE_WAS_DELETED:
2556 case self::AS_CONFLICT_DETECTED:
2557 case self::AS_SUMMARY_NEEDED:
2558 case self::AS_TEXTBOX_EMPTY:
2559 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
2560 case self::AS_END:
2561 return true;
2562
2563 case self::AS_HOOK_ERROR:
2564 case self::AS_FILTERING:
2565 case self::AS_SUCCESS_NEW_ARTICLE:
2566 case self::AS_SUCCESS_UPDATE:
2567 return false;
2568
2569 case self::AS_SPAM_ERROR:
2570 $this->spamPage ( $resultDetails['spam'] );
2571 return false;
2572
2573 case self::AS_BLOCKED_PAGE_FOR_USER:
2574 $this->blockedPage();
2575 return false;
2576
2577 case self::AS_IMAGE_REDIRECT_ANON:
2578 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2579 return false;
2580
2581 case self::AS_READ_ONLY_PAGE_ANON:
2582 $this->userNotLoggedInPage();
2583 return false;
2584
2585 case self::AS_READ_ONLY_PAGE_LOGGED:
2586 case self::AS_READ_ONLY_PAGE:
2587 $wgOut->readOnlyPage();
2588 return false;
2589
2590 case self::AS_RATE_LIMITED:
2591 $wgOut->rateLimited();
2592 return false;
2593
2594 case self::AS_NO_CREATE_PERMISSION;
2595 $this->noCreatePermission();
2596 return;
2597
2598 case self::AS_BLANK_ARTICLE:
2599 $wgOut->redirect( $wgTitle->getFullURL() );
2600 return false;
2601
2602 case self::AS_IMAGE_REDIRECT_LOGGED:
2603 $wgOut->permissionRequired( 'upload' );
2604 return false;
2605 }
2606 }
2607
2608 function getBaseRevision() {
2609 if ( $this->mBaseRevision == false ) {
2610 $db = wfGetDB( DB_MASTER );
2611 $baseRevision = Revision::loadFromTimestamp(
2612 $db, $this->mTitle, $this->edittime );
2613 return $this->mBaseRevision = $baseRevision;
2614 } else {
2615 return $this->mBaseRevision;
2616 }
2617 }
2618 }