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