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