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