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