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