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