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