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