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