Replaced all instances of <<<END (which breaks vim syntax highlighting), with a type...
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * Contains the EditPage class
4 * @file
5 */
6
7 /**
8 * The edit page/HTML interface (split from Article)
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
11 * interfaces.
12 *
13 * EditPage cares about two distinct titles:
14 * $wgTitle is the page that forms submit to, links point to,
15 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
16 * page in the database that is actually being edited. These are
17 * usually the same, but they are now allowed to be different.
18 */
19 class EditPage {
20 const AS_SUCCESS_UPDATE = 200;
21 const AS_SUCCESS_NEW_ARTICLE = 201;
22 const AS_HOOK_ERROR = 210;
23 const AS_FILTERING = 211;
24 const AS_HOOK_ERROR_EXPECTED = 212;
25 const AS_BLOCKED_PAGE_FOR_USER = 215;
26 const AS_CONTENT_TOO_BIG = 216;
27 const AS_USER_CANNOT_EDIT = 217;
28 const AS_READ_ONLY_PAGE_ANON = 218;
29 const AS_READ_ONLY_PAGE_LOGGED = 219;
30 const AS_READ_ONLY_PAGE = 220;
31 const AS_RATE_LIMITED = 221;
32 const AS_ARTICLE_WAS_DELETED = 222;
33 const AS_NO_CREATE_PERMISSION = 223;
34 const AS_BLANK_ARTICLE = 224;
35 const AS_CONFLICT_DETECTED = 225;
36 const AS_SUMMARY_NEEDED = 226;
37 const AS_TEXTBOX_EMPTY = 228;
38 const AS_MAX_ARTICLE_SIZE_EXCEEDED = 229;
39 const AS_OK = 230;
40 const AS_END = 231;
41 const AS_SPAM_ERROR = 232;
42 const AS_IMAGE_REDIRECT_ANON = 233;
43 const AS_IMAGE_REDIRECT_LOGGED = 234;
44
45 var $mArticle;
46 var $mTitle;
47 var $action;
48 var $mMetaData = '';
49 var $isConflict = false;
50 var $isCssJsSubpage = false;
51 var $isCssSubpage = false;
52 var $isJsSubpage = false;
53 var $deletedSinceEdit = false;
54 var $formtype;
55 var $firsttime;
56 var $lastDelete;
57 var $mTokenOk = false;
58 var $mTokenOkExceptSuffix = false;
59 var $mTriedSave = false;
60 var $tooBig = false;
61 var $kblength = false;
62 var $missingComment = false;
63 var $missingSummary = false;
64 var $allowBlankSummary = false;
65 var $autoSumm = '';
66 var $hookError = '';
67 #var $mPreviewTemplates;
68 var $mParserOutput;
69 var $mBaseRevision = false;
70 var $mShowSummaryField = true;
71
72 # Form values
73 var $save = false, $preview = false, $diff = false;
74 var $minoredit = false, $watchthis = false, $recreate = false;
75 var $textbox1 = '', $textbox2 = '', $summary = '';
76 var $edittime = '', $section = '', $starttime = '';
77 var $oldid = 0, $editintro = '', $scrolltop = null;
78
79 # Placeholders for text injection by hooks (must be HTML)
80 # extensions should take care to _append_ to the present value
81 public $editFormPageTop; // Before even the preview
82 public $editFormTextTop;
83 public $editFormTextBeforeContent;
84 public $editFormTextAfterWarn;
85 public $editFormTextAfterTools;
86 public $editFormTextBottom;
87 public $editFormTextAfterContent;
88 public $previewTextAfterContent;
89
90 /* $didSave should be set to true whenever an article was succesfully altered. */
91 public $didSave = false;
92 public $undidRev = 0;
93
94 public $suppressIntro = false;
95
96 /**
97 * @todo document
98 * @param $article
99 */
100 function EditPage( $article ) {
101 $this->mArticle =& $article;
102 $this->mTitle = $article->getTitle();
103 $this->action = 'submit';
104
105 # Placeholders for text injection by hooks (empty per default)
106 $this->editFormPageTop =
107 $this->editFormTextTop =
108 $this->editFormTextBeforeContent =
109 $this->editFormTextAfterWarn =
110 $this->editFormTextAfterTools =
111 $this->editFormTextBottom =
112 $this->editFormTextAfterContent =
113 $this->previewTextAfterContent =
114 $this->mPreloadText = "";
115 }
116
117 function getArticle() {
118 return $this->mArticle;
119 }
120
121
122 /**
123 * Fetch initial editing page content.
124 * @private
125 */
126 function getContent( $def_text = '' ) {
127 global $wgOut, $wgRequest, $wgParser, $wgContLang, $wgMessageCache;
128
129 wfProfileIn( __METHOD__ );
130 # Get variables from query string :P
131 $section = $wgRequest->getVal( 'section' );
132 $preload = $wgRequest->getVal( 'preload' );
133 $undoafter = $wgRequest->getVal( 'undoafter' );
134 $undo = $wgRequest->getVal( 'undo' );
135
136 $text = '';
137 // For message page not locally set, use the i18n message.
138 // For other non-existent articles, use preload text if any.
139 if ( !$this->mTitle->exists() ) {
140 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
141 # If this is a system message, get the default text.
142 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
143 $wgMessageCache->loadAllMessages( $lang );
144 $text = wfMsgGetKey( $message, false, $lang, false );
145 if( wfEmptyMsg( $message, $text ) )
146 $text = $this->getPreloadedText( $preload );
147 } else {
148 # If requested, preload some text.
149 $text = $this->getPreloadedText( $preload );
150 }
151 // For existing pages, get text based on "undo" or section parameters.
152 } else {
153 $text = $this->mArticle->getContent();
154 if ( $undo > 0 && $undoafter > 0 && $undo < $undoafter ) {
155 # If they got undoafter and undo round the wrong way, switch them
156 list( $undo, $undoafter ) = array( $undoafter, $undo );
157 }
158 if ( $undo > 0 && $undo > $undoafter ) {
159 # Undoing a specific edit overrides section editing; section-editing
160 # doesn't work with undoing.
161 if ( $undoafter ) {
162 $undorev = Revision::newFromId( $undo );
163 $oldrev = Revision::newFromId( $undoafter );
164 } else {
165 $undorev = Revision::newFromId( $undo );
166 $oldrev = $undorev ? $undorev->getPrevious() : null;
167 }
168
169 # Sanity check, make sure it's the right page,
170 # the revisions exist and they were not deleted.
171 # Otherwise, $text will be left as-is.
172 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
173 $undorev->getPage() == $oldrev->getPage() &&
174 $undorev->getPage() == $this->mArticle->getID() &&
175 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
176 !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
177
178 $undotext = $this->mArticle->getUndoText( $undorev, $oldrev );
179 if ( $undotext === false ) {
180 # Warn the user that something went wrong
181 $this->editFormPageTop .= $wgOut->parse( '<div class="error mw-undo-failure">' . wfMsgNoTrans( 'undo-failure' ) . '</div>' );
182 } else {
183 $text = $undotext;
184 # Inform the user of our success and set an automatic edit summary
185 $this->editFormPageTop .= $wgOut->parse( '<div class="mw-undo-success">' . wfMsgNoTrans( 'undo-success' ) . '</div>' );
186 $firstrev = $oldrev->getNext();
187 # If we just undid one rev, use an autosummary
188 if ( $firstrev->mId == $undo ) {
189 $this->summary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
190 $this->undidRev = $undo;
191 }
192 $this->formtype = 'diff';
193 }
194 } else {
195 // Failed basic sanity checks.
196 // Older revisions may have been removed since the link
197 // was created, or we may simply have got bogus input.
198 $this->editFormPageTop .= $wgOut->parse( '<div class="error mw-undo-norev">' . wfMsgNoTrans( 'undo-norev' ) . '</div>' );
199 }
200 } else if ( $section != '' ) {
201 if ( $section == 'new' ) {
202 $text = $this->getPreloadedText( $preload );
203 } else {
204 $text = $wgParser->getSection( $text, $section, $def_text );
205 }
206 }
207 }
208
209 wfProfileOut( __METHOD__ );
210 return $text;
211 }
212
213 /** Use this method before edit() to preload some text into the edit box */
214 public function setPreloadedText( $text ) {
215 $this->mPreloadText = $text;
216 }
217
218 /**
219 * Get the contents of a page from its title and remove includeonly tags
220 *
221 * @param $preload String: the title of the page.
222 * @return string The contents of the page.
223 */
224 protected function getPreloadedText( $preload ) {
225 if ( !empty( $this->mPreloadText ) ) {
226 return $this->mPreloadText;
227 } elseif ( $preload === '' ) {
228 return '';
229 } else {
230 $preloadTitle = Title::newFromText( $preload );
231 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
232 $rev = Revision::newFromTitle( $preloadTitle );
233 if ( is_object( $rev ) ) {
234 $text = $rev->getText();
235 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
236 // its own mini-parser! -ævar
237 $text = preg_replace( '~</?includeonly>~', '', $text );
238 return $text;
239 } else
240 return '';
241 }
242 }
243 }
244
245 /**
246 * This is the function that extracts metadata from the article body on the first view.
247 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
248 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
249 */
250 function extractMetaDataFromArticle () {
251 global $wgUseMetadataEdit, $wgMetadataWhitelist, $wgContLang;
252 $this->mMetaData = '';
253 if ( !$wgUseMetadataEdit ) return;
254 if ( $wgMetadataWhitelist == '' ) return;
255 $s = '';
256 $t = $this->getContent();
257
258 # MISSING : <nowiki> filtering
259
260 # Categories and language links
261 $t = explode( "\n" , $t );
262 $catlow = strtolower( $wgContLang->getNsText( NS_CATEGORY ) );
263 $cat = $ll = array();
264 foreach ( $t as $key => $x ) {
265 $y = trim( strtolower ( $x ) );
266 while ( substr( $y , 0 , 2 ) == '[[' ) {
267 $y = explode( ']]' , trim ( $x ) );
268 $first = array_shift( $y );
269 $first = explode( ':' , $first );
270 $ns = array_shift( $first );
271 $ns = trim( str_replace( '[' , '' , $ns ) );
272 if ( $wgContLang->getLanguageName( $ns ) || strtolower( $ns ) == $catlow ) {
273 $add = '[[' . $ns . ':' . implode( ':' , $first ) . ']]';
274 if ( strtolower( $ns ) == $catlow ) $cat[] = $add;
275 else $ll[] = $add;
276 $x = implode( ']]', $y );
277 $t[$key] = $x;
278 $y = trim( strtolower( $x ) );
279 } else {
280 $x = implode( ']]' , $y );
281 $y = trim( strtolower( $x ) );
282 }
283 }
284 }
285 if ( count( $cat ) ) $s .= implode( ' ' , $cat ) . "\n";
286 if ( count( $ll ) ) $s .= implode( ' ' , $ll ) . "\n";
287 $t = implode( "\n" , $t );
288
289 # Load whitelist
290 $sat = array () ; # stand-alone-templates; must be lowercase
291 $wl_title = Title::newFromText( $wgMetadataWhitelist );
292 $wl_article = new Article ( $wl_title );
293 $wl = explode ( "\n" , $wl_article->getContent() );
294 foreach ( $wl AS $x ) {
295 $isentry = false;
296 $x = trim ( $x );
297 while ( substr ( $x , 0 , 1 ) == '*' ) {
298 $isentry = true;
299 $x = trim ( substr ( $x , 1 ) );
300 }
301 if ( $isentry ) {
302 $sat[] = strtolower ( $x );
303 }
304
305 }
306
307 # Templates, but only some
308 $t = explode( '{{' , $t );
309 $tl = array() ;
310 foreach ( $t as $key => $x ) {
311 $y = explode( '}}' , $x , 2 );
312 if ( count( $y ) == 2 ) {
313 $z = $y[0];
314 $z = explode( '|' , $z );
315 $tn = array_shift( $z );
316 if ( in_array( strtolower( $tn ) , $sat ) ) {
317 $tl[] = '{{' . $y[0] . '}}';
318 $t[$key] = $y[1];
319 $y = explode( '}}' , $y[1] , 2 );
320 }
321 else $t[$key] = '{{' . $x;
322 }
323 else if ( $key != 0 ) $t[$key] = '{{' . $x;
324 else $t[$key] = $x;
325 }
326 if ( count( $tl ) ) $s .= implode( ' ' , $tl );
327 $t = implode( '' , $t );
328
329 $t = str_replace( "\n\n\n", "\n", $t );
330 $this->mArticle->mContent = $t;
331 $this->mMetaData = $s;
332 }
333
334 /*
335 * Check if a page was deleted while the user was editing it, before submit.
336 * Note that we rely on the logging table, which hasn't been always there,
337 * but that doesn't matter, because this only applies to brand new
338 * deletes.
339 */
340 protected function wasDeletedSinceLastEdit() {
341 if ( $this->deletedSinceEdit )
342 return true;
343 if ( $this->mTitle->isDeletedQuick() ) {
344 $this->lastDelete = $this->getLastDelete();
345 if ( $this->lastDelete ) {
346 $deleteTime = wfTimestamp( TS_MW, $this->lastDelete->log_timestamp );
347 if ( $deleteTime > $this->starttime ) {
348 $this->deletedSinceEdit = true;
349 }
350 }
351 }
352 return $this->deletedSinceEdit;
353 }
354
355 function submit() {
356 $this->edit();
357 }
358
359 /**
360 * This is the function that gets called for "action=edit". It
361 * sets up various member variables, then passes execution to
362 * another function, usually showEditForm()
363 *
364 * The edit form is self-submitting, so that when things like
365 * preview and edit conflicts occur, we get the same form back
366 * with the extra stuff added. Only when the final submission
367 * is made and all is well do we actually save and redirect to
368 * the newly-edited page.
369 */
370 function edit() {
371 global $wgOut, $wgRequest;
372 // Allow extensions to modify/prevent this form or submission
373 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
374 return;
375 }
376
377 wfProfileIn( __METHOD__ );
378 wfDebug( __METHOD__.": enter\n" );
379
380 // This is not an article
381 $wgOut->setArticleFlag( false );
382
383 $this->importFormData( $wgRequest );
384 $this->firsttime = false;
385
386 if ( $this->live ) {
387 $this->livePreview();
388 wfProfileOut( __METHOD__ );
389 return;
390 }
391
392 if ( wfReadOnly() && $this->save ) {
393 // Force preview
394 $this->save = false;
395 $this->preview = true;
396 }
397
398 $wgOut->addScriptFile( 'edit.js' );
399
400 $permErrors = $this->getEditPermissionErrors();
401 if ( $permErrors ) {
402 wfDebug( __METHOD__ . ": User can't edit\n" );
403 $this->readOnlyPage( $this->getContent(), true, $permErrors, 'edit' );
404 wfProfileOut( __METHOD__ );
405 return;
406 } else {
407 if ( $this->save ) {
408 $this->formtype = 'save';
409 } else if ( $this->preview ) {
410 $this->formtype = 'preview';
411 } else if ( $this->diff ) {
412 $this->formtype = 'diff';
413 } else { # First time through
414 $this->firsttime = true;
415 if ( $this->previewOnOpen() ) {
416 $this->formtype = 'preview';
417 } else {
418 $this->extractMetaDataFromArticle () ;
419 $this->formtype = 'initial';
420 }
421 }
422 }
423
424 // If they used redlink=1 and the page exists, redirect to the main article
425 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle->exists() ) {
426 $wgOut->redirect( $this->mTitle->getFullURL() );
427 }
428
429 wfProfileIn( __METHOD__."-business-end" );
430
431 $this->isConflict = false;
432 // css / js subpages of user pages get a special treatment
433 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
434 $this->isCssSubpage = $this->mTitle->isCssSubpage();
435 $this->isJsSubpage = $this->mTitle->isJsSubpage();
436 $this->isValidCssJsSubpage = $this->mTitle->isValidCssJsSubpage();
437
438 # Show applicable editing introductions
439 if ( $this->formtype == 'initial' || $this->firsttime )
440 $this->showIntro();
441
442 if ( $this->mTitle->isTalkPage() ) {
443 $wgOut->addWikiMsg( 'talkpagetext' );
444 }
445
446 # Optional notices on a per-namespace and per-page basis
447 $editnotice_ns = 'editnotice-'.$this->mTitle->getNamespace();
448 if ( !wfEmptyMsg( $editnotice_ns, wfMsgForContent( $editnotice_ns ) ) ) {
449 $wgOut->addWikiText( wfMsgForContent( $editnotice_ns ) );
450 }
451 if ( MWNamespace::hasSubpages( $this->mTitle->getNamespace() ) ) {
452 $parts = explode( '/', $this->mTitle->getDBkey() );
453 $editnotice_base = $editnotice_ns;
454 while ( count( $parts ) > 0 ) {
455 $editnotice_base .= '-'.array_shift( $parts );
456 if ( !wfEmptyMsg( $editnotice_base, wfMsgForContent( $editnotice_base ) ) ) {
457 $wgOut->addWikiText( wfMsgForContent( $editnotice_base ) );
458 }
459 }
460 }
461
462 # Attempt submission here. This will check for edit conflicts,
463 # and redundantly check for locked database, blocked IPs, etc.
464 # that edit() already checked just in case someone tries to sneak
465 # in the back door with a hand-edited submission URL.
466
467 if ( 'save' == $this->formtype ) {
468 if ( !$this->attemptSave() ) {
469 wfProfileOut( __METHOD__."-business-end" );
470 wfProfileOut( __METHOD__ );
471 return;
472 }
473 }
474
475 # First time through: get contents, set time for conflict
476 # checking, etc.
477 if ( 'initial' == $this->formtype || $this->firsttime ) {
478 if ( $this->initialiseForm() === false ) {
479 $this->noSuchSectionPage();
480 wfProfileOut( __METHOD__."-business-end" );
481 wfProfileOut( __METHOD__ );
482 return;
483 }
484 if ( !$this->mTitle->getArticleId() )
485 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
486 }
487
488 $this->showEditForm();
489 wfProfileOut( __METHOD__."-business-end" );
490 wfProfileOut( __METHOD__ );
491 }
492
493 protected function getEditPermissionErrors() {
494 global $wgUser;
495 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
496 # Can this title be created?
497 if ( !$this->mTitle->exists() ) {
498 $permErrors = array_merge( $permErrors,
499 wfArrayDiff2( $this->mTitle->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
500 }
501 # Ignore some permissions errors when a user is just previewing/viewing diffs
502 $remove = array();
503 foreach( $permErrors as $error ) {
504 if ( ( $this->preview || $this->diff ) &&
505 ( $error[0] == 'blockedtext' || $error[0] == 'autoblockedtext' ) )
506 {
507 $remove[] = $error;
508 }
509 }
510 $permErrors = wfArrayDiff2( $permErrors, $remove );
511 return $permErrors;
512 }
513
514 /**
515 * Show a read-only error
516 * Parameters are the same as OutputPage:readOnlyPage()
517 * Redirect to the article page if redlink=1
518 */
519 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
520 global $wgRequest, $wgOut;
521 if ( $wgRequest->getBool( 'redlink' ) ) {
522 // The edit page was reached via a red link.
523 // Redirect to the article page and let them click the edit tab if
524 // they really want a permission error.
525 $wgOut->redirect( $this->mTitle->getFullUrl() );
526 } else {
527 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
528 }
529 }
530
531 /**
532 * Should we show a preview when the edit form is first shown?
533 *
534 * @return bool
535 */
536 protected function previewOnOpen() {
537 global $wgRequest, $wgUser;
538 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
539 // Explicit override from request
540 return true;
541 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
542 // Explicit override from request
543 return false;
544 } elseif ( $this->section == 'new' ) {
545 // Nothing *to* preview for new sections
546 return false;
547 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null || $this->mTitle->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
548 // Standard preference behaviour
549 return true;
550 } elseif ( !$this->mTitle->exists() && $this->mTitle->getNamespace() == NS_CATEGORY ) {
551 // Categories are special
552 return true;
553 } else {
554 return false;
555 }
556 }
557
558 /**
559 * Does this EditPage class support section editing?
560 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
561 *
562 * @return bool
563 */
564 protected function isSectionEditSupported() {
565 return true;
566 }
567
568 /**
569 * Returns the URL to use in the form's action attribute.
570 * This is used by EditPage subclasses when simply customizing the action
571 * variable in the constructor is not enough. This can be used when the
572 * EditPage lives inside of a Special page rather than a custom page action.
573 *
574 * @param Title $title The title for which is being edited (where we go to for &action= links)
575 * @return string
576 */
577 protected function getActionURL( Title $title ) {
578 return $title->getLocalURL( array( 'action' => $this->action ) );
579 }
580
581 /**
582 * @todo document
583 * @param $request
584 */
585 function importFormData( &$request ) {
586 global $wgLang, $wgUser;
587
588 wfProfileIn( __METHOD__ );
589
590 # Section edit can come from either the form or a link
591 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
592
593 if ( $request->wasPosted() ) {
594 # These fields need to be checked for encoding.
595 # Also remove trailing whitespace, but don't remove _initial_
596 # whitespace from the text boxes. This may be significant formatting.
597 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
598 if ( !$request->getCheck('wpTextbox2') ) {
599 // Skip this if wpTextbox2 has input, it indicates that we came
600 // from a conflict page with raw page text, not a custom form
601 // modified by subclasses
602 wfProfileIn( get_class($this)."::importContentFormData" );
603 $textbox1 = $this->importContentFormData( $request );
604 if ( isset($textbox1) )
605 $this->textbox1 = $textbox1;
606 wfProfileOut( get_class($this)."::importContentFormData" );
607 }
608 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
609 # Truncate for whole multibyte characters. +5 bytes for ellipsis
610 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250, '' );
611
612 # Remove extra headings from summaries and new sections.
613 $this->summary = preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary);
614
615 $this->edittime = $request->getVal( 'wpEdittime' );
616 $this->starttime = $request->getVal( 'wpStarttime' );
617
618 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
619
620 if ( is_null( $this->edittime ) ) {
621 # If the form is incomplete, force to preview.
622 wfDebug( __METHOD__ . ": Form data appears to be incomplete\n" );
623 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
624 $this->preview = true;
625 } else {
626 /* Fallback for live preview */
627 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
628 $this->diff = $request->getCheck( 'wpDiff' );
629
630 // Remember whether a save was requested, so we can indicate
631 // if we forced preview due to session failure.
632 $this->mTriedSave = !$this->preview;
633
634 if ( $this->tokenOk( $request ) ) {
635 # Some browsers will not report any submit button
636 # if the user hits enter in the comment box.
637 # The unmarked state will be assumed to be a save,
638 # if the form seems otherwise complete.
639 wfDebug( __METHOD__ . ": Passed token check.\n" );
640 } else if ( $this->diff ) {
641 # Failed token check, but only requested "Show Changes".
642 wfDebug( __METHOD__ . ": Failed token check; Show Changes requested.\n" );
643 } else {
644 # Page might be a hack attempt posted from
645 # an external site. Preview instead of saving.
646 wfDebug( __METHOD__ . ": Failed token check; forcing preview\n" );
647 $this->preview = true;
648 }
649 }
650 $this->save = !$this->preview && !$this->diff;
651 if ( !preg_match( '/^\d{14}$/', $this->edittime ) ) {
652 $this->edittime = null;
653 }
654
655 if ( !preg_match( '/^\d{14}$/', $this->starttime ) ) {
656 $this->starttime = null;
657 }
658
659 $this->recreate = $request->getCheck( 'wpRecreate' );
660
661 $this->minoredit = $request->getCheck( 'wpMinoredit' );
662 $this->watchthis = $request->getCheck( 'wpWatchthis' );
663
664 # Don't force edit summaries when a user is editing their own user or talk page
665 if ( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) &&
666 $this->mTitle->getText() == $wgUser->getName() )
667 {
668 $this->allowBlankSummary = true;
669 } else {
670 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' ) || !$wgUser->getOption( 'forceeditsummary');
671 }
672
673 $this->autoSumm = $request->getText( 'wpAutoSummary' );
674 } else {
675 # Not a posted form? Start with nothing.
676 wfDebug( __METHOD__ . ": Not a posted form.\n" );
677 $this->textbox1 = '';
678 $this->mMetaData = '';
679 $this->summary = '';
680 $this->edittime = '';
681 $this->starttime = wfTimestampNow();
682 $this->edit = false;
683 $this->preview = false;
684 $this->save = false;
685 $this->diff = false;
686 $this->minoredit = false;
687 $this->watchthis = false;
688 $this->recreate = false;
689
690 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
691 $this->summary = $request->getVal( 'preloadtitle' );
692 }
693 elseif ( $this->section != 'new' && $request->getVal( 'summary' ) ) {
694 $this->summary = $request->getText( 'summary' );
695 }
696
697 if ( $request->getVal( 'minor' ) ) {
698 $this->minoredit = true;
699 }
700 }
701
702 // FIXME: unused variable?
703 $this->oldid = $request->getInt( 'oldid' );
704
705 $this->live = $request->getCheck( 'live' );
706 $this->editintro = $request->getText( 'editintro' );
707
708 wfProfileOut( __METHOD__ );
709
710 // Allow extensions to modify form data
711 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
712 }
713
714 /**
715 * Subpage overridable method for extracting the page content data from the
716 * posted form to be placed in $this->textbox1, if using customized input
717 * this method should be overrided and return the page text that will be used
718 * for saving, preview parsing and so on...
719 *
720 * @praram WebRequest $request
721 */
722 protected function importContentFormData( &$request ) {
723 return; // Don't do anything, EditPage already extracted wpTextbox1
724 }
725
726 /**
727 * Make sure the form isn't faking a user's credentials.
728 *
729 * @param $request WebRequest
730 * @return bool
731 * @private
732 */
733 function tokenOk( &$request ) {
734 global $wgUser;
735 $token = $request->getVal( 'wpEditToken' );
736 $this->mTokenOk = $wgUser->matchEditToken( $token );
737 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
738 return $this->mTokenOk;
739 }
740
741 /**
742 * Show all applicable editing introductions
743 */
744 protected function showIntro() {
745 global $wgOut, $wgUser;
746 if ( $this->suppressIntro ) {
747 return;
748 }
749
750 $namespace = $this->mTitle->getNamespace();
751
752 if ( $namespace == NS_MEDIAWIKI ) {
753 # Show a warning if editing an interface message
754 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1</div>", 'editinginterface' );
755 }
756
757 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
758 if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
759 $parts = explode( '/', $this->mTitle->getText(), 2 );
760 $username = $parts[0];
761 $id = User::idFromName( $username );
762 $ip = User::isIP( $username );
763 if ( $id == 0 && !$ip ) {
764 $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>',
765 array( 'userpage-userdoesnotexist', $username ) );
766 }
767 }
768 # Try to add a custom edit intro, or use the standard one if this is not possible.
769 if ( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
770 if ( $wgUser->isLoggedIn() ) {
771 $wgOut->wrapWikiMsg( '<div class="mw-newarticletext">$1</div>', 'newarticletext' );
772 } else {
773 $wgOut->wrapWikiMsg( '<div class="mw-newarticletextanon">$1</div>', 'newarticletextanon' );
774 }
775 }
776 # Give a notice if the user is editing a deleted/moved page...
777 if ( !$this->mTitle->exists() ) {
778 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle->getPrefixedText(),
779 '', array( 'lim' => 10,
780 'conds' => array( "log_action != 'revision'" ),
781 'showIfEmpty' => false,
782 'msgKey' => array( 'recreate-moveddeleted-warn') )
783 );
784 }
785 }
786
787 /**
788 * Attempt to show a custom editing introduction, if supplied
789 *
790 * @return bool
791 */
792 protected function showCustomIntro() {
793 if ( $this->editintro ) {
794 $title = Title::newFromText( $this->editintro );
795 if ( $title instanceof Title && $title->exists() && $title->userCanRead() ) {
796 global $wgOut;
797 $revision = Revision::newFromTitle( $title );
798 $wgOut->addWikiTextTitleTidy( $revision->getText(), $this->mTitle );
799 return true;
800 } else {
801 return false;
802 }
803 } else {
804 return false;
805 }
806 }
807
808 /**
809 * Attempt submission (no UI)
810 * @return one of the constants describing the result
811 */
812 function internalAttemptSave( &$result, $bot = false ) {
813 global $wgFilterCallback, $wgUser, $wgOut, $wgParser;
814 global $wgMaxArticleSize;
815
816 wfProfileIn( __METHOD__ );
817 wfProfileIn( __METHOD__ . '-checks' );
818
819 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) )
820 {
821 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
822 return self::AS_HOOK_ERROR;
823 }
824
825 # Check image redirect
826 if ( $this->mTitle->getNamespace() == NS_FILE &&
827 Title::newFromRedirect( $this->textbox1 ) instanceof Title &&
828 !$wgUser->isAllowed( 'upload' ) ) {
829 if ( $wgUser->isAnon() ) {
830 return self::AS_IMAGE_REDIRECT_ANON;
831 } else {
832 return self::AS_IMAGE_REDIRECT_LOGGED;
833 }
834 }
835
836 # Reintegrate metadata
837 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
838 $this->mMetaData = '' ;
839
840 # Check for spam
841 $match = self::matchSummarySpamRegex( $this->summary );
842 if ( $match === false ) {
843 $match = self::matchSpamRegex( $this->textbox1 );
844 }
845 if ( $match !== false ) {
846 $result['spam'] = $match;
847 $ip = wfGetIP();
848 $pdbk = $this->mTitle->getPrefixedDBkey();
849 $match = str_replace( "\n", '', $match );
850 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
851 wfProfileOut( __METHOD__ . '-checks' );
852 wfProfileOut( __METHOD__ );
853 return self::AS_SPAM_ERROR;
854 }
855 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section, $this->hookError, $this->summary ) ) {
856 # Error messages or other handling should be performed by the filter function
857 wfProfileOut( __METHOD__ . '-checks' );
858 wfProfileOut( __METHOD__ );
859 return self::AS_FILTERING;
860 }
861 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) ) ) {
862 # Error messages etc. could be handled within the hook...
863 wfProfileOut( __METHOD__ . '-checks' );
864 wfProfileOut( __METHOD__ );
865 return self::AS_HOOK_ERROR;
866 } elseif ( $this->hookError != '' ) {
867 # ...or the hook could be expecting us to produce an error
868 wfProfileOut( __METHOD__ . '-checks' );
869 wfProfileOut( __METHOD__ );
870 return self::AS_HOOK_ERROR_EXPECTED;
871 }
872 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
873 # Check block state against master, thus 'false'.
874 wfProfileOut( __METHOD__ . '-checks' );
875 wfProfileOut( __METHOD__ );
876 return self::AS_BLOCKED_PAGE_FOR_USER;
877 }
878 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
879 if ( $this->kblength > $wgMaxArticleSize ) {
880 // Error will be displayed by showEditForm()
881 $this->tooBig = true;
882 wfProfileOut( __METHOD__ . '-checks' );
883 wfProfileOut( __METHOD__ );
884 return self::AS_CONTENT_TOO_BIG;
885 }
886
887 if ( !$wgUser->isAllowed( 'edit' ) ) {
888 if ( $wgUser->isAnon() ) {
889 wfProfileOut( __METHOD__ . '-checks' );
890 wfProfileOut( __METHOD__ );
891 return self::AS_READ_ONLY_PAGE_ANON;
892 } else {
893 wfProfileOut( __METHOD__ . '-checks' );
894 wfProfileOut( __METHOD__ );
895 return self::AS_READ_ONLY_PAGE_LOGGED;
896 }
897 }
898
899 if ( wfReadOnly() ) {
900 wfProfileOut( __METHOD__ . '-checks' );
901 wfProfileOut( __METHOD__ );
902 return self::AS_READ_ONLY_PAGE;
903 }
904 if ( $wgUser->pingLimiter() ) {
905 wfProfileOut( __METHOD__ . '-checks' );
906 wfProfileOut( __METHOD__ );
907 return self::AS_RATE_LIMITED;
908 }
909
910 # If the article has been deleted while editing, don't save it without
911 # confirmation
912 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
913 wfProfileOut( __METHOD__ . '-checks' );
914 wfProfileOut( __METHOD__ );
915 return self::AS_ARTICLE_WAS_DELETED;
916 }
917
918 wfProfileOut( __METHOD__ . '-checks' );
919
920 # If article is new, insert it.
921 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
922 if ( 0 == $aid ) {
923 // Late check for create permission, just in case *PARANOIA*
924 if ( !$this->mTitle->userCan( 'create' ) ) {
925 wfDebug( __METHOD__ . ": no create permission\n" );
926 wfProfileOut( __METHOD__ );
927 return self::AS_NO_CREATE_PERMISSION;
928 }
929
930 # Don't save a new article if it's blank.
931 if ( '' == $this->textbox1 ) {
932 wfProfileOut( __METHOD__ );
933 return self::AS_BLANK_ARTICLE;
934 }
935
936 // Run post-section-merge edit filter
937 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1, &$this->hookError, $this->summary ) ) ) {
938 # Error messages etc. could be handled within the hook...
939 wfProfileOut( __METHOD__ );
940 return self::AS_HOOK_ERROR;
941 } elseif ( $this->hookError != '' ) {
942 # ...or the hook could be expecting us to produce an error
943 wfProfileOut( __METHOD__ );
944 return self::AS_HOOK_ERROR_EXPECTED;
945 }
946
947 # Handle the user preference to force summaries here. Check if it's not a redirect.
948 if ( !$this->allowBlankSummary && !Title::newFromRedirect( $this->textbox1 ) ) {
949 if ( md5( $this->summary ) == $this->autoSumm ) {
950 $this->missingSummary = true;
951 wfProfileOut( __METHOD__ );
952 return self::AS_SUMMARY_NEEDED;
953 }
954 }
955
956 $isComment = ( $this->section == 'new' );
957
958 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
959 $this->minoredit, $this->watchthis, false, $isComment, $bot );
960
961 wfProfileOut( __METHOD__ );
962 return self::AS_SUCCESS_NEW_ARTICLE;
963 }
964
965 # Article exists. Check for edit conflict.
966
967 $this->mArticle->clear(); # Force reload of dates, etc.
968 $this->mArticle->forUpdate( true ); # Lock the article
969
970 wfDebug( "timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n" );
971
972 if ( $this->mArticle->getTimestamp() != $this->edittime ) {
973 $this->isConflict = true;
974 if ( $this->section == 'new' ) {
975 if ( $this->mArticle->getUserText() == $wgUser->getName() &&
976 $this->mArticle->getComment() == $this->summary ) {
977 // Probably a duplicate submission of a new comment.
978 // This can happen when squid resends a request after
979 // a timeout but the first one actually went through.
980 wfDebug( __METHOD__ . ": duplicate new section submission; trigger edit conflict!\n" );
981 } else {
982 // New comment; suppress conflict.
983 $this->isConflict = false;
984 wfDebug( __METHOD__ .": conflict suppressed; new section\n" );
985 }
986 }
987 }
988 $userid = $wgUser->getId();
989
990 # Suppress edit conflict with self, except for section edits where merging is required.
991 if ( $this->isConflict && $this->section == '' && $this->userWasLastToEdit( $userid, $this->edittime ) ) {
992 wfDebug( __METHOD__ . ": Suppressing edit conflict, same user.\n" );
993 $this->isConflict = false;
994 }
995
996 if ( $this->isConflict ) {
997 wfDebug( __METHOD__ . ": conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
998 $this->mArticle->getTimestamp() . "')\n" );
999 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime );
1000 } else {
1001 wfDebug( __METHOD__ . ": getting section '$this->section'\n" );
1002 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary );
1003 }
1004 if ( is_null( $text ) ) {
1005 wfDebug( __METHOD__ . ": activating conflict; section replace failed.\n" );
1006 $this->isConflict = true;
1007 $text = $this->textbox1; // do not try to merge here!
1008 } else if ( $this->isConflict ) {
1009 # Attempt merge
1010 if ( $this->mergeChangesInto( $text ) ) {
1011 // Successful merge! Maybe we should tell the user the good news?
1012 $this->isConflict = false;
1013 wfDebug( __METHOD__ . ": Suppressing edit conflict, successful merge.\n" );
1014 } else {
1015 $this->section = '';
1016 $this->textbox1 = $text;
1017 wfDebug( __METHOD__ . ": Keeping edit conflict, failed merge.\n" );
1018 }
1019 }
1020
1021 if ( $this->isConflict ) {
1022 wfProfileOut( __METHOD__ );
1023 return self::AS_CONFLICT_DETECTED;
1024 }
1025
1026 $oldtext = $this->mArticle->getContent();
1027
1028 // Run post-section-merge edit filter
1029 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError, $this->summary ) ) ) {
1030 # Error messages etc. could be handled within the hook...
1031 wfProfileOut( __METHOD__ );
1032 return self::AS_HOOK_ERROR;
1033 } elseif ( $this->hookError != '' ) {
1034 # ...or the hook could be expecting us to produce an error
1035 wfProfileOut( __METHOD__ );
1036 return self::AS_HOOK_ERROR_EXPECTED;
1037 }
1038
1039 # Handle the user preference to force summaries here, but not for null edits
1040 if ( $this->section != 'new' && !$this->allowBlankSummary && 0 != strcmp( $oldtext, $text )
1041 && !Title::newFromRedirect( $text ) ) # check if it's not a redirect
1042 {
1043 if ( md5( $this->summary ) == $this->autoSumm ) {
1044 $this->missingSummary = true;
1045 wfProfileOut( __METHOD__ );
1046 return self::AS_SUMMARY_NEEDED;
1047 }
1048 }
1049
1050 # And a similar thing for new sections
1051 if ( $this->section == 'new' && !$this->allowBlankSummary ) {
1052 if ( trim( $this->summary ) == '' ) {
1053 $this->missingSummary = true;
1054 wfProfileOut( __METHOD__ );
1055 return self::AS_SUMMARY_NEEDED;
1056 }
1057 }
1058
1059 # All's well
1060 wfProfileIn( __METHOD__ . '-sectionanchor' );
1061 $sectionanchor = '';
1062 if ( $this->section == 'new' ) {
1063 if ( $this->textbox1 == '' ) {
1064 $this->missingComment = true;
1065 wfProfileOut( __METHOD__ . '-sectionanchor' );
1066 wfProfileOut( __METHOD__ );
1067 return self::AS_TEXTBOX_EMPTY;
1068 }
1069 if ( $this->summary != '' ) {
1070 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary );
1071 # This is a new section, so create a link to the new section
1072 # in the revision summary.
1073 $cleanSummary = $wgParser->stripSectionName( $this->summary );
1074 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
1075 }
1076 } elseif ( $this->section != '' ) {
1077 # Try to get a section anchor from the section source, redirect to edited section if header found
1078 # XXX: might be better to integrate this into Article::replaceSection
1079 # for duplicate heading checking and maybe parsing
1080 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
1081 # we can't deal with anchors, includes, html etc in the header for now,
1082 # headline would need to be parsed to improve this
1083 if ( $hasmatch and strlen( $matches[2] ) > 0 ) {
1084 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
1085 }
1086 }
1087 wfProfileOut( __METHOD__ . '-sectionanchor' );
1088
1089 // Save errors may fall down to the edit form, but we've now
1090 // merged the section into full text. Clear the section field
1091 // so that later submission of conflict forms won't try to
1092 // replace that into a duplicated mess.
1093 $this->textbox1 = $text;
1094 $this->section = '';
1095
1096 // Check for length errors again now that the section is merged in
1097 $this->kblength = (int)( strlen( $text ) / 1024 );
1098 if ( $this->kblength > $wgMaxArticleSize ) {
1099 $this->tooBig = true;
1100 wfProfileOut( __METHOD__ );
1101 return self::AS_MAX_ARTICLE_SIZE_EXCEEDED;
1102 }
1103
1104 # update the article here
1105 if ( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
1106 $this->watchthis, $bot, $sectionanchor ) )
1107 {
1108 wfProfileOut( __METHOD__ );
1109 return self::AS_SUCCESS_UPDATE;
1110 } else {
1111 $this->isConflict = true;
1112 }
1113 wfProfileOut( __METHOD__ );
1114 return self::AS_END;
1115 }
1116
1117 /**
1118 * Check if no edits were made by other users since
1119 * the time a user started editing the page. Limit to
1120 * 50 revisions for the sake of performance.
1121 */
1122 protected function userWasLastToEdit( $id, $edittime ) {
1123 if( !$id ) return false;
1124 $dbw = wfGetDB( DB_MASTER );
1125 $res = $dbw->select( 'revision',
1126 'rev_user',
1127 array(
1128 'rev_page' => $this->mArticle->getId(),
1129 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1130 ),
1131 __METHOD__,
1132 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1133 while( $row = $res->fetchObject() ) {
1134 if( $row->rev_user != $id ) {
1135 return false;
1136 }
1137 }
1138 return true;
1139 }
1140
1141 /**
1142 * Check given input text against $wgSpamRegex, and return the text of the first match.
1143 * @return mixed -- matching string or false
1144 */
1145 public static function matchSpamRegex( $text ) {
1146 global $wgSpamRegex;
1147 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1148 $regexes = (array)$wgSpamRegex;
1149 return self::matchSpamRegexInternal( $text, $regexes );
1150 }
1151
1152 /**
1153 * Check given input text against $wgSpamRegex, and return the text of the first match.
1154 * @return mixed -- matching string or false
1155 */
1156 public static function matchSummarySpamRegex( $text ) {
1157 global $wgSummarySpamRegex;
1158 $regexes = (array)$wgSummarySpamRegex;
1159 return self::matchSpamRegexInternal( $text, $regexes );
1160 }
1161
1162 protected static function matchSpamRegexInternal( $text, $regexes ) {
1163 foreach( $regexes as $regex ) {
1164 $matches = array();
1165 if( preg_match( $regex, $text, $matches ) ) {
1166 return $matches[0];
1167 }
1168 }
1169 return false;
1170 }
1171
1172 /**
1173 * Initialise form fields in the object
1174 * Called on the first invocation, e.g. when a user clicks an edit link
1175 */
1176 function initialiseForm() {
1177 $this->edittime = $this->mArticle->getTimestamp();
1178 $this->textbox1 = $this->getContent( false );
1179 if ( $this->textbox1 === false ) return false;
1180 wfProxyCheck();
1181 return true;
1182 }
1183
1184 function setHeaders() {
1185 global $wgOut, $wgTitle;
1186 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1187 if ( $this->formtype == 'preview' ) {
1188 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1189 }
1190 if ( $this->isConflict ) {
1191 $wgOut->setPageTitle( wfMsg( 'editconflict', $wgTitle->getPrefixedText() ) );
1192 } elseif ( $this->section != '' ) {
1193 $msg = $this->section == 'new' ? 'editingcomment' : 'editingsection';
1194 $wgOut->setPageTitle( wfMsg( $msg, $wgTitle->getPrefixedText() ) );
1195 } else {
1196 # Use the title defined by DISPLAYTITLE magic word when present
1197 if ( isset( $this->mParserOutput )
1198 && ( $dt = $this->mParserOutput->getDisplayTitle() ) !== false ) {
1199 $title = $dt;
1200 } else {
1201 $title = $wgTitle->getPrefixedText();
1202 }
1203 $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
1204 }
1205 }
1206
1207 /**
1208 * Send the edit form and related headers to $wgOut
1209 * @param $formCallback Optional callable that takes an OutputPage
1210 * parameter; will be called during form output
1211 * near the top, for captchas and the like.
1212 */
1213 function showEditForm( $formCallback=null ) {
1214 global $wgOut, $wgUser, $wgTitle, $wgRequest;
1215
1216 # If $wgTitle is null, that means we're in API mode.
1217 # Some hook probably called this function without checking
1218 # for is_null($wgTitle) first. Bail out right here so we don't
1219 # do lots of work just to discard it right after.
1220 if ( is_null( $wgTitle ) )
1221 return;
1222
1223 wfProfileIn( __METHOD__ );
1224
1225 $sk = $wgUser->getSkin();
1226
1227 #need to parse the preview early so that we know which templates are used,
1228 #otherwise users with "show preview after edit box" will get a blank list
1229 #we parse this near the beginning so that setHeaders can do the title
1230 #setting work instead of leaving it in getPreviewText
1231 $previewOutput = '';
1232 if ( $this->formtype == 'preview' ) {
1233 $previewOutput = $this->getPreviewText();
1234 }
1235
1236 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1237
1238 $this->setHeaders();
1239
1240 # Enabled article-related sidebar, toplinks, etc.
1241 $wgOut->setArticleRelated( true );
1242
1243 if ( $this->editFormHeadInit() === false )
1244 return;
1245
1246 $action = htmlspecialchars($this->getActionURL($wgTitle));
1247
1248 if ( $wgUser->getOption( 'showtoolbar' ) and !$this->isCssJsSubpage ) {
1249 # prepare toolbar for edit buttons
1250 $toolbar = EditPage::getEditToolbar();
1251 } else {
1252 $toolbar = '';
1253 }
1254
1255
1256 // activate checkboxes if user wants them to be always active
1257 if ( !$this->preview && !$this->diff ) {
1258 # Sort out the "watch" checkbox
1259 if ( $wgUser->getOption( 'watchdefault' ) ) {
1260 # Watch all edits
1261 $this->watchthis = true;
1262 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1263 # Watch creations
1264 $this->watchthis = true;
1265 } elseif ( $this->mTitle->userIsWatching() ) {
1266 # Already watched
1267 $this->watchthis = true;
1268 }
1269
1270 # May be overriden by request parameters
1271 if( $wgRequest->getBool( 'watchthis' ) ) {
1272 $this->watchthis = true;
1273 }
1274
1275 if ( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1276 }
1277
1278 $wgOut->addHTML( $this->editFormPageTop );
1279
1280 if ( $wgUser->getOption( 'previewontop' ) ) {
1281 $this->displayPreviewArea( $previewOutput, true );
1282 }
1283
1284 $wgOut->addHTML( $this->editFormTextTop );
1285
1286 $templates = $this->getTemplates();
1287 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1288
1289 $hiddencats = $this->mArticle->getHiddenCategories();
1290 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1291
1292 if ( $this->wasDeletedSinceLastEdit() && 'save' != $this->formtype ) {
1293 $wgOut->wrapWikiMsg(
1294 "<div class='error mw-deleted-while-editing'>\n$1</div>",
1295 'deletedwhileediting' );
1296 } elseif ( $this->wasDeletedSinceLastEdit() ) {
1297 // Hide the toolbar and edit area, user can click preview to get it back
1298 // Add an confirmation checkbox and explanation.
1299 $toolbar = '';
1300 // @todo move this to a cleaner conditional instead of blanking a variable
1301 }
1302 $wgOut->addHTML( <<<HTML
1303 {$toolbar}
1304 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1305 HTML
1306 );
1307
1308 if ( is_callable( $formCallback ) ) {
1309 call_user_func_array( $formCallback, array( &$wgOut ) );
1310 }
1311
1312 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1313
1314 // Put these up at the top to ensure they aren't lost on early form submission
1315 $this->showFormBeforeText();
1316
1317 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype ) {
1318 $wgOut->addHTML(
1319 '<div class="mw-confirm-recreate">' .
1320 $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ) ) .
1321 Xml::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1322 array( 'title' => $sk->titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1323 ) .
1324 '</div>'
1325 );
1326 }
1327
1328 # If a blank edit summary was previously provided, and the appropriate
1329 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1330 # user being bounced back more than once in the event that a summary
1331 # is not required.
1332 #####
1333 # For a bit more sophisticated detection of blank summaries, hash the
1334 # automatic one and pass that in the hidden field wpAutoSummary.
1335 if ( $this->missingSummary ||
1336 ( $this->section == 'new' && $wgRequest->getBool( 'nosummary' ) ) )
1337 $wgOut->addHTML( Xml::hidden( 'wpIgnoreBlankSummary', true ) );
1338 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1339 $wgOut->addHTML( Xml::hidden( 'wpAutoSummary', $autosumm ) );
1340
1341 if ( $this->section == 'new' ) {
1342 $this->showSummaryInput( true, $this->summary );
1343 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary ) );
1344 }
1345
1346 $wgOut->addHTML( $this->editFormTextBeforeContent );
1347
1348 if ( $this->isConflict ) {
1349 // In an edit conflict bypass the overrideable content form method
1350 // and fallback to the raw wpTextbox1 since editconflicts can't be
1351 // resolved between page source edits and custom ui edits using the
1352 // custom edit ui.
1353 $this->showTextbox1();
1354 } else {
1355 $this->showContentForm();
1356 }
1357
1358 $wgOut->addHTML( $this->editFormTextAfterContent );
1359
1360 $wgOut->addWikiText( $this->getCopywarn() );
1361 if ( isset($this->editFormTextAfterWarn) && $this->editFormTextAfterWarn !== '' )
1362 $wgOut->addHTML( $this->editFormTextAfterWarn );
1363
1364 global $wgUseMetadataEdit;
1365 if ( $wgUseMetadataEdit )
1366 $this->showMetaData();
1367
1368 $this->showStandardInputs();
1369
1370 $this->showFormAfterText();
1371
1372 $this->showTosSummary();
1373 $this->showEditTools();
1374
1375 $wgOut->addHTML( <<<HTML
1376 {$this->editFormTextAfterTools}
1377 <div class='templatesUsed'>
1378 {$formattedtemplates}
1379 </div>
1380 <div class='hiddencats'>
1381 {$formattedhiddencats}
1382 </div>
1383 HTML
1384 );
1385
1386 if ( $this->isConflict )
1387 $this->showConflict();
1388
1389 $wgOut->addHTML( $this->editFormTextBottom );
1390 $wgOut->addHTML( "</form>\n" );
1391 if ( !$wgUser->getOption( 'previewontop' ) ) {
1392 $this->displayPreviewArea( $previewOutput, false );
1393 }
1394
1395 wfProfileOut( __METHOD__ );
1396 }
1397
1398 protected function editFormHeadInit() {
1399 global $wgOut, $wgParser, $wgUser, $wgMaxArticleSize, $wgLang;
1400 if ( $this->isConflict ) {
1401 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1</div>", 'explainconflict' );
1402 $this->edittime = $this->mArticle->getTimestamp();
1403 } else {
1404 if ( $this->section != '' && !$this->isSectionEditSupported() ) {
1405 // We use $this->section to much before this and getVal('wgSection') directly in other places
1406 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1407 // Someone is welcome to try refactoring though
1408 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1409 return false;
1410 }
1411
1412 if ( $this->section != '' && $this->section != 'new' ) {
1413 $matches = array();
1414 if ( !$this->summary && !$this->preview && !$this->diff ) {
1415 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1, $matches );
1416 if ( !empty( $matches[2] ) ) {
1417 global $wgParser;
1418 $this->summary = "/* " .
1419 $wgParser->stripSectionName(trim($matches[2])) .
1420 " */ ";
1421 }
1422 }
1423 }
1424
1425 if ( $this->missingComment )
1426 $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' );
1427
1428 if ( $this->missingSummary && $this->section != 'new' )
1429 $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' );
1430
1431 if ( $this->missingSummary && $this->section == 'new' )
1432 $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' );
1433
1434 if ( $this->hookError !== '' )
1435 $wgOut->addWikiText( $this->hookError );
1436
1437 if ( !$this->checkUnicodeCompliantBrowser() )
1438 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1439
1440 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
1441 // Let sysop know that this will make private content public if saved
1442
1443 if ( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1444 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
1445 } else if ( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1446 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
1447 }
1448
1449 if ( !$this->mArticle->mRevision->isCurrent() ) {
1450 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
1451 $wgOut->addWikiMsg( 'editingold' );
1452 }
1453 }
1454 }
1455
1456 if ( wfReadOnly() ) {
1457 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1458 } elseif ( $wgUser->isAnon() && $this->formtype != 'preview' ) {
1459 $wgOut->wrapWikiMsg( '<div id="mw-anon-edit-warning">$1</div>', 'anoneditwarning' );
1460 } else {
1461 if ( $this->isCssJsSubpage ) {
1462 # Check the skin exists
1463 if ( !$this->isValidCssJsSubpage ) {
1464 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1465 }
1466 if ( $this->formtype !== 'preview' ) {
1467 if ( $this->isCssSubpage )
1468 $wgOut->addWikiMsg( 'usercssyoucanpreview' );
1469 if ( $this->isJsSubpage )
1470 $wgOut->addWikiMsg( 'userjsyoucanpreview' );
1471 }
1472 }
1473 }
1474
1475 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
1476 # Is the title semi-protected?
1477 if ( $this->mTitle->isSemiProtected() ) {
1478 $noticeMsg = 'semiprotectedpagewarning';
1479 } else {
1480 # Then it must be protected based on static groups (regular)
1481 $noticeMsg = 'protectedpagewarning';
1482 }
1483 LogEventsList::showLogExtract( $wgOut, 'protect', $this->mTitle->getPrefixedText(), '',
1484 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1485 }
1486 if ( $this->mTitle->isCascadeProtected() ) {
1487 # Is this page under cascading protection from some source pages?
1488 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1489 $notice = "<div class='mw-cascadeprotectedwarning'>$1\n";
1490 $cascadeSourcesCount = count( $cascadeSources );
1491 if ( $cascadeSourcesCount > 0 ) {
1492 # Explain, and list the titles responsible
1493 foreach( $cascadeSources as $page ) {
1494 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1495 }
1496 }
1497 $notice .= '</div>';
1498 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1499 }
1500 if ( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) ) {
1501 $wgOut->wrapWikiMsg( '<div class="mw-titleprotectedwarning">$1</div>', 'titleprotectedwarning' );
1502 }
1503
1504 if ( $this->kblength === false )
1505 $this->kblength = (int)( strlen( $this->textbox1 ) / 1024 );
1506
1507 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1508 $wgOut->addHTML( "<div class='error' id='mw-edit-longpageerror'>\n" );
1509 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgLang->formatNum( $wgMaxArticleSize ) );
1510 $wgOut->addHTML( "</div>\n" );
1511 } elseif ( $this->kblength > 29 ) {
1512 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1513 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) );
1514 $wgOut->addHTML( "</div>\n" );
1515 }
1516 }
1517
1518 /**
1519 * Standard summary input and label (wgSummary), abstracted so EditPage
1520 * subclasses may reorganize the form.
1521 * Note that you do not need to worry about the label's for=, it will be
1522 * inferred by the id given to the input. You can remove them both by
1523 * passing array( 'id' => false ) to $userInputAttrs.
1524 *
1525 * @param $summary The value of the summary input
1526 * @param $labelText The html to place inside the label
1527 * @param $userInputAttrs An array of attrs to use on the input
1528 * @param $userSpanAttrs An array of attrs to use on the span inside the label
1529 *
1530 * @return array An array in the format array( $label, $input )
1531 */
1532 function getSummaryInput($summary = "", $labelText = null, $userInputAttrs = null, $userSpanLabelAttrs = null) {
1533 $inputAttrs = array(
1534 'id' => 'wpSummary',
1535 'maxlength' => '200',
1536 'tabindex' => '1',
1537 'size' => 60,
1538 'spellcheck' => 'true',
1539 'onfocus' => "currentFocused = this;", // Make wpSummary insertable for editbuttons
1540 );
1541 if ( $userInputAttrs )
1542 $inputAttrs += $userInputAttrs;
1543 $spanLabelAttrs = array(
1544 'class' => $this->missingSummary ? 'mw-summarymissed' : 'mw-summary',
1545 'id' => "wpSummaryLabel"
1546 );
1547 if ( is_array($userSpanLabelAttrs) )
1548 $spanLabelAttrs += $userSpanLabelAttrs;
1549
1550 $label = null;
1551 if ( $labelText ) {
1552 $label = Xml::tags( 'label', $inputAttrs['id'] ? array( 'for' => $inputAttrs['id'] ) : null, $labelText );
1553 $label = Xml::tags( 'span', $spanLabelAttrs, $label );
1554 }
1555
1556 $input = Html::input( 'wpSummary', $summary, 'text', $inputAttrs );
1557
1558 return array( $label, $input );
1559 }
1560
1561 /**
1562 * @param bool $isSubjectPreview true if this is the section subject/title
1563 * up top, or false if this is the comment
1564 * summary down below the textarea
1565 * @param string $summary The text of the summary to display
1566 * @return string
1567 */
1568 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
1569 global $wgOut, $wgContLang, $wgRequest;
1570 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1571 $summaryClass = $this->missingSummary ? 'mw-summarymissed' : 'mw-summary';
1572 if ( $isSubjectPreview ) {
1573 if ( $wgRequest->getBool( 'nosummary' ) )
1574 return;
1575 } else {
1576 if ( !$this->mShowSummaryField )
1577 return;
1578 }
1579 $summary = $wgContLang->recodeForEdit( $summary );
1580 $labelText = wfMsgExt( $isSubjectPreview ? 'subject' : 'summary', 'parseinline' );
1581 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
1582 $wgOut->addHTML("{$label} {$input}");
1583 }
1584
1585 /**
1586 * @param bool $isSubjectPreview true if this is the section subject/title
1587 * up top, or false if this is the comment
1588 * summary down below the textarea
1589 * @param string $summary The text of the summary to display
1590 * @return string
1591 */
1592 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
1593 if ( !$summary || ( !$this->preview && !$this->diff ) )
1594 return "";
1595
1596 global $wgParser, $wgUser;
1597 $sk = $wgUser->getSkin();
1598
1599 if ( $isSubjectPreview )
1600 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
1601
1602 $summary = wfMsgExt( 'subject-preview', 'parseinline' ) . $sk->commentBlock( $summary, $this->mTitle, !!$isSubjectPreview );
1603 return Xml::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
1604 }
1605
1606 protected function showFormBeforeText() {
1607 global $wgOut;
1608 $section = htmlspecialchars( $this->section );
1609 $wgOut->addHTML( <<<INPUTS
1610 <input type='hidden' value="{$section}" name="wpSection" />
1611 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
1612 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
1613 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
1614
1615 INPUTS
1616 );
1617 if ( !$this->checkUnicodeCompliantBrowser() )
1618 $wgOut->addHTML(Xml::hidden( 'safemode', '1' ));
1619 }
1620
1621 protected function showFormAfterText() {
1622 global $wgOut, $wgUser;
1623 /**
1624 * To make it harder for someone to slip a user a page
1625 * which submits an edit form to the wiki without their
1626 * knowledge, a random token is associated with the login
1627 * session. If it's not passed back with the submission,
1628 * we won't save the page, or render user JavaScript and
1629 * CSS previews.
1630 *
1631 * For anon editors, who may not have a session, we just
1632 * include the constant suffix to prevent editing from
1633 * broken text-mangling proxies.
1634 */
1635 $wgOut->addHTML( "\n" . Xml::hidden( "wpEditToken", $wgUser->editToken() ) . "\n" );
1636 }
1637
1638 /**
1639 * Subpage overridable method for printing the form for page content editing
1640 * By default this simply outputs wpTextbox1
1641 * Subclasses can override this to provide a custom UI for editing;
1642 * be it a form, or simply wpTextbox1 with a modified content that will be
1643 * reverse modified when extracted from the post data.
1644 * Note that this is basically the inverse for importContentFormData
1645 *
1646 * @praram WebRequest $request
1647 */
1648 protected function showContentForm() {
1649 $this->showTextbox1();
1650 }
1651
1652 /**
1653 * Method to output wpTextbox1
1654 * The $textoverride method can be used by subclasses overriding showContentForm
1655 * to pass back to this method.
1656 *
1657 * @param array $customAttribs An array of html attributes to use in the textarea
1658 * @param string $textoverride Optional text to override $this->textarea1 with
1659 */
1660 protected function showTextbox1($customAttribs = null, $textoverride = null) {
1661 $classes = array(); // Textarea CSS
1662 if ( $this->mTitle->getNamespace() != NS_MEDIAWIKI && $this->mTitle->isProtected( 'edit' ) ) {
1663 # Is the title semi-protected?
1664 if ( $this->mTitle->isSemiProtected() ) {
1665 $classes[] = 'mw-textarea-sprotected';
1666 } else {
1667 # Then it must be protected based on static groups (regular)
1668 $classes[] = 'mw-textarea-protected';
1669 }
1670 }
1671 $attribs = array( 'tabindex' => 1 );
1672 if ( is_array($customAttribs) )
1673 $attribs += $customAttribs;
1674
1675 if ( $this->wasDeletedSinceLastEdit() )
1676 $attribs['type'] = 'hidden';
1677 if ( !empty( $classes ) ) {
1678 if ( isset($attribs['class']) )
1679 $classes[] = $attribs['class'];
1680 $attribs['class'] = implode( ' ', $classes );
1681 }
1682
1683 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1684 if ( !$this->preview && !$this->diff ) {
1685 global $wgOut;
1686 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus();' );
1687 }
1688
1689 $this->showTextbox( isset($textoverride) ? $textoverride : $this->textbox1, 'wpTextbox1', $attribs );
1690 }
1691
1692 protected function showTextbox2() {
1693 $this->showTextbox( $this->textbox2, 'wpTextbox2', array( 'tabindex' => 6 ) );
1694 }
1695
1696 protected function showTextbox( $content, $name, $customAttribs = array() ) {
1697 global $wgOut, $wgUser;
1698
1699 $wikitext = $this->safeUnicodeOutput( $content );
1700 if ( $wikitext !== '' ) {
1701 // Ensure there's a newline at the end, otherwise adding lines
1702 // is awkward.
1703 // But don't add a newline if the ext is empty, or Firefox in XHTML
1704 // mode will show an extra newline. A bit annoying.
1705 $wikitext .= "\n";
1706 }
1707
1708 $attribs = $customAttribs + array(
1709 'accesskey' => ',',
1710 'id' => $name,
1711 'cols' => $wgUser->getIntOption( 'cols' ),
1712 'rows' => $wgUser->getIntOption( 'rows' ),
1713 'onfocus' => "currentFocused = this;", // Make textareas insertable for editbuttons
1714 'style' => '' // avoid php notices when appending for editwidth preference (appending allows customAttribs['style'] to still work
1715 );
1716
1717 if ( $wgUser->getOption( 'editwidth' ) )
1718 $attribs['style'] .= 'width: 100%';
1719
1720 $wgOut->addHTML( Html::textarea( $name, $wikitext, $attribs ) );
1721 }
1722
1723 protected function showMetaData() {
1724 global $wgOut, $wgContLang, $wgUser;
1725 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $this->mMetaData ) );
1726 $ew = $wgUser->getOption( 'editwidth' ) ? ' style="width:100%"' : '';
1727 $cols = $wgUser->getIntOption( 'cols' );
1728 $metadata = wfMsgWikiHtml( 'metadata_help' ) . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1729 $wgOut->addHTML( $metadata );
1730 }
1731
1732 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1733 global $wgOut;
1734 $classes = array();
1735 if ( $isOnTop )
1736 $classes[] = 'ontop';
1737
1738 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1739
1740 if ( $this->formtype != 'preview' )
1741 $attribs['style'] = 'display: none;';
1742
1743 $wgOut->addHTML( Xml::openElement( 'div', $attribs ) );
1744
1745 if ( $this->formtype == 'preview' ) {
1746 $this->showPreview( $previewOutput );
1747 }
1748
1749 $wgOut->addHTML( '</div>' );
1750
1751 if ( $this->formtype == 'diff') {
1752 $this->showDiff();
1753 }
1754 }
1755
1756 /**
1757 * Append preview output to $wgOut.
1758 * Includes category rendering if this is a category page.
1759 *
1760 * @param string $text The HTML to be output for the preview.
1761 */
1762 protected function showPreview( $text ) {
1763 global $wgOut;
1764 if ( $this->mTitle->getNamespace() == NS_CATEGORY) {
1765 $this->mArticle->openShowCategory();
1766 }
1767 # This hook seems slightly odd here, but makes things more
1768 # consistent for extensions.
1769 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1770 $wgOut->addHTML( $text );
1771 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1772 $this->mArticle->closeShowCategory();
1773 }
1774 }
1775
1776 protected function showTosSummary() {
1777 $msg = 'editpage-tos-summary';
1778 // Give a chance for site and per-namespace customizations of
1779 // terms of service summary link that might exist separately
1780 // from the copyright notice.
1781 //
1782 // This will display between the save button and the edit tools,
1783 // so should remain short!
1784 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle, &$msg ) );
1785 $text = wfMsg( $msg );
1786 if( !wfEmptyMsg( $msg, $text ) && $text !== '-' ) {
1787 global $wgOut;
1788 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1789 $wgOut->addWikiMsgArray( $msg, array() );
1790 $wgOut->addHTML( '</div>' );
1791 }
1792 }
1793
1794 protected function showEditTools() {
1795 global $wgOut;
1796 $wgOut->addHTML( '<div class="mw-editTools">' );
1797 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1798 $wgOut->addHTML( '</div>' );
1799 }
1800
1801 protected function getCopywarn() {
1802 global $wgRightsText;
1803 if ( $wgRightsText ) {
1804 $copywarnMsg = array( 'copyrightwarning',
1805 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1806 $wgRightsText );
1807 } else {
1808 $copywarnMsg = array( 'copyrightwarning2',
1809 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1810 }
1811 // Allow for site and per-namespace customization of contribution/copyright notice.
1812 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle, &$copywarnMsg ) );
1813
1814 return "<div id=\"editpage-copywarn\">\n" . call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
1815 }
1816
1817 protected function showStandardInputs( &$tabindex = 2 ) {
1818 global $wgOut, $wgUser;
1819 $wgOut->addHTML( "<div class='editOptions'>\n" );
1820
1821 if ( $this->section != 'new' ) {
1822 $this->showSummaryInput( false, $this->summary );
1823 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary ) );
1824 }
1825
1826 $checkboxes = $this->getCheckboxes( $tabindex, $wgUser->getSkin(),
1827 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1828 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
1829 $wgOut->addHTML( "<div class='editButtons'>\n" );
1830 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
1831
1832 $cancel = $this->getCancelLink();
1833 $separator = wfMsgExt( 'pipe-separator' , 'escapenoentities' );
1834 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
1835 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1836 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1837 htmlspecialchars( wfMsg( 'newwindow' ) );
1838 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$separator}{$edithelp}</span>\n" );
1839 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
1840 }
1841
1842 protected function showConflict() {
1843 global $wgOut;
1844 $this->textbox2 = $this->textbox1;
1845 $this->textbox1 = $this->getContent();
1846 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1847 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
1848
1849 $de = new DifferenceEngine( $this->mTitle );
1850 $de->setText( $this->textbox2, $this->textbox1 );
1851 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1852
1853 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
1854 $this->showTextbox2();
1855 }
1856 }
1857
1858 protected function getLastDelete() {
1859 $dbr = wfGetDB( DB_SLAVE );
1860 $data = $dbr->selectRow(
1861 array( 'logging', 'user' ),
1862 array( 'log_type',
1863 'log_action',
1864 'log_timestamp',
1865 'log_user',
1866 'log_namespace',
1867 'log_title',
1868 'log_comment',
1869 'log_params',
1870 'log_deleted',
1871 'user_name' ),
1872 array( 'log_namespace' => $this->mTitle->getNamespace(),
1873 'log_title' => $this->mTitle->getDBkey(),
1874 'log_type' => 'delete',
1875 'log_action' => 'delete',
1876 'user_id=log_user' ),
1877 __METHOD__,
1878 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1879 );
1880 // Quick paranoid permission checks...
1881 if( is_object( $data ) ) {
1882 if( $data->log_deleted & LogPage::DELETED_USER )
1883 $data->user_name = wfMsgHtml( 'rev-deleted-user' );
1884 if( $data->log_deleted & LogPage::DELETED_COMMENT )
1885 $data->log_comment = wfMsgHtml( 'rev-deleted-comment' );
1886 }
1887 return $data;
1888 }
1889
1890 /**
1891 * Get the rendered text for previewing.
1892 * @return string
1893 */
1894 function getPreviewText() {
1895 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang, $wgMessageCache;
1896
1897 wfProfileIn( __METHOD__ );
1898
1899 if ( $this->mTriedSave && !$this->mTokenOk ) {
1900 if ( $this->mTokenOkExceptSuffix ) {
1901 $note = wfMsg( 'token_suffix_mismatch' );
1902 } else {
1903 $note = wfMsg( 'session_fail_preview' );
1904 }
1905 } else {
1906 $note = wfMsg( 'previewnote' );
1907 }
1908
1909 $parserOptions = ParserOptions::newFromUser( $wgUser );
1910 $parserOptions->setEditSection( false );
1911 $parserOptions->setIsPreview( true );
1912 $parserOptions->setIsSectionPreview( !is_null($this->section) && $this->section !== '' );
1913
1914 global $wgRawHtml;
1915 if ( $wgRawHtml && !$this->mTokenOk ) {
1916 // Could be an offsite preview attempt. This is very unsafe if
1917 // HTML is enabled, as it could be an attack.
1918 return $wgOut->parse( "<div class='previewnote'>" .
1919 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1920 }
1921
1922 # don't parse user css/js, show message about preview
1923 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1924
1925 if ( $this->isCssJsSubpage ) {
1926 if (preg_match( "/\\.css$/", $this->mTitle->getText() ) ) {
1927 $previewtext = wfMsg( 'usercsspreview' );
1928 } else if (preg_match( "/\\.js$/", $this->mTitle->getText() ) ) {
1929 $previewtext = wfMsg( 'userjspreview' );
1930 }
1931 $parserOptions->setTidy( true );
1932 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle, $parserOptions );
1933 $previewHTML = $parserOutput->mText;
1934 } elseif ( $rt = Title::newFromRedirectArray( $this->textbox1 ) ) {
1935 $previewHTML = $this->mArticle->viewRedirect( $rt, false );
1936 } else {
1937 $toparse = $this->textbox1;
1938
1939 # If we're adding a comment, we need to show the
1940 # summary as the headline
1941 if ( $this->section == "new" && $this->summary != "" ) {
1942 $toparse="== {$this->summary} ==\n\n" . $toparse;
1943 }
1944
1945 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData;
1946
1947 // Parse mediawiki messages with correct target language
1948 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1949 list( /* $unused */, $lang ) = $wgMessageCache->figureMessage( $this->mTitle->getText() );
1950 $obj = wfGetLangObj( $lang );
1951 $parserOptions->setTargetLanguage( $obj );
1952 }
1953
1954
1955 $parserOptions->setTidy( true );
1956 $parserOptions->enableLimitReport();
1957 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ),
1958 $this->mTitle, $parserOptions );
1959
1960 $previewHTML = $parserOutput->getText();
1961 $this->mParserOutput = $parserOutput;
1962 $wgOut->addParserOutputNoText( $parserOutput );
1963
1964 if ( count( $parserOutput->getWarnings() ) ) {
1965 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1966 }
1967 }
1968
1969 if( $this->isConflict ) {
1970 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1971 } else {
1972 $conflict = '<hr />';
1973 }
1974
1975 $previewhead = "<div class='previewnote'>\n" .
1976 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
1977 $wgOut->parse( $note ) . $conflict . "</div>\n";
1978
1979 wfProfileOut( __METHOD__ );
1980 return $previewhead . $previewHTML . $this->previewTextAfterContent;
1981 }
1982
1983 function getTemplates() {
1984 if ( $this->preview || $this->section != '' ) {
1985 $templates = array();
1986 if ( !isset( $this->mParserOutput ) ) return $templates;
1987 foreach( $this->mParserOutput->getTemplates() as $ns => $template) {
1988 foreach( array_keys( $template ) as $dbk ) {
1989 $templates[] = Title::makeTitle($ns, $dbk);
1990 }
1991 }
1992 return $templates;
1993 } else {
1994 return $this->mArticle->getUsedTemplates();
1995 }
1996 }
1997
1998 /**
1999 * Call the stock "user is blocked" page
2000 */
2001 function blockedPage() {
2002 global $wgOut, $wgUser;
2003 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
2004
2005 # If the user made changes, preserve them when showing the markup
2006 # (This happens when a user is blocked during edit, for instance)
2007 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
2008 if ( $first ) {
2009 $source = $this->mTitle->exists() ? $this->getContent() : false;
2010 } else {
2011 $source = $this->textbox1;
2012 }
2013
2014 # Spit out the source or the user's modified version
2015 if ( $source !== false ) {
2016 $rows = $wgUser->getIntOption( 'rows' );
2017 $cols = $wgUser->getIntOption( 'cols' );
2018 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
2019 $wgOut->addHTML( '<hr />' );
2020 $wgOut->addWikiMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() );
2021 # Why we don't use Xml::element here?
2022 # Is it because if $source is '', it returns <textarea />?
2023 $wgOut->addHTML( Xml::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml::closeElement( 'textarea' ) );
2024 }
2025 }
2026
2027 /**
2028 * Produce the stock "please login to edit pages" page
2029 */
2030 function userNotLoggedInPage() {
2031 global $wgUser, $wgOut, $wgTitle;
2032 $skin = $wgUser->getSkin();
2033
2034 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
2035 $loginLink = $skin->link(
2036 $loginTitle,
2037 wfMsgHtml( 'loginreqlink' ),
2038 array(),
2039 array( 'returnto' => $wgTitle->getPrefixedText() ),
2040 array( 'known', 'noclasses' )
2041 );
2042
2043 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
2044 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2045 $wgOut->setArticleRelated( false );
2046
2047 $wgOut->addHTML( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
2048 $wgOut->returnToMain( false, $wgTitle );
2049 }
2050
2051 /**
2052 * Creates a basic error page which informs the user that
2053 * they have attempted to edit a nonexistent section.
2054 */
2055 function noSuchSectionPage() {
2056 global $wgOut, $wgTitle;
2057
2058 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
2059 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2060 $wgOut->setArticleRelated( false );
2061
2062 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section );
2063 $wgOut->returnToMain( false, $wgTitle );
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, $wgRequest;
2620
2621 $resultDetails = false;
2622 # Allow bots to exempt some edits from bot flagging
2623 $bot = $wgUser->isAllowed( 'bot' ) && $wgRequest->getBool( 'bot', true );
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 }