Follow-up on r56284: LogEventsList::showLogExtract gets associative array for additio...
[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 if ( $this->isConflict ) {
1200 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1</div>", 'explainconflict' );
1201
1202 $this->textbox2 = $this->textbox1;
1203 $this->textbox1 = $this->getContent();
1204 $this->edittime = $this->mArticle->getTimestamp();
1205 } else {
1206 if ( $this->section != '' && $this->section != 'new' ) {
1207 $matches = array();
1208 if ( !$this->summary && !$this->preview && !$this->diff ) {
1209 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1, $matches );
1210 if ( !empty( $matches[2] ) ) {
1211 global $wgParser;
1212 $this->summary = "/* " .
1213 $wgParser->stripSectionName(trim($matches[2])) .
1214 " */ ";
1215 }
1216 }
1217 }
1218
1219 if ( $this->missingComment ) {
1220 $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' );
1221 }
1222
1223 if ( $this->missingSummary && $this->section != 'new' ) {
1224 $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' );
1225 }
1226
1227 if ( $this->missingSummary && $this->section == 'new' ) {
1228 $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' );
1229 }
1230
1231 if ( $this->hookError !== '' ) {
1232 $wgOut->addWikiText( $this->hookError );
1233 }
1234
1235 if ( !$this->checkUnicodeCompliantBrowser() ) {
1236 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1237 }
1238 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
1239 // Let sysop know that this will make private content public if saved
1240
1241 if ( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1242 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
1243 } else if ( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1244 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
1245 }
1246
1247 if ( !$this->mArticle->mRevision->isCurrent() ) {
1248 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
1249 $wgOut->addWikiMsg( 'editingold' );
1250 }
1251 }
1252 }
1253
1254 if ( wfReadOnly() ) {
1255 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1256 } elseif ( $wgUser->isAnon() && $this->formtype != 'preview' ) {
1257 $wgOut->wrapWikiMsg( '<div id="mw-anon-edit-warning">$1</div>', 'anoneditwarning' );
1258 } else {
1259 if ( $this->isCssJsSubpage ) {
1260 # Check the skin exists
1261 if ( !$this->isValidCssJsSubpage ) {
1262 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1263 }
1264 if ( $this->formtype !== 'preview' ) {
1265 if ( $this->isCssSubpage )
1266 $wgOut->addWikiMsg( 'usercssyoucanpreview' );
1267 if ( $this->isJsSubpage )
1268 $wgOut->addWikiMsg( 'userjsyoucanpreview' );
1269 }
1270 }
1271 }
1272
1273 $classes = array(); // Textarea CSS
1274 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1275 } elseif ( $this->mTitle->isProtected( 'edit' ) ) {
1276 # Is the title semi-protected?
1277 if ( $this->mTitle->isSemiProtected() ) {
1278 $noticeMsg = 'semiprotectedpagewarning';
1279 $classes[] = 'mw-textarea-sprotected';
1280 } else {
1281 # Then it must be protected based on static groups (regular)
1282 $noticeMsg = 'protectedpagewarning';
1283 $classes[] = 'mw-textarea-protected';
1284 }
1285 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle->getPrefixedText(), '',
1286 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1287 }
1288 if ( $this->mTitle->isCascadeProtected() ) {
1289 # Is this page under cascading protection from some source pages?
1290 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1291 $notice = "<div class='mw-cascadeprotectedwarning'>$1\n";
1292 $cascadeSourcesCount = count( $cascadeSources );
1293 if ( $cascadeSourcesCount > 0 ) {
1294 # Explain, and list the titles responsible
1295 foreach( $cascadeSources as $page ) {
1296 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1297 }
1298 }
1299 $notice .= '</div>';
1300 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1301 }
1302 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
1303 $wgOut->wrapWikiMsg( '<div class="mw-titleprotectedwarning">$1</div>', 'titleprotectedwarning' );
1304 }
1305
1306 if ( $this->kblength === false ) {
1307 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
1308 }
1309 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1310 $wgOut->addHTML( "<div class='error' id='mw-edit-longpageerror'>\n" );
1311 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) );
1312 $wgOut->addHTML( "</div>\n" );
1313 } elseif ( $this->kblength > 29 ) {
1314 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1315 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) );
1316 $wgOut->addHTML( "</div>\n" );
1317 }
1318
1319 $action = $wgTitle->escapeLocalURL( array( 'action' => $this->action ) );
1320
1321 $summary = wfMsgExt( 'summary', 'parseinline' );
1322 $subject = wfMsgExt( 'subject', 'parseinline' );
1323
1324 $cancel = $sk->link(
1325 $wgTitle,
1326 wfMsgExt( 'cancel', array( 'parseinline' ) ),
1327 array( 'id' => 'mw-editform-cancel' ),
1328 array(),
1329 array( 'known', 'noclasses' )
1330 );
1331 $separator = wfMsgExt( 'pipe-separator' , 'escapenoentities' );
1332 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1333 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1334 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1335 htmlspecialchars( wfMsg( 'newwindow' ) );
1336
1337 global $wgRightsText;
1338 if ( $wgRightsText ) {
1339 $copywarnMsg = array( 'copyrightwarning',
1340 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1341 $wgRightsText );
1342 } else {
1343 $copywarnMsg = array( 'copyrightwarning2',
1344 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1345 }
1346 // Allow for site and per-namespace customization of contribution/copyright notice.
1347 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle, &$copywarnMsg ) );
1348
1349 if ( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
1350 # prepare toolbar for edit buttons
1351 $toolbar = EditPage::getEditToolbar();
1352 } else {
1353 $toolbar = '';
1354 }
1355
1356
1357 // activate checkboxes if user wants them to be always active
1358 if ( !$this->preview && !$this->diff ) {
1359 # Sort out the "watch" checkbox
1360 if ( $wgUser->getOption( 'watchdefault' ) ) {
1361 # Watch all edits
1362 $this->watchthis = true;
1363 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1364 # Watch creations
1365 $this->watchthis = true;
1366 } elseif ( $this->mTitle->userIsWatching() ) {
1367 # Already watched
1368 $this->watchthis = true;
1369 }
1370
1371 # May be overriden by request parameters
1372 if( $wgRequest->getBool( 'watchthis' ) ) {
1373 $this->watchthis = true;
1374 }
1375
1376 if ( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1377 }
1378
1379 $wgOut->addHTML( $this->editFormPageTop );
1380
1381 if ( $wgUser->getOption( 'previewontop' ) ) {
1382 $this->displayPreviewArea( $previewOutput, true );
1383 }
1384
1385
1386 $wgOut->addHTML( $this->editFormTextTop );
1387
1388 # if this is a comment, show a subject line at the top, which is also the edit summary.
1389 # Otherwise, show a summary field at the bottom
1390 $summarytext = $wgContLang->recodeForEdit( $this->summary );
1391
1392 # If a blank edit summary was previously provided, and the appropriate
1393 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1394 # user being bounced back more than once in the event that a summary
1395 # is not required.
1396 #####
1397 # For a bit more sophisticated detection of blank summaries, hash the
1398 # automatic one and pass that in the hidden field wpAutoSummary.
1399 $summaryhiddens = '';
1400 if ( $this->missingSummary ) $summaryhiddens .= Xml::hidden( 'wpIgnoreBlankSummary', true );
1401 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1402 $summaryhiddens .= Xml::hidden( 'wpAutoSummary', $autosumm );
1403 if ( $this->section == 'new' ) {
1404 $commentsubject = '';
1405 if ( !$wgRequest->getBool( 'nosummary' ) ) {
1406 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1407 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
1408
1409 $commentsubject =
1410 Xml::tags( 'label', array( 'for' => 'wpSummary' ), $subject );
1411 $commentsubject =
1412 Xml::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1413 $commentsubject );
1414 $commentsubject .= '&nbsp;';
1415 $commentsubject .= Xml::input( 'wpSummary',
1416 60,
1417 $summarytext,
1418 array(
1419 'id' => 'wpSummary',
1420 'maxlength' => '200',
1421 'tabindex' => '1'
1422 ) );
1423 } else {
1424 $summaryhiddens .= Xml::hidden( 'wpIgnoreBlankSummary', true ); # bug 18699
1425 }
1426 $editsummary = "<div class='editOptions'>\n";
1427 global $wgParser;
1428 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary ) );
1429 $subjectpreview = $summarytext && ( $this->preview || $this->diff ) ?
1430 "<div class=\"mw-summary-preview\">". wfMsgExt('subject-preview', 'parseinline') . $sk->commentBlock( $formattedSummary, $this->mTitle, true )."</div>\n" : '';
1431 $summarypreview = '';
1432 } else {
1433 $commentsubject = '';
1434
1435 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1436 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
1437
1438 $editsummary = Xml::tags( 'label', array( 'for' => 'wpSummary' ), $summary );
1439 $editsummary = Xml::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1440 $editsummary ) . ' ';
1441
1442 $editsummary .= Xml::input( 'wpSummary',
1443 60,
1444 $summarytext,
1445 array(
1446 'id' => 'wpSummary',
1447 'maxlength' => '200',
1448 'tabindex' => '1'
1449 ) );
1450
1451 // No idea where this is closed.
1452 $editsummary = Xml::openElement( 'div', array( 'class' => 'editOptions' ) )
1453 . $editsummary . '<br/>';
1454
1455 $summarypreview = '';
1456 if ( $summarytext && ( $this->preview || $this->diff ) ) {
1457 $summarypreview =
1458 Xml::tags( 'div',
1459 array( 'class' => 'mw-summary-preview' ),
1460 wfMsgExt( 'summary-preview', 'parseinline' ) .
1461 $sk->commentBlock( $this->summary, $this->mTitle )
1462 );
1463 }
1464 $subjectpreview = '';
1465 }
1466 $commentsubject .= $summaryhiddens;
1467
1468 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1469 if ( !$this->preview && !$this->diff ) {
1470 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1471 }
1472 $templates = $this->getTemplates();
1473 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1474
1475 $hiddencats = $this->mArticle->getHiddenCategories();
1476 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1477
1478 global $wgUseMetadataEdit ;
1479 if ( $wgUseMetadataEdit ) {
1480 $metadata = $this->mMetaData ;
1481 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1482 $top = wfMsgWikiHtml( 'metadata_help' );
1483 /* ToDo: Replace with clean code */
1484 $ew = $wgUser->getOption( 'editwidth' );
1485 if ( $ew ) $ew = " style=\"width:100%\"";
1486 else $ew = '';
1487 $cols = $wgUser->getIntOption( 'cols' );
1488 /* /ToDo */
1489 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1490 }
1491 else $metadata = "" ;
1492
1493 $recreate = '';
1494 if ( $this->wasDeletedSinceLastEdit() ) {
1495 if ( 'save' != $this->formtype ) {
1496 $wgOut->wrapWikiMsg(
1497 "<div class='error mw-deleted-while-editing'>\n$1</div>",
1498 'deletedwhileediting' );
1499 } else {
1500 // Hide the toolbar and edit area, user can click preview to get it back
1501 // Add an confirmation checkbox and explanation.
1502 $toolbar = '';
1503 $recreate = '<div class="mw-confirm-recreate">' .
1504 $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ) ) .
1505 Xml::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1506 array( 'title' => $sk->titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1507 ) . '</div>';
1508 }
1509 }
1510
1511 $tabindex = 2;
1512
1513 $checkboxes = $this->getCheckboxes( $tabindex, $sk,
1514 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1515
1516 $checkboxhtml = implode( $checkboxes, "\n" );
1517
1518 $buttons = $this->getEditButtons( $tabindex );
1519 $buttonshtml = implode( $buttons, "\n" );
1520
1521 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1522 ? '' : Xml::hidden( 'safemode', '1' );
1523
1524 $wgOut->addHTML( <<<END
1525 {$toolbar}
1526 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1527 END
1528 );
1529
1530 if ( is_callable( $formCallback ) ) {
1531 call_user_func_array( $formCallback, array( &$wgOut ) );
1532 }
1533
1534 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1535
1536 // Put these up at the top to ensure they aren't lost on early form submission
1537 $this->showFormBeforeText();
1538
1539 $wgOut->addHTML( <<<END
1540 {$recreate}
1541 {$commentsubject}
1542 {$subjectpreview}
1543 {$this->editFormTextBeforeContent}
1544 END
1545 );
1546 $this->showTextbox1( $classes );
1547
1548 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1549 $wgOut->addHTML( <<<END
1550 {$this->editFormTextAfterWarn}
1551 {$metadata}
1552 {$editsummary}
1553 {$summarypreview}
1554 {$checkboxhtml}
1555 {$safemodehtml}
1556 END
1557 );
1558
1559 $wgOut->addHTML(
1560 "<div class='editButtons'>
1561 {$buttonshtml}
1562 <span class='editHelp'>{$cancel}{$separator}{$edithelp}</span>
1563 </div><!-- editButtons -->
1564 </div><!-- editOptions -->");
1565
1566 /**
1567 * To make it harder for someone to slip a user a page
1568 * which submits an edit form to the wiki without their
1569 * knowledge, a random token is associated with the login
1570 * session. If it's not passed back with the submission,
1571 * we won't save the page, or render user JavaScript and
1572 * CSS previews.
1573 *
1574 * For anon editors, who may not have a session, we just
1575 * include the constant suffix to prevent editing from
1576 * broken text-mangling proxies.
1577 */
1578 $token = htmlspecialchars( $wgUser->editToken() );
1579 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1580
1581 $this->showTosSummary();
1582 $this->showEditTools();
1583
1584 $wgOut->addHTML( <<<END
1585 {$this->editFormTextAfterTools}
1586 <div class='templatesUsed'>
1587 {$formattedtemplates}
1588 </div>
1589 <div class='hiddencats'>
1590 {$formattedhiddencats}
1591 </div>
1592 END
1593 );
1594
1595 if (!$this->preview) {
1596 $wgOut->addHTML( Xml::tags( 'div',
1597 array( 'class' => 'catlinks catlinks-allhidden',
1598 'id' => 'catlinks' ), ' ' ) );
1599 }
1600
1601 if ( $this->isConflict && wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1602 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1603
1604 $de = new DifferenceEngine( $this->mTitle );
1605 $de->setText( $this->textbox2, $this->textbox1 );
1606 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1607
1608 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1609 $this->showTextbox2();
1610 }
1611 $wgOut->addHTML( $this->editFormTextBottom );
1612 $wgOut->addHTML( "</form>\n" );
1613 if ( !$wgUser->getOption( 'previewontop' ) ) {
1614 $this->displayPreviewArea( $previewOutput, false );
1615 }
1616
1617 wfProfileOut( $fname );
1618 }
1619
1620 protected function showFormBeforeText() {
1621 global $wgOut;
1622 $wgOut->addHTML( "
1623 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1624 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1625 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1626 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1627 }
1628
1629 protected function showTextbox1( $classes ) {
1630 $attribs = array( 'tabindex' => 1 );
1631
1632 if ( $this->wasDeletedSinceLastEdit() )
1633 $attribs['type'] = 'hidden';
1634 if ( !empty($classes) )
1635 $attribs['class'] = implode(' ',$classes);
1636
1637 $this->showTextbox( $this->textbox1, 'wpTextbox1', $attribs );
1638 }
1639
1640 protected function showTextbox2() {
1641 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6 ) );
1642 }
1643
1644 protected function showTextbox( $content, $name, $attribs = array() ) {
1645 global $wgOut, $wgUser;
1646
1647 $wikitext = $this->safeUnicodeOutput( $content );
1648 if ( $wikitext !== '' ) {
1649 // Ensure there's a newline at the end, otherwise adding lines
1650 // is awkward.
1651 // But don't add a newline if the ext is empty, or Firefox in XHTML
1652 // mode will show an extra newline. A bit annoying.
1653 $wikitext .= "\n";
1654 }
1655
1656 $attribs['accesskey'] = ',';
1657 $attribs['id'] = $name;
1658
1659 if ( $wgUser->getOption( 'editwidth' ) )
1660 $attribs['style'] = 'width: 100%';
1661
1662 $wgOut->addHTML( Xml::textarea(
1663 $name,
1664 $wikitext,
1665 $wgUser->getIntOption( 'cols' ), $wgUser->getIntOption( 'rows' ),
1666 $attribs ) );
1667 }
1668
1669 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1670 global $wgOut;
1671 $classes = array();
1672 if ( $isOnTop )
1673 $classes[] = 'ontop';
1674
1675 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1676
1677 if ( $this->formtype != 'preview' )
1678 $attribs['style'] = 'display: none;';
1679
1680 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
1681
1682 if ( $this->formtype == 'preview' ) {
1683 $this->showPreview( $previewOutput );
1684 }
1685
1686 $wgOut->addHTML( '</div>' );
1687
1688 if ( $this->formtype == 'diff') {
1689 $this->showDiff();
1690 }
1691 }
1692
1693 /**
1694 * Append preview output to $wgOut.
1695 * Includes category rendering if this is a category page.
1696 *
1697 * @param string $text The HTML to be output for the preview.
1698 */
1699 protected function showPreview( $text ) {
1700 global $wgOut;
1701 if ( $this->mTitle->getNamespace() == NS_CATEGORY) {
1702 $this->mArticle->openShowCategory();
1703 }
1704 # This hook seems slightly odd here, but makes things more
1705 # consistent for extensions.
1706 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1707 $wgOut->addHTML( $text );
1708 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1709 $this->mArticle->closeShowCategory();
1710 }
1711 }
1712
1713 /**
1714 * Live Preview lets us fetch rendered preview page content and
1715 * add it to the page without refreshing the whole page.
1716 * If not supported by the browser it will fall through to the normal form
1717 * submission method.
1718 *
1719 * This function outputs a script tag to support live preview, and
1720 * returns an onclick handler which should be added to the attributes
1721 * of the preview button
1722 */
1723 function doLivePreviewScript() {
1724 global $wgOut, $wgTitle;
1725 $wgOut->addScriptFile( 'preview.js' );
1726 return "";
1727 }
1728
1729 protected function showTosSummary() {
1730 $msg = 'editpage-tos-summary';
1731 // Give a chance for site and per-namespace customizations of
1732 // terms of service summary link that might exist separately
1733 // from the copyright notice.
1734 //
1735 // This will display between the save button and the edit tools,
1736 // so should remain short!
1737 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
1738 $text = wfMsg( $msg );
1739 if( !wfEmptyMsg( $msg, $text ) && $text !== '-' ) {
1740 global $wgOut;
1741 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1742 $wgOut->addWikiMsgArray( $msg, array() );
1743 $wgOut->addHTML( '</div>' );
1744 }
1745 }
1746
1747 protected function showEditTools() {
1748 global $wgOut;
1749 $wgOut->addHTML( '<div class="mw-editTools">' );
1750 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1751 $wgOut->addHTML( '</div>' );
1752 }
1753
1754 protected function getLastDelete() {
1755 $dbr = wfGetDB( DB_SLAVE );
1756 $data = $dbr->selectRow(
1757 array( 'logging', 'user' ),
1758 array( 'log_type',
1759 'log_action',
1760 'log_timestamp',
1761 'log_user',
1762 'log_namespace',
1763 'log_title',
1764 'log_comment',
1765 'log_params',
1766 'log_deleted',
1767 'user_name' ),
1768 array( 'log_namespace' => $this->mTitle->getNamespace(),
1769 'log_title' => $this->mTitle->getDBkey(),
1770 'log_type' => 'delete',
1771 'log_action' => 'delete',
1772 'user_id=log_user' ),
1773 __METHOD__,
1774 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1775 );
1776 // Quick paranoid permission checks...
1777 if( is_object($data) ) {
1778 if( $data->log_deleted & LogPage::DELETED_USER )
1779 $data->user_name = wfMsgHtml('rev-deleted-user');
1780 if( $data->log_deleted & LogPage::DELETED_COMMENT )
1781 $data->log_comment = wfMsgHtml('rev-deleted-comment');
1782 }
1783 return $data;
1784 }
1785
1786 /**
1787 * Get the rendered text for previewing.
1788 * @return string
1789 */
1790 function getPreviewText() {
1791 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang, $wgMessageCache;
1792
1793 wfProfileIn( __METHOD__ );
1794
1795 if ( $this->mTriedSave && !$this->mTokenOk ) {
1796 if ( $this->mTokenOkExceptSuffix ) {
1797 $note = wfMsg( 'token_suffix_mismatch' );
1798 } else {
1799 $note = wfMsg( 'session_fail_preview' );
1800 }
1801 } else {
1802 $note = wfMsg( 'previewnote' );
1803 }
1804
1805 $parserOptions = ParserOptions::newFromUser( $wgUser );
1806 $parserOptions->setEditSection( false );
1807 $parserOptions->setIsPreview( true );
1808 $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' );
1809
1810 global $wgRawHtml;
1811 if ( $wgRawHtml && !$this->mTokenOk ) {
1812 // Could be an offsite preview attempt. This is very unsafe if
1813 // HTML is enabled, as it could be an attack.
1814 return $wgOut->parse( "<div class='previewnote'>" .
1815 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1816 }
1817
1818 # don't parse user css/js, show message about preview
1819 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1820
1821 if ( $this->isCssJsSubpage ) {
1822 if (preg_match("/\\.css$/", $this->mTitle->getText() ) ) {
1823 $previewtext = wfMsg('usercsspreview');
1824 } else if (preg_match("/\\.js$/", $this->mTitle->getText() ) ) {
1825 $previewtext = wfMsg('userjspreview');
1826 }
1827 $parserOptions->setTidy(true);
1828 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
1829 $previewHTML = $parserOutput->mText;
1830 } elseif ( $rt = Title::newFromRedirectArray( $this->textbox1 ) ) {
1831 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
1832 } else {
1833 $toparse = $this->textbox1;
1834
1835 # If we're adding a comment, we need to show the
1836 # summary as the headline
1837 if ( $this->section=="new" && $this->summary!="" ) {
1838 $toparse="== {$this->summary} ==\n\n".$toparse;
1839 }
1840
1841 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData;
1842
1843 // Parse mediawiki messages with correct target language
1844 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1845 list( /* $unused */, $lang ) = $wgMessageCache->figureMessage( $this->mTitle->getText() );
1846 $obj = wfGetLangObj( $lang );
1847 $parserOptions->setTargetLanguage( $obj );
1848 }
1849
1850
1851 $parserOptions->setTidy(true);
1852 $parserOptions->enableLimitReport();
1853 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ),
1854 $this->mTitle, $parserOptions );
1855
1856 $previewHTML = $parserOutput->getText();
1857 $this->mParserOutput = $parserOutput;
1858 $wgOut->addParserOutputNoText( $parserOutput );
1859
1860 if ( count( $parserOutput->getWarnings() ) ) {
1861 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1862 }
1863 }
1864
1865 if( $this->isConflict ) {
1866 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1867 } else {
1868 $conflict = '<hr />';
1869 }
1870
1871 $previewhead = "<div class='previewnote'>\n" .
1872 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
1873 $wgOut->parse( $note ) . $conflict . "</div>\n";
1874
1875 wfProfileOut( __METHOD__ );
1876 return $previewhead . $previewHTML;
1877 }
1878
1879 function getTemplates() {
1880 if ( $this->preview || $this->section != '' ) {
1881 $templates = array();
1882 if ( !isset($this->mParserOutput) ) return $templates;
1883 foreach( $this->mParserOutput->getTemplates() as $ns => $template) {
1884 foreach( array_keys( $template ) as $dbk ) {
1885 $templates[] = Title::makeTitle($ns, $dbk);
1886 }
1887 }
1888 return $templates;
1889 } else {
1890 return $this->mArticle->getUsedTemplates();
1891 }
1892 }
1893
1894 /**
1895 * Call the stock "user is blocked" page
1896 */
1897 function blockedPage() {
1898 global $wgOut, $wgUser;
1899 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1900
1901 # If the user made changes, preserve them when showing the markup
1902 # (This happens when a user is blocked during edit, for instance)
1903 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1904 if ( $first ) {
1905 $source = $this->mTitle->exists() ? $this->getContent() : false;
1906 } else {
1907 $source = $this->textbox1;
1908 }
1909
1910 # Spit out the source or the user's modified version
1911 if ( $source !== false ) {
1912 $rows = $wgUser->getIntOption( 'rows' );
1913 $cols = $wgUser->getIntOption( 'cols' );
1914 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1915 $wgOut->addHTML( '<hr />' );
1916 $wgOut->addWikiMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() );
1917 # Why we don't use Xml::element here?
1918 # Is it because if $source is '', it returns <textarea />?
1919 $wgOut->addHTML( Xml::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml::closeElement( 'textarea' ) );
1920 }
1921 }
1922
1923 /**
1924 * Produce the stock "please login to edit pages" page
1925 */
1926 function userNotLoggedInPage() {
1927 global $wgUser, $wgOut, $wgTitle;
1928 $skin = $wgUser->getSkin();
1929
1930 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1931 $loginLink = $skin->link(
1932 $loginTitle,
1933 wfMsgHtml( 'loginreqlink' ),
1934 array(),
1935 array( 'returnto' => $wgTitle->getPrefixedText() ),
1936 array( 'known', 'noclasses' )
1937 );
1938
1939 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1940 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1941 $wgOut->setArticleRelated( false );
1942
1943 $wgOut->addHTML( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1944 $wgOut->returnToMain( false, $wgTitle );
1945 }
1946
1947 /**
1948 * Creates a basic error page which informs the user that
1949 * they have attempted to edit a nonexistent section.
1950 */
1951 function noSuchSectionPage() {
1952 global $wgOut, $wgTitle;
1953
1954 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1955 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1956 $wgOut->setArticleRelated( false );
1957
1958 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section );
1959 $wgOut->returnToMain( false, $wgTitle );
1960 }
1961
1962 /**
1963 * Produce the stock "your edit contains spam" page
1964 *
1965 * @param $match Text which triggered one or more filters
1966 */
1967 function spamPage( $match = false ) {
1968 global $wgOut, $wgTitle;
1969
1970 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1971 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1972 $wgOut->setArticleRelated( false );
1973
1974 $wgOut->addHTML( '<div id="spamprotected">' );
1975 $wgOut->addWikiMsg( 'spamprotectiontext' );
1976 if ( $match )
1977 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1978 $wgOut->addHTML( '</div>' );
1979
1980 $wgOut->returnToMain( false, $wgTitle );
1981 }
1982
1983 /**
1984 * @private
1985 * @todo document
1986 */
1987 function mergeChangesInto( &$editText ){
1988 $fname = 'EditPage::mergeChangesInto';
1989 wfProfileIn( $fname );
1990
1991 $db = wfGetDB( DB_MASTER );
1992
1993 // This is the revision the editor started from
1994 $baseRevision = $this->getBaseRevision();
1995 if ( is_null( $baseRevision ) ) {
1996 wfProfileOut( $fname );
1997 return false;
1998 }
1999 $baseText = $baseRevision->getText();
2000
2001 // The current state, we want to merge updates into it
2002 $currentRevision = Revision::loadFromTitle( $db, $this->mTitle );
2003 if ( is_null( $currentRevision ) ) {
2004 wfProfileOut( $fname );
2005 return false;
2006 }
2007 $currentText = $currentRevision->getText();
2008
2009 $result = '';
2010 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
2011 $editText = $result;
2012 wfProfileOut( $fname );
2013 return true;
2014 } else {
2015 wfProfileOut( $fname );
2016 return false;
2017 }
2018 }
2019
2020 /**
2021 * Check if the browser is on a blacklist of user-agents known to
2022 * mangle UTF-8 data on form submission. Returns true if Unicode
2023 * should make it through, false if it's known to be a problem.
2024 * @return bool
2025 * @private
2026 */
2027 function checkUnicodeCompliantBrowser() {
2028 global $wgBrowserBlackList;
2029 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2030 // No User-Agent header sent? Trust it by default...
2031 return true;
2032 }
2033 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2034 foreach ( $wgBrowserBlackList as $browser ) {
2035 if ( preg_match($browser, $currentbrowser) ) {
2036 return false;
2037 }
2038 }
2039 return true;
2040 }
2041
2042 /**
2043 * @deprecated use $wgParser->stripSectionName()
2044 */
2045 function pseudoParseSectionAnchor( $text ) {
2046 global $wgParser;
2047 return $wgParser->stripSectionName( $text );
2048 }
2049
2050 /**
2051 * Format an anchor fragment as it would appear for a given section name
2052 * @param string $text
2053 * @return string
2054 * @private
2055 */
2056 function sectionAnchor( $text ) {
2057 global $wgParser;
2058 return $wgParser->guessSectionNameFromWikiText( $text );
2059 }
2060
2061 /**
2062 * Shows a bulletin board style toolbar for common editing functions.
2063 * It can be disabled in the user preferences.
2064 * The necessary JavaScript code can be found in skins/common/edit.js.
2065 *
2066 * @return string
2067 */
2068 static function getEditToolbar() {
2069 global $wgStylePath, $wgContLang, $wgLang;
2070
2071 /**
2072 * toolarray an array of arrays which each include the filename of
2073 * the button image (without path), the opening tag, the closing tag,
2074 * and optionally a sample text that is inserted between the two when no
2075 * selection is highlighted.
2076 * The tip text is shown when the user moves the mouse over the button.
2077 *
2078 * Already here are accesskeys (key), which are not used yet until someone
2079 * can figure out a way to make them work in IE. However, we should make
2080 * sure these keys are not defined on the edit page.
2081 */
2082 $toolarray = array(
2083 array(
2084 'image' => $wgLang->getImageFile('button-bold'),
2085 'id' => 'mw-editbutton-bold',
2086 'open' => '\'\'\'',
2087 'close' => '\'\'\'',
2088 'sample' => wfMsg('bold_sample'),
2089 'tip' => wfMsg('bold_tip'),
2090 'key' => 'B'
2091 ),
2092 array(
2093 'image' => $wgLang->getImageFile('button-italic'),
2094 'id' => 'mw-editbutton-italic',
2095 'open' => '\'\'',
2096 'close' => '\'\'',
2097 'sample' => wfMsg('italic_sample'),
2098 'tip' => wfMsg('italic_tip'),
2099 'key' => 'I'
2100 ),
2101 array(
2102 'image' => $wgLang->getImageFile('button-link'),
2103 'id' => 'mw-editbutton-link',
2104 'open' => '[[',
2105 'close' => ']]',
2106 'sample' => wfMsg('link_sample'),
2107 'tip' => wfMsg('link_tip'),
2108 'key' => 'L'
2109 ),
2110 array(
2111 'image' => $wgLang->getImageFile('button-extlink'),
2112 'id' => 'mw-editbutton-extlink',
2113 'open' => '[',
2114 'close' => ']',
2115 'sample' => wfMsg('extlink_sample'),
2116 'tip' => wfMsg('extlink_tip'),
2117 'key' => 'X'
2118 ),
2119 array(
2120 'image' => $wgLang->getImageFile('button-headline'),
2121 'id' => 'mw-editbutton-headline',
2122 'open' => "\n== ",
2123 'close' => " ==\n",
2124 'sample' => wfMsg('headline_sample'),
2125 'tip' => wfMsg('headline_tip'),
2126 'key' => 'H'
2127 ),
2128 array(
2129 'image' => $wgLang->getImageFile('button-image'),
2130 'id' => 'mw-editbutton-image',
2131 'open' => '[['.$wgContLang->getNsText(NS_FILE).':',
2132 'close' => ']]',
2133 'sample' => wfMsg('image_sample'),
2134 'tip' => wfMsg('image_tip'),
2135 'key' => 'D'
2136 ),
2137 array(
2138 'image' => $wgLang->getImageFile('button-media'),
2139 'id' => 'mw-editbutton-media',
2140 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
2141 'close' => ']]',
2142 'sample' => wfMsg('media_sample'),
2143 'tip' => wfMsg('media_tip'),
2144 'key' => 'M'
2145 ),
2146 array(
2147 'image' => $wgLang->getImageFile('button-math'),
2148 'id' => 'mw-editbutton-math',
2149 'open' => "<math>",
2150 'close' => "</math>",
2151 'sample' => wfMsg('math_sample'),
2152 'tip' => wfMsg('math_tip'),
2153 'key' => 'C'
2154 ),
2155 array(
2156 'image' => $wgLang->getImageFile('button-nowiki'),
2157 'id' => 'mw-editbutton-nowiki',
2158 'open' => "<nowiki>",
2159 'close' => "</nowiki>",
2160 'sample' => wfMsg('nowiki_sample'),
2161 'tip' => wfMsg('nowiki_tip'),
2162 'key' => 'N'
2163 ),
2164 array(
2165 'image' => $wgLang->getImageFile('button-sig'),
2166 'id' => 'mw-editbutton-signature',
2167 'open' => '--~~~~',
2168 'close' => '',
2169 'sample' => '',
2170 'tip' => wfMsg('sig_tip'),
2171 'key' => 'Y'
2172 ),
2173 array(
2174 'image' => $wgLang->getImageFile('button-hr'),
2175 'id' => 'mw-editbutton-hr',
2176 'open' => "\n----\n",
2177 'close' => '',
2178 'sample' => '',
2179 'tip' => wfMsg('hr_tip'),
2180 'key' => 'R'
2181 )
2182 );
2183 $toolbar = "<div id='toolbar'>\n";
2184
2185 $script = '';
2186 foreach ( $toolarray as $tool ) {
2187 $params = array(
2188 $image = $wgStylePath.'/common/images/'.$tool['image'],
2189 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2190 // Older browsers show a "speedtip" type message only for ALT.
2191 // Ideally these should be different, realistically they
2192 // probably don't need to be.
2193 $tip = $tool['tip'],
2194 $open = $tool['open'],
2195 $close = $tool['close'],
2196 $sample = $tool['sample'],
2197 $cssId = $tool['id'],
2198 );
2199
2200 $paramList = implode( ',',
2201 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2202 $script .= "addButton($paramList);\n";
2203 }
2204 $toolbar .= Html::inlineScript( "\n$script\n" );
2205
2206 $toolbar .= "\n</div>";
2207
2208 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2209
2210 return $toolbar;
2211 }
2212
2213 /**
2214 * Returns an array of html code of the following checkboxes:
2215 * minor and watch
2216 *
2217 * @param $tabindex Current tabindex
2218 * @param $skin Skin object
2219 * @param $checked Array of checkbox => bool, where bool indicates the checked
2220 * status of the checkbox
2221 *
2222 * @return array
2223 */
2224 public function getCheckboxes( &$tabindex, $skin, $checked ) {
2225 global $wgUser;
2226
2227 $checkboxes = array();
2228
2229 $checkboxes['minor'] = '';
2230 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
2231 if ( $wgUser->isAllowed('minoredit') ) {
2232 $attribs = array(
2233 'tabindex' => ++$tabindex,
2234 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2235 'id' => 'wpMinoredit',
2236 );
2237 $checkboxes['minor'] =
2238 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2239 "&nbsp;<label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>";
2240 }
2241
2242 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
2243 $checkboxes['watch'] = '';
2244 if ( $wgUser->isLoggedIn() ) {
2245 $attribs = array(
2246 'tabindex' => ++$tabindex,
2247 'accesskey' => wfMsg( 'accesskey-watch' ),
2248 'id' => 'wpWatchthis',
2249 );
2250 $checkboxes['watch'] =
2251 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2252 "&nbsp;<label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>";
2253 }
2254 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2255 return $checkboxes;
2256 }
2257
2258 /**
2259 * Returns an array of html code of the following buttons:
2260 * save, diff, preview and live
2261 *
2262 * @param $tabindex Current tabindex
2263 *
2264 * @return array
2265 */
2266 public function getEditButtons(&$tabindex) {
2267 global $wgLivePreview, $wgUser;
2268
2269 $buttons = array();
2270
2271 $temp = array(
2272 'id' => 'wpSave',
2273 'name' => 'wpSave',
2274 'type' => 'submit',
2275 'tabindex' => ++$tabindex,
2276 'value' => wfMsg('savearticle'),
2277 'accesskey' => wfMsg('accesskey-save'),
2278 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2279 );
2280 $buttons['save'] = Xml::element('input', $temp, '');
2281
2282 ++$tabindex; // use the same for preview and live preview
2283 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
2284 $this->doLivePreviewScript(); // Add to output
2285
2286 $temp = array(
2287 'id' => 'wpPreview',
2288 'name' => 'wpPreview',
2289 'type' => 'submit',
2290 'tabindex' => $tabindex,
2291 'value' => wfMsg('showpreview'),
2292 'accesskey' => '',
2293 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2294 'style' => 'display: none;',
2295 );
2296 $buttons['preview'] = Xml::element('input', $temp, '');
2297
2298 $temp = array(
2299 'id' => 'wpLivePreview',
2300 'name' => 'wpLivePreview',
2301 'type' => 'submit',
2302 'tabindex' => $tabindex,
2303 'value' => wfMsg('showlivepreview'),
2304 'accesskey' => wfMsg('accesskey-preview'),
2305 'title' => '',
2306 );
2307
2308 $buttons['live'] = Xml::element('input', $temp, '');
2309 } else {
2310 $temp = array(
2311 'id' => 'wpPreview',
2312 'name' => 'wpPreview',
2313 'type' => 'submit',
2314 'tabindex' => $tabindex,
2315 'value' => wfMsg('showpreview'),
2316 'accesskey' => wfMsg('accesskey-preview'),
2317 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2318 );
2319 $buttons['preview'] = Xml::element('input', $temp, '');
2320 $buttons['live'] = '';
2321 }
2322
2323 $temp = array(
2324 'id' => 'wpDiff',
2325 'name' => 'wpDiff',
2326 'type' => 'submit',
2327 'tabindex' => ++$tabindex,
2328 'value' => wfMsg('showdiff'),
2329 'accesskey' => wfMsg('accesskey-diff'),
2330 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2331 );
2332 $buttons['diff'] = Xml::element('input', $temp, '');
2333
2334 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2335 return $buttons;
2336 }
2337
2338
2339 /**
2340 * Get a diff between the current contents of the edit box and the
2341 * version of the page we're editing from.
2342 *
2343 * If this is a section edit, we'll replace the section as for final
2344 * save and then make a comparison.
2345 */
2346 function showDiff() {
2347 $oldtext = $this->mArticle->fetchContent();
2348 $newtext = $this->mArticle->replaceSection(
2349 $this->section, $this->textbox1, $this->summary, $this->edittime );
2350 $newtext = $this->mArticle->preSaveTransform( $newtext );
2351 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2352 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2353 if ( $oldtext !== false || $newtext != '' ) {
2354 $de = new DifferenceEngine( $this->mTitle );
2355 $de->setText( $oldtext, $newtext );
2356 $difftext = $de->getDiff( $oldtitle, $newtitle );
2357 $de->showDiffStyle();
2358 } else {
2359 $difftext = '';
2360 }
2361
2362 global $wgOut;
2363 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2364 }
2365
2366 /**
2367 * Filter an input field through a Unicode de-armoring process if it
2368 * came from an old browser with known broken Unicode editing issues.
2369 *
2370 * @param WebRequest $request
2371 * @param string $field
2372 * @return string
2373 * @private
2374 */
2375 function safeUnicodeInput( $request, $field ) {
2376 $text = rtrim( $request->getText( $field ) );
2377 return $request->getBool( 'safemode' )
2378 ? $this->unmakesafe( $text )
2379 : $text;
2380 }
2381
2382 /**
2383 * Filter an output field through a Unicode armoring process if it is
2384 * going to an old browser with known broken Unicode editing issues.
2385 *
2386 * @param string $text
2387 * @return string
2388 * @private
2389 */
2390 function safeUnicodeOutput( $text ) {
2391 global $wgContLang;
2392 $codedText = $wgContLang->recodeForEdit( $text );
2393 return $this->checkUnicodeCompliantBrowser()
2394 ? $codedText
2395 : $this->makesafe( $codedText );
2396 }
2397
2398 /**
2399 * A number of web browsers are known to corrupt non-ASCII characters
2400 * in a UTF-8 text editing environment. To protect against this,
2401 * detected browsers will be served an armored version of the text,
2402 * with non-ASCII chars converted to numeric HTML character references.
2403 *
2404 * Preexisting such character references will have a 0 added to them
2405 * to ensure that round-trips do not alter the original data.
2406 *
2407 * @param string $invalue
2408 * @return string
2409 * @private
2410 */
2411 function makesafe( $invalue ) {
2412 // Armor existing references for reversability.
2413 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
2414
2415 $bytesleft = 0;
2416 $result = "";
2417 $working = 0;
2418 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2419 $bytevalue = ord( $invalue{$i} );
2420 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2421 $result .= chr( $bytevalue );
2422 $bytesleft = 0;
2423 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2424 $working = $working << 6;
2425 $working += ($bytevalue & 0x3F);
2426 $bytesleft--;
2427 if ( $bytesleft <= 0 ) {
2428 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2429 }
2430 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2431 $working = $bytevalue & 0x1F;
2432 $bytesleft = 1;
2433 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2434 $working = $bytevalue & 0x0F;
2435 $bytesleft = 2;
2436 } else { //1111 0xxx
2437 $working = $bytevalue & 0x07;
2438 $bytesleft = 3;
2439 }
2440 }
2441 return $result;
2442 }
2443
2444 /**
2445 * Reverse the previously applied transliteration of non-ASCII characters
2446 * back to UTF-8. Used to protect data from corruption by broken web browsers
2447 * as listed in $wgBrowserBlackList.
2448 *
2449 * @param string $invalue
2450 * @return string
2451 * @private
2452 */
2453 function unmakesafe( $invalue ) {
2454 $result = "";
2455 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2456 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
2457 $i += 3;
2458 $hexstring = "";
2459 do {
2460 $hexstring .= $invalue{$i};
2461 $i++;
2462 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2463
2464 // Do some sanity checks. These aren't needed for reversability,
2465 // but should help keep the breakage down if the editor
2466 // breaks one of the entities whilst editing.
2467 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2468 $codepoint = hexdec($hexstring);
2469 $result .= codepointToUtf8( $codepoint );
2470 } else {
2471 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2472 }
2473 } else {
2474 $result .= substr( $invalue, $i, 1 );
2475 }
2476 }
2477 // reverse the transform that we made for reversability reasons.
2478 return strtr( $result, array( "&#x0" => "&#x" ) );
2479 }
2480
2481 function noCreatePermission() {
2482 global $wgOut;
2483 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2484 $wgOut->addWikiMsg( 'nocreatetext' );
2485 }
2486
2487 /**
2488 * Attempt submission
2489 * @return bool false if output is done, true if the rest of the form should be displayed
2490 */
2491 function attemptSave() {
2492 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2493
2494 $resultDetails = false;
2495 # Allow bots to exempt some edits from bot flagging
2496 $bot = $wgUser->isAllowed('bot') && $wgRequest->getBool('bot',true);
2497 $value = $this->internalAttemptSave( $resultDetails, $bot );
2498
2499 if ( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) {
2500 $this->didSave = true;
2501 }
2502
2503 switch ($value) {
2504 case self::AS_HOOK_ERROR_EXPECTED:
2505 case self::AS_CONTENT_TOO_BIG:
2506 case self::AS_ARTICLE_WAS_DELETED:
2507 case self::AS_CONFLICT_DETECTED:
2508 case self::AS_SUMMARY_NEEDED:
2509 case self::AS_TEXTBOX_EMPTY:
2510 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
2511 case self::AS_END:
2512 return true;
2513
2514 case self::AS_HOOK_ERROR:
2515 case self::AS_FILTERING:
2516 case self::AS_SUCCESS_NEW_ARTICLE:
2517 case self::AS_SUCCESS_UPDATE:
2518 return false;
2519
2520 case self::AS_SPAM_ERROR:
2521 $this->spamPage ( $resultDetails['spam'] );
2522 return false;
2523
2524 case self::AS_BLOCKED_PAGE_FOR_USER:
2525 $this->blockedPage();
2526 return false;
2527
2528 case self::AS_IMAGE_REDIRECT_ANON:
2529 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2530 return false;
2531
2532 case self::AS_READ_ONLY_PAGE_ANON:
2533 $this->userNotLoggedInPage();
2534 return false;
2535
2536 case self::AS_READ_ONLY_PAGE_LOGGED:
2537 case self::AS_READ_ONLY_PAGE:
2538 $wgOut->readOnlyPage();
2539 return false;
2540
2541 case self::AS_RATE_LIMITED:
2542 $wgOut->rateLimited();
2543 return false;
2544
2545 case self::AS_NO_CREATE_PERMISSION;
2546 $this->noCreatePermission();
2547 return;
2548
2549 case self::AS_BLANK_ARTICLE:
2550 $wgOut->redirect( $wgTitle->getFullURL() );
2551 return false;
2552
2553 case self::AS_IMAGE_REDIRECT_LOGGED:
2554 $wgOut->permissionRequired( 'upload' );
2555 return false;
2556 }
2557 }
2558
2559 function getBaseRevision() {
2560 if ( $this->mBaseRevision == false ) {
2561 $db = wfGetDB( DB_MASTER );
2562 $baseRevision = Revision::loadFromTimestamp(
2563 $db, $this->mTitle, $this->edittime );
2564 return $this->mBaseRevision = $baseRevision;
2565 } else {
2566 return $this->mBaseRevision;
2567 }
2568 }
2569 }