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