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