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