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