For HTML 5, drop type="" attributes for CSS/JS
[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 } 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 ?
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 ) {
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 $liveAction = $wgTitle->getLocalUrl( array(
1710 'action' => $this->action,
1711 'wpPreview' => 'true',
1712 'live' => 'true'
1713 ) );
1714 return "return !lpDoPreview(" .
1715 "editform.wpTextbox1.value," .
1716 '"' . $liveAction . '"' . ")";
1717 }
1718
1719 protected function showTosSummary() {
1720 $msg = 'editpage-tos-summary';
1721 // Give a chance for site and per-namespace customizations of
1722 // terms of service summary link that might exist separately
1723 // from the copyright notice.
1724 //
1725 // This will display between the save button and the edit tools,
1726 // so should remain short!
1727 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
1728 $text = wfMsg( $msg );
1729 if( !wfEmptyMsg( $msg, $text ) && $text !== '-' ) {
1730 global $wgOut;
1731 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1732 $wgOut->addWikiMsgArray( $msg, array() );
1733 $wgOut->addHTML( '</div>' );
1734 }
1735 }
1736
1737 protected function showEditTools() {
1738 global $wgOut;
1739 $wgOut->addHTML( '<div class="mw-editTools">' );
1740 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1741 $wgOut->addHTML( '</div>' );
1742 }
1743
1744 protected function getLastDelete() {
1745 $dbr = wfGetDB( DB_SLAVE );
1746 $data = $dbr->selectRow(
1747 array( 'logging', 'user' ),
1748 array( 'log_type',
1749 'log_action',
1750 'log_timestamp',
1751 'log_user',
1752 'log_namespace',
1753 'log_title',
1754 'log_comment',
1755 'log_params',
1756 'log_deleted',
1757 'user_name' ),
1758 array( 'log_namespace' => $this->mTitle->getNamespace(),
1759 'log_title' => $this->mTitle->getDBkey(),
1760 'log_type' => 'delete',
1761 'log_action' => 'delete',
1762 'user_id=log_user' ),
1763 __METHOD__,
1764 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1765 );
1766 // Quick paranoid permission checks...
1767 if( is_object($data) ) {
1768 if( $data->log_deleted & LogPage::DELETED_USER )
1769 $data->user_name = wfMsgHtml('rev-deleted-user');
1770 if( $data->log_deleted & LogPage::DELETED_COMMENT )
1771 $data->log_comment = wfMsgHtml('rev-deleted-comment');
1772 }
1773 return $data;
1774 }
1775
1776 /**
1777 * Get the rendered text for previewing.
1778 * @return string
1779 */
1780 function getPreviewText() {
1781 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang, $wgMessageCache;
1782
1783 wfProfileIn( __METHOD__ );
1784
1785 if ( $this->mTriedSave && !$this->mTokenOk ) {
1786 if ( $this->mTokenOkExceptSuffix ) {
1787 $note = wfMsg( 'token_suffix_mismatch' );
1788 } else {
1789 $note = wfMsg( 'session_fail_preview' );
1790 }
1791 } else {
1792 $note = wfMsg( 'previewnote' );
1793 }
1794
1795 $parserOptions = ParserOptions::newFromUser( $wgUser );
1796 $parserOptions->setEditSection( false );
1797 $parserOptions->setIsPreview( true );
1798 $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' );
1799
1800 global $wgRawHtml;
1801 if ( $wgRawHtml && !$this->mTokenOk ) {
1802 // Could be an offsite preview attempt. This is very unsafe if
1803 // HTML is enabled, as it could be an attack.
1804 return $wgOut->parse( "<div class='previewnote'>" .
1805 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1806 }
1807
1808 # don't parse user css/js, show message about preview
1809 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1810
1811 if ( $this->isCssJsSubpage ) {
1812 if (preg_match("/\\.css$/", $this->mTitle->getText() ) ) {
1813 $previewtext = wfMsg('usercsspreview');
1814 } else if (preg_match("/\\.js$/", $this->mTitle->getText() ) ) {
1815 $previewtext = wfMsg('userjspreview');
1816 }
1817 $parserOptions->setTidy(true);
1818 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
1819 $previewHTML = $parserOutput->mText;
1820 } elseif ( $rt = Title::newFromRedirectArray( $this->textbox1 ) ) {
1821 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
1822 } else {
1823 $toparse = $this->textbox1;
1824
1825 # If we're adding a comment, we need to show the
1826 # summary as the headline
1827 if ( $this->section=="new" && $this->summary!="" ) {
1828 $toparse="== {$this->summary} ==\n\n".$toparse;
1829 }
1830
1831 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData;
1832
1833 // Parse mediawiki messages with correct target language
1834 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1835 list( /* $unused */, $lang ) = $wgMessageCache->figureMessage( $this->mTitle->getText() );
1836 $obj = wfGetLangObj( $lang );
1837 $parserOptions->setTargetLanguage( $obj );
1838 }
1839
1840
1841 $parserOptions->setTidy(true);
1842 $parserOptions->enableLimitReport();
1843 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ),
1844 $this->mTitle, $parserOptions );
1845
1846 $previewHTML = $parserOutput->getText();
1847 $this->mParserOutput = $parserOutput;
1848 $wgOut->addParserOutputNoText( $parserOutput );
1849
1850 if ( count( $parserOutput->getWarnings() ) ) {
1851 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1852 }
1853 }
1854
1855 if( $this->isConflict ) {
1856 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1857 } else {
1858 $conflict = '<hr />';
1859 }
1860
1861 $previewhead = "<div class='previewnote'>\n" .
1862 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
1863 $wgOut->parse( $note ) . $conflict . "</div>\n";
1864
1865 wfProfileOut( __METHOD__ );
1866 return $previewhead . $previewHTML;
1867 }
1868
1869 function getTemplates() {
1870 if ( $this->preview || $this->section != '' ) {
1871 $templates = array();
1872 if ( !isset($this->mParserOutput) ) return $templates;
1873 foreach( $this->mParserOutput->getTemplates() as $ns => $template) {
1874 foreach( array_keys( $template ) as $dbk ) {
1875 $templates[] = Title::makeTitle($ns, $dbk);
1876 }
1877 }
1878 return $templates;
1879 } else {
1880 return $this->mArticle->getUsedTemplates();
1881 }
1882 }
1883
1884 /**
1885 * Call the stock "user is blocked" page
1886 */
1887 function blockedPage() {
1888 global $wgOut, $wgUser;
1889 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1890
1891 # If the user made changes, preserve them when showing the markup
1892 # (This happens when a user is blocked during edit, for instance)
1893 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1894 if ( $first ) {
1895 $source = $this->mTitle->exists() ? $this->getContent() : false;
1896 } else {
1897 $source = $this->textbox1;
1898 }
1899
1900 # Spit out the source or the user's modified version
1901 if ( $source !== false ) {
1902 $rows = $wgUser->getIntOption( 'rows' );
1903 $cols = $wgUser->getIntOption( 'cols' );
1904 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1905 $wgOut->addHTML( '<hr />' );
1906 $wgOut->addWikiMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() );
1907 # Why we don't use Xml::element here?
1908 # Is it because if $source is '', it returns <textarea />?
1909 $wgOut->addHTML( Xml::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml::closeElement( 'textarea' ) );
1910 }
1911 }
1912
1913 /**
1914 * Produce the stock "please login to edit pages" page
1915 */
1916 function userNotLoggedInPage() {
1917 global $wgUser, $wgOut, $wgTitle;
1918 $skin = $wgUser->getSkin();
1919
1920 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1921 $loginLink = $skin->link(
1922 $loginTitle,
1923 wfMsgHtml( 'loginreqlink' ),
1924 array(),
1925 array( 'returnto' => $wgTitle->getPrefixedText() ),
1926 array( 'known', 'noclasses' )
1927 );
1928
1929 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1930 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1931 $wgOut->setArticleRelated( false );
1932
1933 $wgOut->addHTML( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1934 $wgOut->returnToMain( false, $wgTitle );
1935 }
1936
1937 /**
1938 * Creates a basic error page which informs the user that
1939 * they have attempted to edit a nonexistent section.
1940 */
1941 function noSuchSectionPage() {
1942 global $wgOut, $wgTitle;
1943
1944 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1945 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1946 $wgOut->setArticleRelated( false );
1947
1948 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section );
1949 $wgOut->returnToMain( false, $wgTitle );
1950 }
1951
1952 /**
1953 * Produce the stock "your edit contains spam" page
1954 *
1955 * @param $match Text which triggered one or more filters
1956 */
1957 function spamPage( $match = false ) {
1958 global $wgOut, $wgTitle;
1959
1960 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1961 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1962 $wgOut->setArticleRelated( false );
1963
1964 $wgOut->addHTML( '<div id="spamprotected">' );
1965 $wgOut->addWikiMsg( 'spamprotectiontext' );
1966 if ( $match )
1967 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1968 $wgOut->addHTML( '</div>' );
1969
1970 $wgOut->returnToMain( false, $wgTitle );
1971 }
1972
1973 /**
1974 * @private
1975 * @todo document
1976 */
1977 function mergeChangesInto( &$editText ){
1978 $fname = 'EditPage::mergeChangesInto';
1979 wfProfileIn( $fname );
1980
1981 $db = wfGetDB( DB_MASTER );
1982
1983 // This is the revision the editor started from
1984 $baseRevision = $this->getBaseRevision();
1985 if ( is_null( $baseRevision ) ) {
1986 wfProfileOut( $fname );
1987 return false;
1988 }
1989 $baseText = $baseRevision->getText();
1990
1991 // The current state, we want to merge updates into it
1992 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
1993 if ( is_null( $currentRevision ) ) {
1994 wfProfileOut( $fname );
1995 return false;
1996 }
1997 $currentText = $currentRevision->getText();
1998
1999 $result = '';
2000 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
2001 $editText = $result;
2002 wfProfileOut( $fname );
2003 return true;
2004 } else {
2005 wfProfileOut( $fname );
2006 return false;
2007 }
2008 }
2009
2010 /**
2011 * Check if the browser is on a blacklist of user-agents known to
2012 * mangle UTF-8 data on form submission. Returns true if Unicode
2013 * should make it through, false if it's known to be a problem.
2014 * @return bool
2015 * @private
2016 */
2017 function checkUnicodeCompliantBrowser() {
2018 global $wgBrowserBlackList;
2019 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2020 // No User-Agent header sent? Trust it by default...
2021 return true;
2022 }
2023 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2024 foreach ( $wgBrowserBlackList as $browser ) {
2025 if ( preg_match($browser, $currentbrowser) ) {
2026 return false;
2027 }
2028 }
2029 return true;
2030 }
2031
2032 /**
2033 * @deprecated use $wgParser->stripSectionName()
2034 */
2035 function pseudoParseSectionAnchor( $text ) {
2036 global $wgParser;
2037 return $wgParser->stripSectionName( $text );
2038 }
2039
2040 /**
2041 * Format an anchor fragment as it would appear for a given section name
2042 * @param string $text
2043 * @return string
2044 * @private
2045 */
2046 function sectionAnchor( $text ) {
2047 global $wgParser;
2048 return $wgParser->guessSectionNameFromWikiText( $text );
2049 }
2050
2051 /**
2052 * Shows a bulletin board style toolbar for common editing functions.
2053 * It can be disabled in the user preferences.
2054 * The necessary JavaScript code can be found in skins/common/edit.js.
2055 *
2056 * @return string
2057 */
2058 static function getEditToolbar() {
2059 global $wgStylePath, $wgContLang, $wgLang;
2060
2061 /**
2062 * toolarray an array of arrays which each include the filename of
2063 * the button image (without path), the opening tag, the closing tag,
2064 * and optionally a sample text that is inserted between the two when no
2065 * selection is highlighted.
2066 * The tip text is shown when the user moves the mouse over the button.
2067 *
2068 * Already here are accesskeys (key), which are not used yet until someone
2069 * can figure out a way to make them work in IE. However, we should make
2070 * sure these keys are not defined on the edit page.
2071 */
2072 $toolarray = array(
2073 array(
2074 'image' => $wgLang->getImageFile('button-bold'),
2075 'id' => 'mw-editbutton-bold',
2076 'open' => '\'\'\'',
2077 'close' => '\'\'\'',
2078 'sample' => wfMsg('bold_sample'),
2079 'tip' => wfMsg('bold_tip'),
2080 'key' => 'B'
2081 ),
2082 array(
2083 'image' => $wgLang->getImageFile('button-italic'),
2084 'id' => 'mw-editbutton-italic',
2085 'open' => '\'\'',
2086 'close' => '\'\'',
2087 'sample' => wfMsg('italic_sample'),
2088 'tip' => wfMsg('italic_tip'),
2089 'key' => 'I'
2090 ),
2091 array(
2092 'image' => $wgLang->getImageFile('button-link'),
2093 'id' => 'mw-editbutton-link',
2094 'open' => '[[',
2095 'close' => ']]',
2096 'sample' => wfMsg('link_sample'),
2097 'tip' => wfMsg('link_tip'),
2098 'key' => 'L'
2099 ),
2100 array(
2101 'image' => $wgLang->getImageFile('button-extlink'),
2102 'id' => 'mw-editbutton-extlink',
2103 'open' => '[',
2104 'close' => ']',
2105 'sample' => wfMsg('extlink_sample'),
2106 'tip' => wfMsg('extlink_tip'),
2107 'key' => 'X'
2108 ),
2109 array(
2110 'image' => $wgLang->getImageFile('button-headline'),
2111 'id' => 'mw-editbutton-headline',
2112 'open' => "\n== ",
2113 'close' => " ==\n",
2114 'sample' => wfMsg('headline_sample'),
2115 'tip' => wfMsg('headline_tip'),
2116 'key' => 'H'
2117 ),
2118 array(
2119 'image' => $wgLang->getImageFile('button-image'),
2120 'id' => 'mw-editbutton-image',
2121 'open' => '[['.$wgContLang->getNsText(NS_FILE).':',
2122 'close' => ']]',
2123 'sample' => wfMsg('image_sample'),
2124 'tip' => wfMsg('image_tip'),
2125 'key' => 'D'
2126 ),
2127 array(
2128 'image' => $wgLang->getImageFile('button-media'),
2129 'id' => 'mw-editbutton-media',
2130 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
2131 'close' => ']]',
2132 'sample' => wfMsg('media_sample'),
2133 'tip' => wfMsg('media_tip'),
2134 'key' => 'M'
2135 ),
2136 array(
2137 'image' => $wgLang->getImageFile('button-math'),
2138 'id' => 'mw-editbutton-math',
2139 'open' => "<math>",
2140 'close' => "</math>",
2141 'sample' => wfMsg('math_sample'),
2142 'tip' => wfMsg('math_tip'),
2143 'key' => 'C'
2144 ),
2145 array(
2146 'image' => $wgLang->getImageFile('button-nowiki'),
2147 'id' => 'mw-editbutton-nowiki',
2148 'open' => "<nowiki>",
2149 'close' => "</nowiki>",
2150 'sample' => wfMsg('nowiki_sample'),
2151 'tip' => wfMsg('nowiki_tip'),
2152 'key' => 'N'
2153 ),
2154 array(
2155 'image' => $wgLang->getImageFile('button-sig'),
2156 'id' => 'mw-editbutton-signature',
2157 'open' => '--~~~~',
2158 'close' => '',
2159 'sample' => '',
2160 'tip' => wfMsg('sig_tip'),
2161 'key' => 'Y'
2162 ),
2163 array(
2164 'image' => $wgLang->getImageFile('button-hr'),
2165 'id' => 'mw-editbutton-hr',
2166 'open' => "\n----\n",
2167 'close' => '',
2168 'sample' => '',
2169 'tip' => wfMsg('hr_tip'),
2170 'key' => 'R'
2171 )
2172 );
2173 $toolbar = "<div id='toolbar'>\n";
2174
2175 $script = '';
2176 foreach ( $toolarray as $tool ) {
2177 $params = array(
2178 $image = $wgStylePath.'/common/images/'.$tool['image'],
2179 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2180 // Older browsers show a "speedtip" type message only for ALT.
2181 // Ideally these should be different, realistically they
2182 // probably don't need to be.
2183 $tip = $tool['tip'],
2184 $open = $tool['open'],
2185 $close = $tool['close'],
2186 $sample = $tool['sample'],
2187 $cssId = $tool['id'],
2188 );
2189
2190 $paramList = implode( ',',
2191 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2192 $script .= "addButton($paramList);\n";
2193 }
2194 $toolbar .= Html::inlineScript( "\n$script\n" );
2195
2196 $toolbar .= "\n</div>";
2197
2198 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2199
2200 return $toolbar;
2201 }
2202
2203 /**
2204 * Returns an array of html code of the following checkboxes:
2205 * minor and watch
2206 *
2207 * @param $tabindex Current tabindex
2208 * @param $skin Skin object
2209 * @param $checked Array of checkbox => bool, where bool indicates the checked
2210 * status of the checkbox
2211 *
2212 * @return array
2213 */
2214 public function getCheckboxes( &$tabindex, $skin, $checked ) {
2215 global $wgUser;
2216
2217 $checkboxes = array();
2218
2219 $checkboxes['minor'] = '';
2220 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
2221 if ( $wgUser->isAllowed('minoredit') ) {
2222 $attribs = array(
2223 'tabindex' => ++$tabindex,
2224 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2225 'id' => 'wpMinoredit',
2226 );
2227 $checkboxes['minor'] =
2228 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2229 "&nbsp;<label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>";
2230 }
2231
2232 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
2233 $checkboxes['watch'] = '';
2234 if ( $wgUser->isLoggedIn() ) {
2235 $attribs = array(
2236 'tabindex' => ++$tabindex,
2237 'accesskey' => wfMsg( 'accesskey-watch' ),
2238 'id' => 'wpWatchthis',
2239 );
2240 $checkboxes['watch'] =
2241 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2242 "&nbsp;<label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>";
2243 }
2244 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2245 return $checkboxes;
2246 }
2247
2248 /**
2249 * Returns an array of html code of the following buttons:
2250 * save, diff, preview and live
2251 *
2252 * @param $tabindex Current tabindex
2253 *
2254 * @return array
2255 */
2256 public function getEditButtons(&$tabindex) {
2257 global $wgLivePreview, $wgUser;
2258
2259 $buttons = array();
2260
2261 $temp = array(
2262 'id' => 'wpSave',
2263 'name' => 'wpSave',
2264 'type' => 'submit',
2265 'tabindex' => ++$tabindex,
2266 'value' => wfMsg('savearticle'),
2267 'accesskey' => wfMsg('accesskey-save'),
2268 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2269 );
2270 $buttons['save'] = Xml::element('input', $temp, '');
2271
2272 ++$tabindex; // use the same for preview and live preview
2273 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
2274 $temp = array(
2275 'id' => 'wpPreview',
2276 'name' => 'wpPreview',
2277 'type' => 'submit',
2278 'tabindex' => $tabindex,
2279 'value' => wfMsg('showpreview'),
2280 'accesskey' => '',
2281 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2282 'style' => 'display: none;',
2283 );
2284 $buttons['preview'] = Xml::element('input', $temp, '');
2285
2286 $temp = array(
2287 'id' => 'wpLivePreview',
2288 'name' => 'wpLivePreview',
2289 'type' => 'submit',
2290 'tabindex' => $tabindex,
2291 'value' => wfMsg('showlivepreview'),
2292 'accesskey' => wfMsg('accesskey-preview'),
2293 'title' => '',
2294 'onclick' => $this->doLivePreviewScript(),
2295 );
2296 $buttons['live'] = Xml::element('input', $temp, '');
2297 } else {
2298 $temp = array(
2299 'id' => 'wpPreview',
2300 'name' => 'wpPreview',
2301 'type' => 'submit',
2302 'tabindex' => $tabindex,
2303 'value' => wfMsg('showpreview'),
2304 'accesskey' => wfMsg('accesskey-preview'),
2305 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2306 );
2307 $buttons['preview'] = Xml::element('input', $temp, '');
2308 $buttons['live'] = '';
2309 }
2310
2311 $temp = array(
2312 'id' => 'wpDiff',
2313 'name' => 'wpDiff',
2314 'type' => 'submit',
2315 'tabindex' => ++$tabindex,
2316 'value' => wfMsg('showdiff'),
2317 'accesskey' => wfMsg('accesskey-diff'),
2318 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2319 );
2320 $buttons['diff'] = Xml::element('input', $temp, '');
2321
2322 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2323 return $buttons;
2324 }
2325
2326 /**
2327 * Output preview text only. This can be sucked into the edit page
2328 * via JavaScript, and saves the server time rendering the skin as
2329 * well as theoretically being more robust on the client (doesn't
2330 * disturb the edit box's undo history, won't eat your text on
2331 * failure, etc).
2332 *
2333 * @todo This doesn't include category or interlanguage links.
2334 * Would need to enhance it a bit, <s>maybe wrap them in XML
2335 * or something...</s> that might also require more skin
2336 * initialization, so check whether that's a problem.
2337 */
2338 function livePreview() {
2339 global $wgOut;
2340 $wgOut->disable();
2341 header( 'Content-type: text/xml; charset=utf-8' );
2342 header( 'Cache-control: no-cache' );
2343
2344 $previewText = $this->getPreviewText();
2345 #$categories = $skin->getCategoryLinks();
2346
2347 $s =
2348 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2349 Xml::tags( 'livepreview', null,
2350 Xml::element( 'preview', null, $previewText )
2351 #. Xml::element( 'category', null, $categories )
2352 );
2353 echo $s;
2354 }
2355
2356
2357 /**
2358 * Get a diff between the current contents of the edit box and the
2359 * version of the page we're editing from.
2360 *
2361 * If this is a section edit, we'll replace the section as for final
2362 * save and then make a comparison.
2363 */
2364 function showDiff() {
2365 $oldtext = $this->mArticle->fetchContent();
2366 $newtext = $this->mArticle->replaceSection(
2367 $this->section, $this->textbox1, $this->summary, $this->edittime );
2368 $newtext = $this->mArticle->preSaveTransform( $newtext );
2369 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2370 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2371 if ( $oldtext !== false || $newtext != '' ) {
2372 $de = new DifferenceEngine( $this->mTitle );
2373 $de->setText( $oldtext, $newtext );
2374 $difftext = $de->getDiff( $oldtitle, $newtitle );
2375 $de->showDiffStyle();
2376 } else {
2377 $difftext = '';
2378 }
2379
2380 global $wgOut;
2381 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2382 }
2383
2384 /**
2385 * Filter an input field through a Unicode de-armoring process if it
2386 * came from an old browser with known broken Unicode editing issues.
2387 *
2388 * @param WebRequest $request
2389 * @param string $field
2390 * @return string
2391 * @private
2392 */
2393 function safeUnicodeInput( $request, $field ) {
2394 $text = rtrim( $request->getText( $field ) );
2395 return $request->getBool( 'safemode' )
2396 ? $this->unmakesafe( $text )
2397 : $text;
2398 }
2399
2400 /**
2401 * Filter an output field through a Unicode armoring process if it is
2402 * going to an old browser with known broken Unicode editing issues.
2403 *
2404 * @param string $text
2405 * @return string
2406 * @private
2407 */
2408 function safeUnicodeOutput( $text ) {
2409 global $wgContLang;
2410 $codedText = $wgContLang->recodeForEdit( $text );
2411 return $this->checkUnicodeCompliantBrowser()
2412 ? $codedText
2413 : $this->makesafe( $codedText );
2414 }
2415
2416 /**
2417 * A number of web browsers are known to corrupt non-ASCII characters
2418 * in a UTF-8 text editing environment. To protect against this,
2419 * detected browsers will be served an armored version of the text,
2420 * with non-ASCII chars converted to numeric HTML character references.
2421 *
2422 * Preexisting such character references will have a 0 added to them
2423 * to ensure that round-trips do not alter the original data.
2424 *
2425 * @param string $invalue
2426 * @return string
2427 * @private
2428 */
2429 function makesafe( $invalue ) {
2430 // Armor existing references for reversability.
2431 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
2432
2433 $bytesleft = 0;
2434 $result = "";
2435 $working = 0;
2436 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2437 $bytevalue = ord( $invalue{$i} );
2438 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2439 $result .= chr( $bytevalue );
2440 $bytesleft = 0;
2441 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2442 $working = $working << 6;
2443 $working += ($bytevalue & 0x3F);
2444 $bytesleft--;
2445 if ( $bytesleft <= 0 ) {
2446 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2447 }
2448 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2449 $working = $bytevalue & 0x1F;
2450 $bytesleft = 1;
2451 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2452 $working = $bytevalue & 0x0F;
2453 $bytesleft = 2;
2454 } else { //1111 0xxx
2455 $working = $bytevalue & 0x07;
2456 $bytesleft = 3;
2457 }
2458 }
2459 return $result;
2460 }
2461
2462 /**
2463 * Reverse the previously applied transliteration of non-ASCII characters
2464 * back to UTF-8. Used to protect data from corruption by broken web browsers
2465 * as listed in $wgBrowserBlackList.
2466 *
2467 * @param string $invalue
2468 * @return string
2469 * @private
2470 */
2471 function unmakesafe( $invalue ) {
2472 $result = "";
2473 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2474 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
2475 $i += 3;
2476 $hexstring = "";
2477 do {
2478 $hexstring .= $invalue{$i};
2479 $i++;
2480 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2481
2482 // Do some sanity checks. These aren't needed for reversability,
2483 // but should help keep the breakage down if the editor
2484 // breaks one of the entities whilst editing.
2485 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2486 $codepoint = hexdec($hexstring);
2487 $result .= codepointToUtf8( $codepoint );
2488 } else {
2489 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2490 }
2491 } else {
2492 $result .= substr( $invalue, $i, 1 );
2493 }
2494 }
2495 // reverse the transform that we made for reversability reasons.
2496 return strtr( $result, array( "&#x0" => "&#x" ) );
2497 }
2498
2499 function noCreatePermission() {
2500 global $wgOut;
2501 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2502 $wgOut->addWikiMsg( 'nocreatetext' );
2503 }
2504
2505 /**
2506 * If there are rows in the deletion/move log for this page, show them,
2507 * along with a nice little note for the user
2508 *
2509 * @param OutputPage $out
2510 */
2511 protected function showLogs( $out ) {
2512 global $wgUser;
2513 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
2514 $pager = new LogPager( $loglist, array('move', 'delete'), false,
2515 $this->mTitle->getPrefixedText(), '', array( "log_action != 'revision'" ) );
2516
2517 $count = $pager->getNumRows();
2518 if ( $count > 0 ) {
2519 $pager->mLimit = 10;
2520 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
2521 $out->addWikiMsg( 'recreate-moveddeleted-warn' );
2522 $out->addHTML(
2523 $loglist->beginLogEventsList() .
2524 $pager->getBody() .
2525 $loglist->endLogEventsList()
2526 );
2527 if($count > 10){
2528 $out->addHTML( $wgUser->getSkin()->link(
2529 SpecialPage::getTitleFor( 'Log' ),
2530 wfMsgHtml( 'log-fulllog' ),
2531 array(),
2532 array( 'page' => $this->mTitle->getPrefixedText() ) ) );
2533 }
2534 $out->addHTML( '</div>' );
2535 return true;
2536 }
2537
2538 return false;
2539 }
2540
2541 /**
2542 * Attempt submission
2543 * @return bool false if output is done, true if the rest of the form should be displayed
2544 */
2545 function attemptSave() {
2546 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2547
2548 $resultDetails = false;
2549 # Allow bots to exempt some edits from bot flagging
2550 $bot = $wgUser->isAllowed('bot') && $wgRequest->getBool('bot',true);
2551 $value = $this->internalAttemptSave( $resultDetails, $bot );
2552
2553 if ( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) {
2554 $this->didSave = true;
2555 }
2556
2557 switch ($value) {
2558 case self::AS_HOOK_ERROR_EXPECTED:
2559 case self::AS_CONTENT_TOO_BIG:
2560 case self::AS_ARTICLE_WAS_DELETED:
2561 case self::AS_CONFLICT_DETECTED:
2562 case self::AS_SUMMARY_NEEDED:
2563 case self::AS_TEXTBOX_EMPTY:
2564 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
2565 case self::AS_END:
2566 return true;
2567
2568 case self::AS_HOOK_ERROR:
2569 case self::AS_FILTERING:
2570 case self::AS_SUCCESS_NEW_ARTICLE:
2571 case self::AS_SUCCESS_UPDATE:
2572 return false;
2573
2574 case self::AS_SPAM_ERROR:
2575 $this->spamPage ( $resultDetails['spam'] );
2576 return false;
2577
2578 case self::AS_BLOCKED_PAGE_FOR_USER:
2579 $this->blockedPage();
2580 return false;
2581
2582 case self::AS_IMAGE_REDIRECT_ANON:
2583 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2584 return false;
2585
2586 case self::AS_READ_ONLY_PAGE_ANON:
2587 $this->userNotLoggedInPage();
2588 return false;
2589
2590 case self::AS_READ_ONLY_PAGE_LOGGED:
2591 case self::AS_READ_ONLY_PAGE:
2592 $wgOut->readOnlyPage();
2593 return false;
2594
2595 case self::AS_RATE_LIMITED:
2596 $wgOut->rateLimited();
2597 return false;
2598
2599 case self::AS_NO_CREATE_PERMISSION;
2600 $this->noCreatePermission();
2601 return;
2602
2603 case self::AS_BLANK_ARTICLE:
2604 $wgOut->redirect( $wgTitle->getFullURL() );
2605 return false;
2606
2607 case self::AS_IMAGE_REDIRECT_LOGGED:
2608 $wgOut->permissionRequired( 'upload' );
2609 return false;
2610 }
2611 }
2612
2613 function getBaseRevision() {
2614 if ( $this->mBaseRevision == false ) {
2615 $db = wfGetDB( DB_MASTER );
2616 $baseRevision = Revision::loadFromTimestamp(
2617 $db, $this->mTitle, $this->edittime );
2618 return $this->mBaseRevision = $baseRevision;
2619 } else {
2620 return $this->mBaseRevision;
2621 }
2622 }
2623 }