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