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