Follow-up on r56251 - merging showLogs and showLogExtract
[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' ),
734 $this->mTitle->getPrefixedText(), '', 10, array( "log_action != 'revision'" ), false, 'recreate-moveddeleted-warn');
735 }
736 }
737
738 /**
739 * Attempt to show a custom editing introduction, if supplied
740 *
741 * @return bool
742 */
743 protected function showCustomIntro() {
744 if ( $this->editintro ) {
745 $title = Title::newFromText( $this->editintro );
746 if ( $title instanceof Title && $title->exists() && $title->userCanRead() ) {
747 global $wgOut;
748 $revision = Revision::newFromTitle( $title );
749 $wgOut->addWikiTextTitleTidy( $revision->getText(), $this->mTitle );
750 return true;
751 } else {
752 return false;
753 }
754 } else {
755 return false;
756 }
757 }
758
759 /**
760 * Attempt submission (no UI)
761 * @return one of the constants describing the result
762 */
763 function internalAttemptSave( &$result, $bot = false ) {
764 global $wgFilterCallback, $wgUser, $wgOut, $wgParser;
765 global $wgMaxArticleSize;
766
767 $fname = 'EditPage::attemptSave';
768 wfProfileIn( $fname );
769 wfProfileIn( "$fname-checks" );
770
771 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) )
772 {
773 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
774 return self::AS_HOOK_ERROR;
775 }
776
777 # Check image redirect
778 if ( $this->mTitle->getNamespace() == NS_FILE &&
779 Title::newFromRedirect( $this->textbox1 ) instanceof Title &&
780 !$wgUser->isAllowed( 'upload' ) ) {
781 if ( $wgUser->isAnon() ) {
782 return self::AS_IMAGE_REDIRECT_ANON;
783 } else {
784 return self::AS_IMAGE_REDIRECT_LOGGED;
785 }
786 }
787
788 # Reintegrate metadata
789 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
790 $this->mMetaData = '' ;
791
792 # Check for spam
793 $match = self::matchSummarySpamRegex( $this->summary );
794 if ( $match === false ) {
795 $match = self::matchSpamRegex( $this->textbox1 );
796 }
797 if ( $match !== false ) {
798 $result['spam'] = $match;
799 $ip = wfGetIP();
800 $pdbk = $this->mTitle->getPrefixedDBkey();
801 $match = str_replace( "\n", '', $match );
802 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
803 wfProfileOut( "$fname-checks" );
804 wfProfileOut( $fname );
805 return self::AS_SPAM_ERROR;
806 }
807 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section, $this->hookError, $this->summary ) ) {
808 # Error messages or other handling should be performed by the filter function
809 wfProfileOut( "$fname-checks" );
810 wfProfileOut( $fname );
811 return self::AS_FILTERING;
812 }
813 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) ) ) {
814 # Error messages etc. could be handled within the hook...
815 wfProfileOut( "$fname-checks" );
816 wfProfileOut( $fname );
817 return self::AS_HOOK_ERROR;
818 } elseif ( $this->hookError != '' ) {
819 # ...or the hook could be expecting us to produce an error
820 wfProfileOut( "$fname-checks" );
821 wfProfileOut( $fname );
822 return self::AS_HOOK_ERROR_EXPECTED;
823 }
824 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
825 # Check block state against master, thus 'false'.
826 wfProfileOut( "$fname-checks" );
827 wfProfileOut( $fname );
828 return self::AS_BLOCKED_PAGE_FOR_USER;
829 }
830 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
831 if ( $this->kblength > $wgMaxArticleSize ) {
832 // Error will be displayed by showEditForm()
833 $this->tooBig = true;
834 wfProfileOut( "$fname-checks" );
835 wfProfileOut( $fname );
836 return self::AS_CONTENT_TOO_BIG;
837 }
838
839 if ( !$wgUser->isAllowed('edit') ) {
840 if ( $wgUser->isAnon() ) {
841 wfProfileOut( "$fname-checks" );
842 wfProfileOut( $fname );
843 return self::AS_READ_ONLY_PAGE_ANON;
844 }
845 else {
846 wfProfileOut( "$fname-checks" );
847 wfProfileOut( $fname );
848 return self::AS_READ_ONLY_PAGE_LOGGED;
849 }
850 }
851
852 if ( wfReadOnly() ) {
853 wfProfileOut( "$fname-checks" );
854 wfProfileOut( $fname );
855 return self::AS_READ_ONLY_PAGE;
856 }
857 if ( $wgUser->pingLimiter() ) {
858 wfProfileOut( "$fname-checks" );
859 wfProfileOut( $fname );
860 return self::AS_RATE_LIMITED;
861 }
862
863 # If the article has been deleted while editing, don't save it without
864 # confirmation
865 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
866 wfProfileOut( "$fname-checks" );
867 wfProfileOut( $fname );
868 return self::AS_ARTICLE_WAS_DELETED;
869 }
870
871 wfProfileOut( "$fname-checks" );
872
873 # If article is new, insert it.
874 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
875 if ( 0 == $aid ) {
876 // Late check for create permission, just in case *PARANOIA*
877 if ( !$this->mTitle->userCan( 'create' ) ) {
878 wfDebug( "$fname: no create permission\n" );
879 wfProfileOut( $fname );
880 return self::AS_NO_CREATE_PERMISSION;
881 }
882
883 # Don't save a new article if it's blank.
884 if ( '' == $this->textbox1 ) {
885 wfProfileOut( $fname );
886 return self::AS_BLANK_ARTICLE;
887 }
888
889 // Run post-section-merge edit filter
890 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1, &$this->hookError, $this->summary ) ) ) {
891 # Error messages etc. could be handled within the hook...
892 wfProfileOut( $fname );
893 return self::AS_HOOK_ERROR;
894 } elseif ( $this->hookError != '' ) {
895 # ...or the hook could be expecting us to produce an error
896 wfProfileOut( $fname );
897 return self::AS_HOOK_ERROR_EXPECTED;
898 }
899
900 # Handle the user preference to force summaries here. Check if it's not a redirect.
901 if ( !$this->allowBlankSummary && !Title::newFromRedirect( $this->textbox1 ) ) {
902 if ( md5( $this->summary ) == $this->autoSumm ) {
903 $this->missingSummary = true;
904 wfProfileOut( $fname );
905 return self::AS_SUMMARY_NEEDED;
906 }
907 }
908
909 $isComment = ( $this->section == 'new' );
910
911 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
912 $this->minoredit, $this->watchthis, false, $isComment, $bot );
913
914 wfProfileOut( $fname );
915 return self::AS_SUCCESS_NEW_ARTICLE;
916 }
917
918 # Article exists. Check for edit conflict.
919
920 $this->mArticle->clear(); # Force reload of dates, etc.
921 $this->mArticle->forUpdate( true ); # Lock the article
922
923 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
924
925 if ( $this->mArticle->getTimestamp() != $this->edittime ) {
926 $this->isConflict = true;
927 if ( $this->section == 'new' ) {
928 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
929 $this->mArticle->getComment() == $this->summary ) {
930 // Probably a duplicate submission of a new comment.
931 // This can happen when squid resends a request after
932 // a timeout but the first one actually went through.
933 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
934 } else {
935 // New comment; suppress conflict.
936 $this->isConflict = false;
937 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
938 }
939 }
940 }
941 $userid = $wgUser->getId();
942
943 # Suppress edit conflict with self, except for section edits where merging is required.
944 if ( $this->isConflict && $this->section == '' && $this->userWasLastToEdit($userid,$this->edittime) ) {
945 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
946 $this->isConflict = false;
947 }
948
949 if ( $this->isConflict ) {
950 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
951 $this->mArticle->getTimestamp() . "')\n" );
952 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime );
953 } else {
954 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
955 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary );
956 }
957 if ( is_null( $text ) ) {
958 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
959 $this->isConflict = true;
960 $text = $this->textbox1; // do not try to merge here!
961 } else if ( $this->isConflict ) {
962 # Attempt merge
963 if ( $this->mergeChangesInto( $text ) ) {
964 // Successful merge! Maybe we should tell the user the good news?
965 $this->isConflict = false;
966 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
967 } else {
968 $this->section = '';
969 $this->textbox1 = $text;
970 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
971 }
972 }
973
974 if ( $this->isConflict ) {
975 wfProfileOut( $fname );
976 return self::AS_CONFLICT_DETECTED;
977 }
978
979 $oldtext = $this->mArticle->getContent();
980
981 // Run post-section-merge edit filter
982 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError, $this->summary ) ) ) {
983 # Error messages etc. could be handled within the hook...
984 wfProfileOut( $fname );
985 return self::AS_HOOK_ERROR;
986 } elseif ( $this->hookError != '' ) {
987 # ...or the hook could be expecting us to produce an error
988 wfProfileOut( $fname );
989 return self::AS_HOOK_ERROR_EXPECTED;
990 }
991
992 # Handle the user preference to force summaries here, but not for null edits
993 if ( $this->section != 'new' && !$this->allowBlankSummary && 0 != strcmp($oldtext,$text)
994 && !Title::newFromRedirect( $text ) ) # check if it's not a redirect
995 {
996 if ( md5( $this->summary ) == $this->autoSumm ) {
997 $this->missingSummary = true;
998 wfProfileOut( $fname );
999 return self::AS_SUMMARY_NEEDED;
1000 }
1001 }
1002
1003 # And a similar thing for new sections
1004 if ( $this->section == 'new' && !$this->allowBlankSummary ) {
1005 if (trim($this->summary) == '') {
1006 $this->missingSummary = true;
1007 wfProfileOut( $fname );
1008 return self::AS_SUMMARY_NEEDED;
1009 }
1010 }
1011
1012 # All's well
1013 wfProfileIn( "$fname-sectionanchor" );
1014 $sectionanchor = '';
1015 if ( $this->section == 'new' ) {
1016 if ( $this->textbox1 == '' ) {
1017 $this->missingComment = true;
1018 return self::AS_TEXTBOX_EMPTY;
1019 }
1020 if ( $this->summary != '' ) {
1021 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary );
1022 # This is a new section, so create a link to the new section
1023 # in the revision summary.
1024 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1025 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
1026 }
1027 } elseif ( $this->section != '' ) {
1028 # Try to get a section anchor from the section source, redirect to edited section if header found
1029 # XXX: might be better to integrate this into Article::replaceSection
1030 # for duplicate heading checking and maybe parsing
1031 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1032 # we can't deal with anchors, includes, html etc in the header for now,
1033 # headline would need to be parsed to improve this
1034 if ( $hasmatch and strlen($matches[2]) > 0 ) {
1035 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
1036 }
1037 }
1038 wfProfileOut( "$fname-sectionanchor" );
1039
1040 // Save errors may fall down to the edit form, but we've now
1041 // merged the section into full text. Clear the section field
1042 // so that later submission of conflict forms won't try to
1043 // replace that into a duplicated mess.
1044 $this->textbox1 = $text;
1045 $this->section = '';
1046
1047 // Check for length errors again now that the section is merged in
1048 $this->kblength = (int)(strlen( $text ) / 1024);
1049 if ( $this->kblength > $wgMaxArticleSize ) {
1050 $this->tooBig = true;
1051 wfProfileOut( $fname );
1052 return self::AS_MAX_ARTICLE_SIZE_EXCEEDED;
1053 }
1054
1055 # update the article here
1056 if ( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
1057 $this->watchthis, $bot, $sectionanchor ) )
1058 {
1059 wfProfileOut( $fname );
1060 return self::AS_SUCCESS_UPDATE;
1061 } else {
1062 $this->isConflict = true;
1063 }
1064 wfProfileOut( $fname );
1065 return self::AS_END;
1066 }
1067
1068 /**
1069 * Check if no edits were made by other users since
1070 * the time a user started editing the page. Limit to
1071 * 50 revisions for the sake of performance.
1072 */
1073 protected function userWasLastToEdit( $id, $edittime ) {
1074 if( !$id ) return false;
1075 $dbw = wfGetDB( DB_MASTER );
1076 $res = $dbw->select( 'revision',
1077 'rev_user',
1078 array(
1079 'rev_page' => $this->mArticle->getId(),
1080 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1081 ),
1082 __METHOD__,
1083 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1084 while( $row = $res->fetchObject() ) {
1085 if( $row->rev_user != $id ) {
1086 return false;
1087 }
1088 }
1089 return true;
1090 }
1091
1092 /**
1093 * Check given input text against $wgSpamRegex, and return the text of the first match.
1094 * @return mixed -- matching string or false
1095 */
1096 public static function matchSpamRegex( $text ) {
1097 global $wgSpamRegex;
1098 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1099 $regexes = (array)$wgSpamRegex;
1100 return self::matchSpamRegexInternal( $text, $regexes );
1101 }
1102
1103 /**
1104 * Check given input text against $wgSpamRegex, and return the text of the first match.
1105 * @return mixed -- matching string or false
1106 */
1107 public static function matchSummarySpamRegex( $text ) {
1108 global $wgSummarySpamRegex;
1109 $regexes = (array)$wgSummarySpamRegex;
1110 return self::matchSpamRegexInternal( $text, $regexes );
1111 }
1112
1113 protected static function matchSpamRegexInternal( $text, $regexes ) {
1114 foreach( $regexes as $regex ) {
1115 $matches = array();
1116 if( preg_match( $regex, $text, $matches ) ) {
1117 return $matches[0];
1118 }
1119 }
1120 return false;
1121 }
1122
1123 /**
1124 * Initialise form fields in the object
1125 * Called on the first invocation, e.g. when a user clicks an edit link
1126 */
1127 function initialiseForm() {
1128 $this->edittime = $this->mArticle->getTimestamp();
1129 $this->textbox1 = $this->getContent( false );
1130 if ( $this->textbox1 === false ) return false;
1131 wfProxyCheck();
1132 return true;
1133 }
1134
1135 function setHeaders() {
1136 global $wgOut, $wgTitle;
1137 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1138 if ( $this->formtype == 'preview' ) {
1139 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1140 }
1141 if ( $this->isConflict ) {
1142 $wgOut->setPageTitle( wfMsg( 'editconflict', $wgTitle->getPrefixedText() ) );
1143 } elseif ( $this->section != '' ) {
1144 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
1145 $wgOut->setPageTitle( wfMsg( $msg, $wgTitle->getPrefixedText() ) );
1146 } else {
1147 # Use the title defined by DISPLAYTITLE magic word when present
1148 if ( isset($this->mParserOutput)
1149 && ( $dt = $this->mParserOutput->getDisplayTitle() ) !== false ) {
1150 $title = $dt;
1151 } else {
1152 $title = $wgTitle->getPrefixedText();
1153 }
1154 $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
1155 }
1156 }
1157
1158 /**
1159 * Send the edit form and related headers to $wgOut
1160 * @param $formCallback Optional callable that takes an OutputPage
1161 * parameter; will be called during form output
1162 * near the top, for captchas and the like.
1163 */
1164 function showEditForm( $formCallback=null ) {
1165 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle, $wgRequest;
1166
1167 # If $wgTitle is null, that means we're in API mode.
1168 # Some hook probably called this function without checking
1169 # for is_null($wgTitle) first. Bail out right here so we don't
1170 # do lots of work just to discard it right after.
1171 if (is_null($wgTitle))
1172 return;
1173
1174 $fname = 'EditPage::showEditForm';
1175 wfProfileIn( $fname );
1176
1177 $sk = $wgUser->getSkin();
1178
1179 #need to parse the preview early so that we know which templates are used,
1180 #otherwise users with "show preview after edit box" will get a blank list
1181 #we parse this near the beginning so that setHeaders can do the title
1182 #setting work instead of leaving it in getPreviewText
1183 $previewOutput = '';
1184 if ( $this->formtype == 'preview' ) {
1185 $previewOutput = $this->getPreviewText();
1186 }
1187
1188 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
1189
1190 $this->setHeaders();
1191
1192 # Enabled article-related sidebar, toplinks, etc.
1193 $wgOut->setArticleRelated( true );
1194
1195 if ( $this->isConflict ) {
1196 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1</div>", 'explainconflict' );
1197
1198 $this->textbox2 = $this->textbox1;
1199 $this->textbox1 = $this->getContent();
1200 $this->edittime = $this->mArticle->getTimestamp();
1201 } else {
1202 if ( $this->section != '' && $this->section != 'new' ) {
1203 $matches = array();
1204 if ( !$this->summary && !$this->preview && !$this->diff ) {
1205 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1, $matches );
1206 if ( !empty( $matches[2] ) ) {
1207 global $wgParser;
1208 $this->summary = "/* " .
1209 $wgParser->stripSectionName(trim($matches[2])) .
1210 " */ ";
1211 }
1212 }
1213 }
1214
1215 if ( $this->missingComment ) {
1216 $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' );
1217 }
1218
1219 if ( $this->missingSummary && $this->section != 'new' ) {
1220 $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' );
1221 }
1222
1223 if ( $this->missingSummary && $this->section == 'new' ) {
1224 $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' );
1225 }
1226
1227 if ( $this->hookError !== '' ) {
1228 $wgOut->addWikiText( $this->hookError );
1229 }
1230
1231 if ( !$this->checkUnicodeCompliantBrowser() ) {
1232 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1233 }
1234 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
1235 // Let sysop know that this will make private content public if saved
1236
1237 if ( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1238 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
1239 } else if ( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1240 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
1241 }
1242
1243 if ( !$this->mArticle->mRevision->isCurrent() ) {
1244 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
1245 $wgOut->addWikiMsg( 'editingold' );
1246 }
1247 }
1248 }
1249
1250 if ( wfReadOnly() ) {
1251 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1252 } elseif ( $wgUser->isAnon() && $this->formtype != 'preview' ) {
1253 $wgOut->wrapWikiMsg( '<div id="mw-anon-edit-warning">$1</div>', 'anoneditwarning' );
1254 } else {
1255 if ( $this->isCssJsSubpage ) {
1256 # Check the skin exists
1257 if ( !$this->isValidCssJsSubpage ) {
1258 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1259 }
1260 if ( $this->formtype !== 'preview' ) {
1261 if ( $this->isCssSubpage )
1262 $wgOut->addWikiMsg( 'usercssyoucanpreview' );
1263 if ( $this->isJsSubpage )
1264 $wgOut->addWikiMsg( 'userjsyoucanpreview' );
1265 }
1266 }
1267 }
1268
1269 $classes = array(); // Textarea CSS
1270 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1271 } elseif ( $this->mTitle->isProtected( 'edit' ) ) {
1272 # Is the title semi-protected?
1273 if ( $this->mTitle->isSemiProtected() ) {
1274 $noticeMsg = 'semiprotectedpagewarning';
1275 $classes[] = 'mw-textarea-sprotected';
1276 } else {
1277 # Then it must be protected based on static groups (regular)
1278 $noticeMsg = 'protectedpagewarning';
1279 $classes[] = 'mw-textarea-protected';
1280 }
1281 $wgOut->addHTML( "<div class='mw-warning-with-logexcerpt'>\n" );
1282 $wgOut->addWikiMsg( $noticeMsg );
1283 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle->getPrefixedText(), '', 1 );
1284 $wgOut->addHTML( "</div>\n" );
1285 }
1286 if ( $this->mTitle->isCascadeProtected() ) {
1287 # Is this page under cascading protection from some source pages?
1288 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1289 $notice = "<div class='mw-cascadeprotectedwarning'>$1\n";
1290 $cascadeSourcesCount = count( $cascadeSources );
1291 if ( $cascadeSourcesCount > 0 ) {
1292 # Explain, and list the titles responsible
1293 foreach( $cascadeSources as $page ) {
1294 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1295 }
1296 }
1297 $notice .= '</div>';
1298 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1299 }
1300 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
1301 $wgOut->wrapWikiMsg( '<div class="mw-titleprotectedwarning">$1</div>', 'titleprotectedwarning' );
1302 }
1303
1304 if ( $this->kblength === false ) {
1305 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
1306 }
1307 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1308 $wgOut->addHTML( "<div class='error' id='mw-edit-longpageerror'>\n" );
1309 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) );
1310 $wgOut->addHTML( "</div>\n" );
1311 } elseif ( $this->kblength > 29 ) {
1312 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1313 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) );
1314 $wgOut->addHTML( "</div>\n" );
1315 }
1316
1317 $action = $wgTitle->escapeLocalURL( array( 'action' => $this->action ) );
1318
1319 $summary = wfMsgExt( 'summary', 'parseinline' );
1320 $subject = wfMsgExt( 'subject', 'parseinline' );
1321
1322 $cancel = $sk->link(
1323 $wgTitle,
1324 wfMsgExt( 'cancel', array( 'parseinline' ) ),
1325 array( 'id' => 'mw-editform-cancel' ),
1326 array(),
1327 array( 'known', 'noclasses' )
1328 );
1329 $separator = wfMsgExt( 'pipe-separator' , 'escapenoentities' );
1330 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1331 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1332 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1333 htmlspecialchars( wfMsg( 'newwindow' ) );
1334
1335 global $wgRightsText;
1336 if ( $wgRightsText ) {
1337 $copywarnMsg = array( 'copyrightwarning',
1338 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1339 $wgRightsText );
1340 } else {
1341 $copywarnMsg = array( 'copyrightwarning2',
1342 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1343 }
1344 // Allow for site and per-namespace customization of contribution/copyright notice.
1345 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle, &$copywarnMsg ) );
1346
1347 if ( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
1348 # prepare toolbar for edit buttons
1349 $toolbar = EditPage::getEditToolbar();
1350 } else {
1351 $toolbar = '';
1352 }
1353
1354
1355 // activate checkboxes if user wants them to be always active
1356 if ( !$this->preview && !$this->diff ) {
1357 # Sort out the "watch" checkbox
1358 if ( $wgUser->getOption( 'watchdefault' ) ) {
1359 # Watch all edits
1360 $this->watchthis = true;
1361 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1362 # Watch creations
1363 $this->watchthis = true;
1364 } elseif ( $this->mTitle->userIsWatching() ) {
1365 # Already watched
1366 $this->watchthis = true;
1367 }
1368
1369 # May be overriden by request parameters
1370 if( $wgRequest->getBool( 'watchthis' ) ) {
1371 $this->watchthis = true;
1372 }
1373
1374 if ( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1375 }
1376
1377 $wgOut->addHTML( $this->editFormPageTop );
1378
1379 if ( $wgUser->getOption( 'previewontop' ) ) {
1380 $this->displayPreviewArea( $previewOutput, true );
1381 }
1382
1383
1384 $wgOut->addHTML( $this->editFormTextTop );
1385
1386 # if this is a comment, show a subject line at the top, which is also the edit summary.
1387 # Otherwise, show a summary field at the bottom
1388 $summarytext = $wgContLang->recodeForEdit( $this->summary );
1389
1390 # If a blank edit summary was previously provided, and the appropriate
1391 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1392 # user being bounced back more than once in the event that a summary
1393 # is not required.
1394 #####
1395 # For a bit more sophisticated detection of blank summaries, hash the
1396 # automatic one and pass that in the hidden field wpAutoSummary.
1397 $summaryhiddens = '';
1398 if ( $this->missingSummary ) $summaryhiddens .= Xml::hidden( 'wpIgnoreBlankSummary', true );
1399 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1400 $summaryhiddens .= Xml::hidden( 'wpAutoSummary', $autosumm );
1401 if ( $this->section == 'new' ) {
1402 $commentsubject = '';
1403 if ( !$wgRequest->getBool( 'nosummary' ) ) {
1404 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1405 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
1406
1407 $commentsubject =
1408 Xml::tags( 'label', array( 'for' => 'wpSummary' ), $subject );
1409 $commentsubject =
1410 Xml::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1411 $commentsubject );
1412 $commentsubject .= '&nbsp;';
1413 $commentsubject .= Xml::input( 'wpSummary',
1414 60,
1415 $summarytext,
1416 array(
1417 'id' => 'wpSummary',
1418 'maxlength' => '200',
1419 'tabindex' => '1'
1420 ) );
1421 } else {
1422 $summaryhiddens .= Xml::hidden( 'wpIgnoreBlankSummary', true ); # bug 18699
1423 }
1424 $editsummary = "<div class='editOptions'>\n";
1425 global $wgParser;
1426 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary ) );
1427 $subjectpreview = $summarytext && ( $this->preview || $this->diff ) ?
1428 "<div class=\"mw-summary-preview\">". wfMsgExt('subject-preview', 'parseinline') . $sk->commentBlock( $formattedSummary, $this->mTitle, true )."</div>\n" : '';
1429 $summarypreview = '';
1430 } else {
1431 $commentsubject = '';
1432
1433 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1434 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
1435
1436 $editsummary = Xml::tags( 'label', array( 'for' => 'wpSummary' ), $summary );
1437 $editsummary = Xml::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1438 $editsummary ) . ' ';
1439
1440 $editsummary .= Xml::input( 'wpSummary',
1441 60,
1442 $summarytext,
1443 array(
1444 'id' => 'wpSummary',
1445 'maxlength' => '200',
1446 'tabindex' => '1'
1447 ) );
1448
1449 // No idea where this is closed.
1450 $editsummary = Xml::openElement( 'div', array( 'class' => 'editOptions' ) )
1451 . $editsummary . '<br/>';
1452
1453 $summarypreview = '';
1454 if ( $summarytext && ( $this->preview || $this->diff ) ) {
1455 $summarypreview =
1456 Xml::tags( 'div',
1457 array( 'class' => 'mw-summary-preview' ),
1458 wfMsgExt( 'summary-preview', 'parseinline' ) .
1459 $sk->commentBlock( $this->summary, $this->mTitle )
1460 );
1461 }
1462 $subjectpreview = '';
1463 }
1464 $commentsubject .= $summaryhiddens;
1465
1466 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1467 if ( !$this->preview && !$this->diff ) {
1468 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1469 }
1470 $templates = $this->getTemplates();
1471 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1472
1473 $hiddencats = $this->mArticle->getHiddenCategories();
1474 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1475
1476 global $wgUseMetadataEdit ;
1477 if ( $wgUseMetadataEdit ) {
1478 $metadata = $this->mMetaData ;
1479 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1480 $top = wfMsgWikiHtml( 'metadata_help' );
1481 /* ToDo: Replace with clean code */
1482 $ew = $wgUser->getOption( 'editwidth' );
1483 if ( $ew ) $ew = " style=\"width:100%\"";
1484 else $ew = '';
1485 $cols = $wgUser->getIntOption( 'cols' );
1486 /* /ToDo */
1487 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1488 }
1489 else $metadata = "" ;
1490
1491 $recreate = '';
1492 if ( $this->wasDeletedSinceLastEdit() ) {
1493 if ( 'save' != $this->formtype ) {
1494 $wgOut->wrapWikiMsg(
1495 "<div class='error mw-deleted-while-editing'>\n$1</div>",
1496 'deletedwhileediting' );
1497 } else {
1498 // Hide the toolbar and edit area, user can click preview to get it back
1499 // Add an confirmation checkbox and explanation.
1500 $toolbar = '';
1501 $recreate = '<div class="mw-confirm-recreate">' .
1502 $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ) ) .
1503 Xml::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1504 array( 'title' => $sk->titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1505 ) . '</div>';
1506 }
1507 }
1508
1509 $tabindex = 2;
1510
1511 $checkboxes = $this->getCheckboxes( $tabindex, $sk,
1512 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1513
1514 $checkboxhtml = implode( $checkboxes, "\n" );
1515
1516 $buttons = $this->getEditButtons( $tabindex );
1517 $buttonshtml = implode( $buttons, "\n" );
1518
1519 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1520 ? '' : Xml::hidden( 'safemode', '1' );
1521
1522 $wgOut->addHTML( <<<END
1523 {$toolbar}
1524 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1525 END
1526 );
1527
1528 if ( is_callable( $formCallback ) ) {
1529 call_user_func_array( $formCallback, array( &$wgOut ) );
1530 }
1531
1532 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1533
1534 // Put these up at the top to ensure they aren't lost on early form submission
1535 $this->showFormBeforeText();
1536
1537 $wgOut->addHTML( <<<END
1538 {$recreate}
1539 {$commentsubject}
1540 {$subjectpreview}
1541 {$this->editFormTextBeforeContent}
1542 END
1543 );
1544 $this->showTextbox1( $classes );
1545
1546 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1547 $wgOut->addHTML( <<<END
1548 {$this->editFormTextAfterWarn}
1549 {$metadata}
1550 {$editsummary}
1551 {$summarypreview}
1552 {$checkboxhtml}
1553 {$safemodehtml}
1554 END
1555 );
1556
1557 $wgOut->addHTML(
1558 "<div class='editButtons'>
1559 {$buttonshtml}
1560 <span class='editHelp'>{$cancel}{$separator}{$edithelp}</span>
1561 </div><!-- editButtons -->
1562 </div><!-- editOptions -->");
1563
1564 /**
1565 * To make it harder for someone to slip a user a page
1566 * which submits an edit form to the wiki without their
1567 * knowledge, a random token is associated with the login
1568 * session. If it's not passed back with the submission,
1569 * we won't save the page, or render user JavaScript and
1570 * CSS previews.
1571 *
1572 * For anon editors, who may not have a session, we just
1573 * include the constant suffix to prevent editing from
1574 * broken text-mangling proxies.
1575 */
1576 $token = htmlspecialchars( $wgUser->editToken() );
1577 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1578
1579 $this->showTosSummary();
1580 $this->showEditTools();
1581
1582 $wgOut->addHTML( <<<END
1583 {$this->editFormTextAfterTools}
1584 <div class='templatesUsed'>
1585 {$formattedtemplates}
1586 </div>
1587 <div class='hiddencats'>
1588 {$formattedhiddencats}
1589 </div>
1590 END
1591 );
1592
1593 if (!$this->preview) {
1594 $wgOut->addHTML( Xml::tags( 'div',
1595 array( 'class' => 'catlinks catlinks-allhidden',
1596 'id' => 'catlinks' ), ' ' ) );
1597 }
1598
1599 if ( $this->isConflict && wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1600 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1601
1602 $de = new DifferenceEngine( $this->mTitle );
1603 $de->setText( $this->textbox2, $this->textbox1 );
1604 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1605
1606 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1607 $this->showTextbox2();
1608 }
1609 $wgOut->addHTML( $this->editFormTextBottom );
1610 $wgOut->addHTML( "</form>\n" );
1611 if ( !$wgUser->getOption( 'previewontop' ) ) {
1612 $this->displayPreviewArea( $previewOutput, false );
1613 }
1614
1615 wfProfileOut( $fname );
1616 }
1617
1618 protected function showFormBeforeText() {
1619 global $wgOut;
1620 $wgOut->addHTML( "
1621 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1622 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1623 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1624 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1625 }
1626
1627 protected function showTextbox1( $classes ) {
1628 $attribs = array( 'tabindex' => 1 );
1629
1630 if ( $this->wasDeletedSinceLastEdit() )
1631 $attribs['type'] = 'hidden';
1632 if ( !empty($classes) )
1633 $attribs['class'] = implode(' ',$classes);
1634
1635 $this->showTextbox( $this->textbox1, 'wpTextbox1', $attribs );
1636 }
1637
1638 protected function showTextbox2() {
1639 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6 ) );
1640 }
1641
1642 protected function showTextbox( $content, $name, $attribs = array() ) {
1643 global $wgOut, $wgUser;
1644
1645 $wikitext = $this->safeUnicodeOutput( $content );
1646 if ( $wikitext !== '' ) {
1647 // Ensure there's a newline at the end, otherwise adding lines
1648 // is awkward.
1649 // But don't add a newline if the ext is empty, or Firefox in XHTML
1650 // mode will show an extra newline. A bit annoying.
1651 $wikitext .= "\n";
1652 }
1653
1654 $attribs['accesskey'] = ',';
1655 $attribs['id'] = $name;
1656
1657 if ( $wgUser->getOption( 'editwidth' ) )
1658 $attribs['style'] = 'width: 100%';
1659
1660 $wgOut->addHTML( Xml::textarea(
1661 $name,
1662 $wikitext,
1663 $wgUser->getIntOption( 'cols' ), $wgUser->getIntOption( 'rows' ),
1664 $attribs ) );
1665 }
1666
1667 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1668 global $wgOut;
1669 $classes = array();
1670 if ( $isOnTop )
1671 $classes[] = 'ontop';
1672
1673 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1674
1675 if ( $this->formtype != 'preview' )
1676 $attribs['style'] = 'display: none;';
1677
1678 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
1679
1680 if ( $this->formtype == 'preview' ) {
1681 $this->showPreview( $previewOutput );
1682 }
1683
1684 $wgOut->addHTML( '</div>' );
1685
1686 if ( $this->formtype == 'diff') {
1687 $this->showDiff();
1688 }
1689 }
1690
1691 /**
1692 * Append preview output to $wgOut.
1693 * Includes category rendering if this is a category page.
1694 *
1695 * @param string $text The HTML to be output for the preview.
1696 */
1697 protected function showPreview( $text ) {
1698 global $wgOut;
1699 if ( $this->mTitle->getNamespace() == NS_CATEGORY) {
1700 $this->mArticle->openShowCategory();
1701 }
1702 # This hook seems slightly odd here, but makes things more
1703 # consistent for extensions.
1704 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1705 $wgOut->addHTML( $text );
1706 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1707 $this->mArticle->closeShowCategory();
1708 }
1709 }
1710
1711 /**
1712 * Live Preview lets us fetch rendered preview page content and
1713 * add it to the page without refreshing the whole page.
1714 * If not supported by the browser it will fall through to the normal form
1715 * submission method.
1716 *
1717 * This function outputs a script tag to support live preview, and
1718 * returns an onclick handler which should be added to the attributes
1719 * of the preview button
1720 */
1721 function doLivePreviewScript() {
1722 global $wgOut, $wgTitle;
1723 $wgOut->addScriptFile( 'preview.js' );
1724 return "";
1725 }
1726
1727 protected function showTosSummary() {
1728 $msg = 'editpage-tos-summary';
1729 // Give a chance for site and per-namespace customizations of
1730 // terms of service summary link that might exist separately
1731 // from the copyright notice.
1732 //
1733 // This will display between the save button and the edit tools,
1734 // so should remain short!
1735 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
1736 $text = wfMsg( $msg );
1737 if( !wfEmptyMsg( $msg, $text ) && $text !== '-' ) {
1738 global $wgOut;
1739 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1740 $wgOut->addWikiMsgArray( $msg, array() );
1741 $wgOut->addHTML( '</div>' );
1742 }
1743 }
1744
1745 protected function showEditTools() {
1746 global $wgOut;
1747 $wgOut->addHTML( '<div class="mw-editTools">' );
1748 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1749 $wgOut->addHTML( '</div>' );
1750 }
1751
1752 protected function getLastDelete() {
1753 $dbr = wfGetDB( DB_SLAVE );
1754 $data = $dbr->selectRow(
1755 array( 'logging', 'user' ),
1756 array( 'log_type',
1757 'log_action',
1758 'log_timestamp',
1759 'log_user',
1760 'log_namespace',
1761 'log_title',
1762 'log_comment',
1763 'log_params',
1764 'log_deleted',
1765 'user_name' ),
1766 array( 'log_namespace' => $this->mTitle->getNamespace(),
1767 'log_title' => $this->mTitle->getDBkey(),
1768 'log_type' => 'delete',
1769 'log_action' => 'delete',
1770 'user_id=log_user' ),
1771 __METHOD__,
1772 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1773 );
1774 // Quick paranoid permission checks...
1775 if( is_object($data) ) {
1776 if( $data->log_deleted & LogPage::DELETED_USER )
1777 $data->user_name = wfMsgHtml('rev-deleted-user');
1778 if( $data->log_deleted & LogPage::DELETED_COMMENT )
1779 $data->log_comment = wfMsgHtml('rev-deleted-comment');
1780 }
1781 return $data;
1782 }
1783
1784 /**
1785 * Get the rendered text for previewing.
1786 * @return string
1787 */
1788 function getPreviewText() {
1789 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang, $wgMessageCache;
1790
1791 wfProfileIn( __METHOD__ );
1792
1793 if ( $this->mTriedSave && !$this->mTokenOk ) {
1794 if ( $this->mTokenOkExceptSuffix ) {
1795 $note = wfMsg( 'token_suffix_mismatch' );
1796 } else {
1797 $note = wfMsg( 'session_fail_preview' );
1798 }
1799 } else {
1800 $note = wfMsg( 'previewnote' );
1801 }
1802
1803 $parserOptions = ParserOptions::newFromUser( $wgUser );
1804 $parserOptions->setEditSection( false );
1805 $parserOptions->setIsPreview( true );
1806 $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' );
1807
1808 global $wgRawHtml;
1809 if ( $wgRawHtml && !$this->mTokenOk ) {
1810 // Could be an offsite preview attempt. This is very unsafe if
1811 // HTML is enabled, as it could be an attack.
1812 return $wgOut->parse( "<div class='previewnote'>" .
1813 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1814 }
1815
1816 # don't parse user css/js, show message about preview
1817 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1818
1819 if ( $this->isCssJsSubpage ) {
1820 if (preg_match("/\\.css$/", $this->mTitle->getText() ) ) {
1821 $previewtext = wfMsg('usercsspreview');
1822 } else if (preg_match("/\\.js$/", $this->mTitle->getText() ) ) {
1823 $previewtext = wfMsg('userjspreview');
1824 }
1825 $parserOptions->setTidy(true);
1826 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
1827 $previewHTML = $parserOutput->mText;
1828 } elseif ( $rt = Title::newFromRedirectArray( $this->textbox1 ) ) {
1829 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
1830 } else {
1831 $toparse = $this->textbox1;
1832
1833 # If we're adding a comment, we need to show the
1834 # summary as the headline
1835 if ( $this->section=="new" && $this->summary!="" ) {
1836 $toparse="== {$this->summary} ==\n\n".$toparse;
1837 }
1838
1839 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData;
1840
1841 // Parse mediawiki messages with correct target language
1842 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1843 list( /* $unused */, $lang ) = $wgMessageCache->figureMessage( $this->mTitle->getText() );
1844 $obj = wfGetLangObj( $lang );
1845 $parserOptions->setTargetLanguage( $obj );
1846 }
1847
1848
1849 $parserOptions->setTidy(true);
1850 $parserOptions->enableLimitReport();
1851 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ),
1852 $this->mTitle, $parserOptions );
1853
1854 $previewHTML = $parserOutput->getText();
1855 $this->mParserOutput = $parserOutput;
1856 $wgOut->addParserOutputNoText( $parserOutput );
1857
1858 if ( count( $parserOutput->getWarnings() ) ) {
1859 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1860 }
1861 }
1862
1863 if( $this->isConflict ) {
1864 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1865 } else {
1866 $conflict = '<hr />';
1867 }
1868
1869 $previewhead = "<div class='previewnote'>\n" .
1870 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
1871 $wgOut->parse( $note ) . $conflict . "</div>\n";
1872
1873 wfProfileOut( __METHOD__ );
1874 return $previewhead . $previewHTML;
1875 }
1876
1877 function getTemplates() {
1878 if ( $this->preview || $this->section != '' ) {
1879 $templates = array();
1880 if ( !isset($this->mParserOutput) ) return $templates;
1881 foreach( $this->mParserOutput->getTemplates() as $ns => $template) {
1882 foreach( array_keys( $template ) as $dbk ) {
1883 $templates[] = Title::makeTitle($ns, $dbk);
1884 }
1885 }
1886 return $templates;
1887 } else {
1888 return $this->mArticle->getUsedTemplates();
1889 }
1890 }
1891
1892 /**
1893 * Call the stock "user is blocked" page
1894 */
1895 function blockedPage() {
1896 global $wgOut, $wgUser;
1897 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1898
1899 # If the user made changes, preserve them when showing the markup
1900 # (This happens when a user is blocked during edit, for instance)
1901 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1902 if ( $first ) {
1903 $source = $this->mTitle->exists() ? $this->getContent() : false;
1904 } else {
1905 $source = $this->textbox1;
1906 }
1907
1908 # Spit out the source or the user's modified version
1909 if ( $source !== false ) {
1910 $rows = $wgUser->getIntOption( 'rows' );
1911 $cols = $wgUser->getIntOption( 'cols' );
1912 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1913 $wgOut->addHTML( '<hr />' );
1914 $wgOut->addWikiMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() );
1915 # Why we don't use Xml::element here?
1916 # Is it because if $source is '', it returns <textarea />?
1917 $wgOut->addHTML( Xml::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml::closeElement( 'textarea' ) );
1918 }
1919 }
1920
1921 /**
1922 * Produce the stock "please login to edit pages" page
1923 */
1924 function userNotLoggedInPage() {
1925 global $wgUser, $wgOut, $wgTitle;
1926 $skin = $wgUser->getSkin();
1927
1928 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1929 $loginLink = $skin->link(
1930 $loginTitle,
1931 wfMsgHtml( 'loginreqlink' ),
1932 array(),
1933 array( 'returnto' => $wgTitle->getPrefixedText() ),
1934 array( 'known', 'noclasses' )
1935 );
1936
1937 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1938 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1939 $wgOut->setArticleRelated( false );
1940
1941 $wgOut->addHTML( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1942 $wgOut->returnToMain( false, $wgTitle );
1943 }
1944
1945 /**
1946 * Creates a basic error page which informs the user that
1947 * they have attempted to edit a nonexistent section.
1948 */
1949 function noSuchSectionPage() {
1950 global $wgOut, $wgTitle;
1951
1952 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1953 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1954 $wgOut->setArticleRelated( false );
1955
1956 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section );
1957 $wgOut->returnToMain( false, $wgTitle );
1958 }
1959
1960 /**
1961 * Produce the stock "your edit contains spam" page
1962 *
1963 * @param $match Text which triggered one or more filters
1964 */
1965 function spamPage( $match = false ) {
1966 global $wgOut, $wgTitle;
1967
1968 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1969 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1970 $wgOut->setArticleRelated( false );
1971
1972 $wgOut->addHTML( '<div id="spamprotected">' );
1973 $wgOut->addWikiMsg( 'spamprotectiontext' );
1974 if ( $match )
1975 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1976 $wgOut->addHTML( '</div>' );
1977
1978 $wgOut->returnToMain( false, $wgTitle );
1979 }
1980
1981 /**
1982 * @private
1983 * @todo document
1984 */
1985 function mergeChangesInto( &$editText ){
1986 $fname = 'EditPage::mergeChangesInto';
1987 wfProfileIn( $fname );
1988
1989 $db = wfGetDB( DB_MASTER );
1990
1991 // This is the revision the editor started from
1992 $baseRevision = $this->getBaseRevision();
1993 if ( is_null( $baseRevision ) ) {
1994 wfProfileOut( $fname );
1995 return false;
1996 }
1997 $baseText = $baseRevision->getText();
1998
1999 // The current state, we want to merge updates into it
2000 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2001 if ( is_null( $currentRevision ) ) {
2002 wfProfileOut( $fname );
2003 return false;
2004 }
2005 $currentText = $currentRevision->getText();
2006
2007 $result = '';
2008 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
2009 $editText = $result;
2010 wfProfileOut( $fname );
2011 return true;
2012 } else {
2013 wfProfileOut( $fname );
2014 return false;
2015 }
2016 }
2017
2018 /**
2019 * Check if the browser is on a blacklist of user-agents known to
2020 * mangle UTF-8 data on form submission. Returns true if Unicode
2021 * should make it through, false if it's known to be a problem.
2022 * @return bool
2023 * @private
2024 */
2025 function checkUnicodeCompliantBrowser() {
2026 global $wgBrowserBlackList;
2027 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2028 // No User-Agent header sent? Trust it by default...
2029 return true;
2030 }
2031 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2032 foreach ( $wgBrowserBlackList as $browser ) {
2033 if ( preg_match($browser, $currentbrowser) ) {
2034 return false;
2035 }
2036 }
2037 return true;
2038 }
2039
2040 /**
2041 * @deprecated use $wgParser->stripSectionName()
2042 */
2043 function pseudoParseSectionAnchor( $text ) {
2044 global $wgParser;
2045 return $wgParser->stripSectionName( $text );
2046 }
2047
2048 /**
2049 * Format an anchor fragment as it would appear for a given section name
2050 * @param string $text
2051 * @return string
2052 * @private
2053 */
2054 function sectionAnchor( $text ) {
2055 global $wgParser;
2056 return $wgParser->guessSectionNameFromWikiText( $text );
2057 }
2058
2059 /**
2060 * Shows a bulletin board style toolbar for common editing functions.
2061 * It can be disabled in the user preferences.
2062 * The necessary JavaScript code can be found in skins/common/edit.js.
2063 *
2064 * @return string
2065 */
2066 static function getEditToolbar() {
2067 global $wgStylePath, $wgContLang, $wgLang;
2068
2069 /**
2070 * toolarray an array of arrays which each include the filename of
2071 * the button image (without path), the opening tag, the closing tag,
2072 * and optionally a sample text that is inserted between the two when no
2073 * selection is highlighted.
2074 * The tip text is shown when the user moves the mouse over the button.
2075 *
2076 * Already here are accesskeys (key), which are not used yet until someone
2077 * can figure out a way to make them work in IE. However, we should make
2078 * sure these keys are not defined on the edit page.
2079 */
2080 $toolarray = array(
2081 array(
2082 'image' => $wgLang->getImageFile('button-bold'),
2083 'id' => 'mw-editbutton-bold',
2084 'open' => '\'\'\'',
2085 'close' => '\'\'\'',
2086 'sample' => wfMsg('bold_sample'),
2087 'tip' => wfMsg('bold_tip'),
2088 'key' => 'B'
2089 ),
2090 array(
2091 'image' => $wgLang->getImageFile('button-italic'),
2092 'id' => 'mw-editbutton-italic',
2093 'open' => '\'\'',
2094 'close' => '\'\'',
2095 'sample' => wfMsg('italic_sample'),
2096 'tip' => wfMsg('italic_tip'),
2097 'key' => 'I'
2098 ),
2099 array(
2100 'image' => $wgLang->getImageFile('button-link'),
2101 'id' => 'mw-editbutton-link',
2102 'open' => '[[',
2103 'close' => ']]',
2104 'sample' => wfMsg('link_sample'),
2105 'tip' => wfMsg('link_tip'),
2106 'key' => 'L'
2107 ),
2108 array(
2109 'image' => $wgLang->getImageFile('button-extlink'),
2110 'id' => 'mw-editbutton-extlink',
2111 'open' => '[',
2112 'close' => ']',
2113 'sample' => wfMsg('extlink_sample'),
2114 'tip' => wfMsg('extlink_tip'),
2115 'key' => 'X'
2116 ),
2117 array(
2118 'image' => $wgLang->getImageFile('button-headline'),
2119 'id' => 'mw-editbutton-headline',
2120 'open' => "\n== ",
2121 'close' => " ==\n",
2122 'sample' => wfMsg('headline_sample'),
2123 'tip' => wfMsg('headline_tip'),
2124 'key' => 'H'
2125 ),
2126 array(
2127 'image' => $wgLang->getImageFile('button-image'),
2128 'id' => 'mw-editbutton-image',
2129 'open' => '[['.$wgContLang->getNsText(NS_FILE).':',
2130 'close' => ']]',
2131 'sample' => wfMsg('image_sample'),
2132 'tip' => wfMsg('image_tip'),
2133 'key' => 'D'
2134 ),
2135 array(
2136 'image' => $wgLang->getImageFile('button-media'),
2137 'id' => 'mw-editbutton-media',
2138 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
2139 'close' => ']]',
2140 'sample' => wfMsg('media_sample'),
2141 'tip' => wfMsg('media_tip'),
2142 'key' => 'M'
2143 ),
2144 array(
2145 'image' => $wgLang->getImageFile('button-math'),
2146 'id' => 'mw-editbutton-math',
2147 'open' => "<math>",
2148 'close' => "</math>",
2149 'sample' => wfMsg('math_sample'),
2150 'tip' => wfMsg('math_tip'),
2151 'key' => 'C'
2152 ),
2153 array(
2154 'image' => $wgLang->getImageFile('button-nowiki'),
2155 'id' => 'mw-editbutton-nowiki',
2156 'open' => "<nowiki>",
2157 'close' => "</nowiki>",
2158 'sample' => wfMsg('nowiki_sample'),
2159 'tip' => wfMsg('nowiki_tip'),
2160 'key' => 'N'
2161 ),
2162 array(
2163 'image' => $wgLang->getImageFile('button-sig'),
2164 'id' => 'mw-editbutton-signature',
2165 'open' => '--~~~~',
2166 'close' => '',
2167 'sample' => '',
2168 'tip' => wfMsg('sig_tip'),
2169 'key' => 'Y'
2170 ),
2171 array(
2172 'image' => $wgLang->getImageFile('button-hr'),
2173 'id' => 'mw-editbutton-hr',
2174 'open' => "\n----\n",
2175 'close' => '',
2176 'sample' => '',
2177 'tip' => wfMsg('hr_tip'),
2178 'key' => 'R'
2179 )
2180 );
2181 $toolbar = "<div id='toolbar'>\n";
2182
2183 $script = '';
2184 foreach ( $toolarray as $tool ) {
2185 $params = array(
2186 $image = $wgStylePath.'/common/images/'.$tool['image'],
2187 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2188 // Older browsers show a "speedtip" type message only for ALT.
2189 // Ideally these should be different, realistically they
2190 // probably don't need to be.
2191 $tip = $tool['tip'],
2192 $open = $tool['open'],
2193 $close = $tool['close'],
2194 $sample = $tool['sample'],
2195 $cssId = $tool['id'],
2196 );
2197
2198 $paramList = implode( ',',
2199 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2200 $script .= "addButton($paramList);\n";
2201 }
2202 $toolbar .= Html::inlineScript( "\n$script\n" );
2203
2204 $toolbar .= "\n</div>";
2205
2206 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2207
2208 return $toolbar;
2209 }
2210
2211 /**
2212 * Returns an array of html code of the following checkboxes:
2213 * minor and watch
2214 *
2215 * @param $tabindex Current tabindex
2216 * @param $skin Skin object
2217 * @param $checked Array of checkbox => bool, where bool indicates the checked
2218 * status of the checkbox
2219 *
2220 * @return array
2221 */
2222 public function getCheckboxes( &$tabindex, $skin, $checked ) {
2223 global $wgUser;
2224
2225 $checkboxes = array();
2226
2227 $checkboxes['minor'] = '';
2228 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
2229 if ( $wgUser->isAllowed('minoredit') ) {
2230 $attribs = array(
2231 'tabindex' => ++$tabindex,
2232 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2233 'id' => 'wpMinoredit',
2234 );
2235 $checkboxes['minor'] =
2236 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2237 "&nbsp;<label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>";
2238 }
2239
2240 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
2241 $checkboxes['watch'] = '';
2242 if ( $wgUser->isLoggedIn() ) {
2243 $attribs = array(
2244 'tabindex' => ++$tabindex,
2245 'accesskey' => wfMsg( 'accesskey-watch' ),
2246 'id' => 'wpWatchthis',
2247 );
2248 $checkboxes['watch'] =
2249 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2250 "&nbsp;<label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>";
2251 }
2252 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2253 return $checkboxes;
2254 }
2255
2256 /**
2257 * Returns an array of html code of the following buttons:
2258 * save, diff, preview and live
2259 *
2260 * @param $tabindex Current tabindex
2261 *
2262 * @return array
2263 */
2264 public function getEditButtons(&$tabindex) {
2265 global $wgLivePreview, $wgUser;
2266
2267 $buttons = array();
2268
2269 $temp = array(
2270 'id' => 'wpSave',
2271 'name' => 'wpSave',
2272 'type' => 'submit',
2273 'tabindex' => ++$tabindex,
2274 'value' => wfMsg('savearticle'),
2275 'accesskey' => wfMsg('accesskey-save'),
2276 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2277 );
2278 $buttons['save'] = Xml::element('input', $temp, '');
2279
2280 ++$tabindex; // use the same for preview and live preview
2281 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
2282 $this->doLivePreviewScript(); // Add to output
2283
2284 $temp = array(
2285 'id' => 'wpPreview',
2286 'name' => 'wpPreview',
2287 'type' => 'submit',
2288 'tabindex' => $tabindex,
2289 'value' => wfMsg('showpreview'),
2290 'accesskey' => '',
2291 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2292 'style' => 'display: none;',
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 );
2305
2306 $buttons['live'] = Xml::element('input', $temp, '');
2307 } else {
2308 $temp = array(
2309 'id' => 'wpPreview',
2310 'name' => 'wpPreview',
2311 'type' => 'submit',
2312 'tabindex' => $tabindex,
2313 'value' => wfMsg('showpreview'),
2314 'accesskey' => wfMsg('accesskey-preview'),
2315 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2316 );
2317 $buttons['preview'] = Xml::element('input', $temp, '');
2318 $buttons['live'] = '';
2319 }
2320
2321 $temp = array(
2322 'id' => 'wpDiff',
2323 'name' => 'wpDiff',
2324 'type' => 'submit',
2325 'tabindex' => ++$tabindex,
2326 'value' => wfMsg('showdiff'),
2327 'accesskey' => wfMsg('accesskey-diff'),
2328 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2329 );
2330 $buttons['diff'] = Xml::element('input', $temp, '');
2331
2332 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2333 return $buttons;
2334 }
2335
2336
2337 /**
2338 * Get a diff between the current contents of the edit box and the
2339 * version of the page we're editing from.
2340 *
2341 * If this is a section edit, we'll replace the section as for final
2342 * save and then make a comparison.
2343 */
2344 function showDiff() {
2345 $oldtext = $this->mArticle->fetchContent();
2346 $newtext = $this->mArticle->replaceSection(
2347 $this->section, $this->textbox1, $this->summary, $this->edittime );
2348 $newtext = $this->mArticle->preSaveTransform( $newtext );
2349 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2350 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2351 if ( $oldtext !== false || $newtext != '' ) {
2352 $de = new DifferenceEngine( $this->mTitle );
2353 $de->setText( $oldtext, $newtext );
2354 $difftext = $de->getDiff( $oldtitle, $newtitle );
2355 $de->showDiffStyle();
2356 } else {
2357 $difftext = '';
2358 }
2359
2360 global $wgOut;
2361 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2362 }
2363
2364 /**
2365 * Filter an input field through a Unicode de-armoring process if it
2366 * came from an old browser with known broken Unicode editing issues.
2367 *
2368 * @param WebRequest $request
2369 * @param string $field
2370 * @return string
2371 * @private
2372 */
2373 function safeUnicodeInput( $request, $field ) {
2374 $text = rtrim( $request->getText( $field ) );
2375 return $request->getBool( 'safemode' )
2376 ? $this->unmakesafe( $text )
2377 : $text;
2378 }
2379
2380 /**
2381 * Filter an output field through a Unicode armoring process if it is
2382 * going to an old browser with known broken Unicode editing issues.
2383 *
2384 * @param string $text
2385 * @return string
2386 * @private
2387 */
2388 function safeUnicodeOutput( $text ) {
2389 global $wgContLang;
2390 $codedText = $wgContLang->recodeForEdit( $text );
2391 return $this->checkUnicodeCompliantBrowser()
2392 ? $codedText
2393 : $this->makesafe( $codedText );
2394 }
2395
2396 /**
2397 * A number of web browsers are known to corrupt non-ASCII characters
2398 * in a UTF-8 text editing environment. To protect against this,
2399 * detected browsers will be served an armored version of the text,
2400 * with non-ASCII chars converted to numeric HTML character references.
2401 *
2402 * Preexisting such character references will have a 0 added to them
2403 * to ensure that round-trips do not alter the original data.
2404 *
2405 * @param string $invalue
2406 * @return string
2407 * @private
2408 */
2409 function makesafe( $invalue ) {
2410 // Armor existing references for reversability.
2411 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
2412
2413 $bytesleft = 0;
2414 $result = "";
2415 $working = 0;
2416 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2417 $bytevalue = ord( $invalue{$i} );
2418 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2419 $result .= chr( $bytevalue );
2420 $bytesleft = 0;
2421 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2422 $working = $working << 6;
2423 $working += ($bytevalue & 0x3F);
2424 $bytesleft--;
2425 if ( $bytesleft <= 0 ) {
2426 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2427 }
2428 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2429 $working = $bytevalue & 0x1F;
2430 $bytesleft = 1;
2431 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2432 $working = $bytevalue & 0x0F;
2433 $bytesleft = 2;
2434 } else { //1111 0xxx
2435 $working = $bytevalue & 0x07;
2436 $bytesleft = 3;
2437 }
2438 }
2439 return $result;
2440 }
2441
2442 /**
2443 * Reverse the previously applied transliteration of non-ASCII characters
2444 * back to UTF-8. Used to protect data from corruption by broken web browsers
2445 * as listed in $wgBrowserBlackList.
2446 *
2447 * @param string $invalue
2448 * @return string
2449 * @private
2450 */
2451 function unmakesafe( $invalue ) {
2452 $result = "";
2453 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2454 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
2455 $i += 3;
2456 $hexstring = "";
2457 do {
2458 $hexstring .= $invalue{$i};
2459 $i++;
2460 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2461
2462 // Do some sanity checks. These aren't needed for reversability,
2463 // but should help keep the breakage down if the editor
2464 // breaks one of the entities whilst editing.
2465 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2466 $codepoint = hexdec($hexstring);
2467 $result .= codepointToUtf8( $codepoint );
2468 } else {
2469 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2470 }
2471 } else {
2472 $result .= substr( $invalue, $i, 1 );
2473 }
2474 }
2475 // reverse the transform that we made for reversability reasons.
2476 return strtr( $result, array( "&#x0" => "&#x" ) );
2477 }
2478
2479 function noCreatePermission() {
2480 global $wgOut;
2481 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2482 $wgOut->addWikiMsg( 'nocreatetext' );
2483 }
2484
2485 /**
2486 * Attempt submission
2487 * @return bool false if output is done, true if the rest of the form should be displayed
2488 */
2489 function attemptSave() {
2490 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2491
2492 $resultDetails = false;
2493 # Allow bots to exempt some edits from bot flagging
2494 $bot = $wgUser->isAllowed('bot') && $wgRequest->getBool('bot',true);
2495 $value = $this->internalAttemptSave( $resultDetails, $bot );
2496
2497 if ( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) {
2498 $this->didSave = true;
2499 }
2500
2501 switch ($value) {
2502 case self::AS_HOOK_ERROR_EXPECTED:
2503 case self::AS_CONTENT_TOO_BIG:
2504 case self::AS_ARTICLE_WAS_DELETED:
2505 case self::AS_CONFLICT_DETECTED:
2506 case self::AS_SUMMARY_NEEDED:
2507 case self::AS_TEXTBOX_EMPTY:
2508 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
2509 case self::AS_END:
2510 return true;
2511
2512 case self::AS_HOOK_ERROR:
2513 case self::AS_FILTERING:
2514 case self::AS_SUCCESS_NEW_ARTICLE:
2515 case self::AS_SUCCESS_UPDATE:
2516 return false;
2517
2518 case self::AS_SPAM_ERROR:
2519 $this->spamPage ( $resultDetails['spam'] );
2520 return false;
2521
2522 case self::AS_BLOCKED_PAGE_FOR_USER:
2523 $this->blockedPage();
2524 return false;
2525
2526 case self::AS_IMAGE_REDIRECT_ANON:
2527 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2528 return false;
2529
2530 case self::AS_READ_ONLY_PAGE_ANON:
2531 $this->userNotLoggedInPage();
2532 return false;
2533
2534 case self::AS_READ_ONLY_PAGE_LOGGED:
2535 case self::AS_READ_ONLY_PAGE:
2536 $wgOut->readOnlyPage();
2537 return false;
2538
2539 case self::AS_RATE_LIMITED:
2540 $wgOut->rateLimited();
2541 return false;
2542
2543 case self::AS_NO_CREATE_PERMISSION;
2544 $this->noCreatePermission();
2545 return;
2546
2547 case self::AS_BLANK_ARTICLE:
2548 $wgOut->redirect( $wgTitle->getFullURL() );
2549 return false;
2550
2551 case self::AS_IMAGE_REDIRECT_LOGGED:
2552 $wgOut->permissionRequired( 'upload' );
2553 return false;
2554 }
2555 }
2556
2557 function getBaseRevision() {
2558 if ( $this->mBaseRevision == false ) {
2559 $db = wfGetDB( DB_MASTER );
2560 $baseRevision = Revision::loadFromTimestamp(
2561 $db, $this->mTitle, $this->edittime );
2562 return $this->mBaseRevision = $baseRevision;
2563 } else {
2564 return $this->mBaseRevision;
2565 }
2566 }
2567 }