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