* (bug 6579) Fixed protecting images from uploading only
[lhc/web/wiklou.git] / includes / ProtectionForm.php
1 <?php
2 /**
3 * Copyright (C) 2005 Brion Vibber <brion@pobox.com>
4 * http://www.mediawiki.org/
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 */
21
22 /**
23 * Handles the page protection UI and backend
24 */
25 class ProtectionForm {
26 /** A map of action to restriction level, from request or default */
27 var $mRestrictions = array();
28
29 /** The custom/additional protection reason */
30 var $mReason = '';
31
32 /** The reason selected from the list, blank for other/additional */
33 var $mReasonSelection = '';
34
35 /** True if the restrictions are cascading, from request or existing protection */
36 var $mCascade = false;
37
38 /** Map of action to "other" expiry time. Used in preference to mExpirySelection. */
39 var $mExpiry = array();
40
41 /**
42 * Map of action to value selected in expiry drop-down list.
43 * Will be set to 'othertime' whenever mExpiry is set.
44 */
45 var $mExpirySelection = array();
46
47 /** Permissions errors for the protect action */
48 var $mPermErrors = array();
49
50 /** Types (i.e. actions) for which levels can be selected */
51 var $mApplicableTypes = array();
52
53 /** Map of action to the expiry time of the existing protection */
54 var $mExistingExpiry = array();
55
56 function __construct( Article $article ) {
57 global $wgRequest, $wgUser;
58 global $wgRestrictionTypes, $wgRestrictionLevels;
59 $this->mArticle = $article;
60 $this->mTitle = $article->mTitle;
61 $this->mApplicableTypes = $this->mTitle->exists() ? $wgRestrictionTypes : array('create');
62
63 $this->mCascade = $this->mTitle->areRestrictionsCascading();
64
65 // The form will be available in read-only to show levels.
66 $this->mPermErrors = $this->mTitle->getUserPermissionsErrors('protect',$wgUser);
67 $this->disabled = wfReadOnly() || $this->mPermErrors != array();
68 $this->disabledAttrib = $this->disabled
69 ? array( 'disabled' => 'disabled' )
70 : array();
71
72 $this->mReason = $wgRequest->getText( 'mwProtect-reason' );
73 $this->mReasonSelection = $wgRequest->getText( 'wpProtectReasonSelection' );
74 $this->mCascade = $wgRequest->getBool( 'mwProtect-cascade', $this->mCascade );
75
76 foreach( $this->mApplicableTypes as $action ) {
77 // Fixme: this form currently requires individual selections,
78 // but the db allows multiples separated by commas.
79 $this->mRestrictions[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
80
81 if ( !$this->mRestrictions[$action] ) {
82 // No existing expiry
83 $existingExpiry = '';
84 } else {
85 $existingExpiry = $this->mTitle->getRestrictionExpiry( $action );
86 }
87 $this->mExistingExpiry[$action] = $existingExpiry;
88
89 $requestExpiry = $wgRequest->getText( "mwProtect-expiry-$action" );
90 $requestExpirySelection = $wgRequest->getVal( "wpProtectExpirySelection-$action" );
91
92 if ( $requestExpiry ) {
93 // Custom expiry takes precedence
94 $this->mExpiry[$action] = $requestExpiry;
95 $this->mExpirySelection[$action] = 'othertime';
96 } elseif ( $requestExpirySelection ) {
97 // Expiry selected from list
98 $this->mExpiry[$action] = '';
99 $this->mExpirySelection[$action] = $requestExpirySelection;
100 } elseif ( $existingExpiry == 'infinity' ) {
101 // Existing expiry is infinite, use "infinite" in drop-down
102 $this->mExpiry[$action] = '';
103 $this->mExpirySelection[$action] = 'infinite';
104 } elseif ( $existingExpiry ) {
105 // Use existing expiry in its own list item
106 $this->mExpiry[$action] = '';
107 $this->mExpirySelection[$action] = $existingExpiry;
108 } else {
109 // Final default: infinite
110 $this->mExpiry[$action] = '';
111 $this->mExpirySelection[$action] = 'infinite';
112 }
113
114 $val = $wgRequest->getVal( "mwProtect-level-$action" );
115 if( isset( $val ) && in_array( $val, $wgRestrictionLevels ) ) {
116 // Prevent users from setting levels that they cannot later unset
117 if( $val == 'sysop' ) {
118 // Special case, rewrite sysop to either protect and editprotected
119 if( !$wgUser->isAllowed('protect') && !$wgUser->isAllowed('editprotected') )
120 continue;
121 } else {
122 if( !$wgUser->isAllowed($val) )
123 continue;
124 }
125 $this->mRestrictions[$action] = $val;
126 }
127 }
128 }
129
130 /**
131 * Get the expiry time for a given action, by combining the relevant inputs.
132 * Returns a 14-char timestamp or "infinity", or false if the input was invalid
133 */
134 function getExpiry( $action ) {
135 if ( $this->mExpirySelection[$action] == 'existing' ) {
136 return $this->mExistingExpiry[$action];
137 } elseif ( $this->mExpirySelection[$action] == 'othertime' ) {
138 $value = $this->mExpiry[$action];
139 } else {
140 $value = $this->mExpirySelection[$action];
141 }
142 if ( $value == 'infinite' || $value == 'indefinite' || $value == 'infinity' ) {
143 $time = Block::infinity();
144 } else {
145 $unix = strtotime( $value );
146
147 if ( !$unix || $unix === -1 ) {
148 return false;
149 }
150
151 // Fixme: non-qualified absolute times are not in users specified timezone
152 // and there isn't notice about it in the ui
153 $time = wfTimestamp( TS_MW, $unix );
154 }
155 return $time;
156 }
157
158 function execute() {
159 global $wgRequest, $wgOut;
160 if( $wgRequest->wasPosted() ) {
161 if( $this->save() ) {
162 $q = $this->mArticle->isRedirect() ? 'redirect=no' : '';
163 $wgOut->redirect( $this->mTitle->getFullUrl( $q ) );
164 }
165 } else {
166 $this->show();
167 }
168 }
169
170 function show( $err = null ) {
171 global $wgOut, $wgUser;
172
173 $wgOut->setRobotPolicy( 'noindex,nofollow' );
174
175 if( is_null( $this->mTitle ) ||
176 $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
177 $wgOut->showFatalError( wfMsg( 'badarticleerror' ) );
178 return;
179 }
180
181 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
182
183 if ( "" != $err ) {
184 $wgOut->setSubtitle( wfMsgHtml( 'formerror' ) );
185 $wgOut->addHTML( "<p class='error'>{$err}</p>\n" );
186 }
187
188 if ( $cascadeSources && count($cascadeSources) > 0 ) {
189 $titles = '';
190
191 foreach ( $cascadeSources as $title ) {
192 $titles .= '* [[:' . $title->getPrefixedText() . "]]\n";
193 }
194
195 $wgOut->wrapWikiMsg( "<div id=\"mw-protect-cascadeon\">\n$1\n" . $titles . "</div>", array( 'protect-cascadeon', count($cascadeSources) ) );
196 }
197
198 $sk = $wgUser->getSkin();
199 $titleLink = $sk->link( $this->mTitle );
200 $wgOut->setPageTitle( wfMsg( 'protect-title', $this->mTitle->getPrefixedText() ) );
201 $wgOut->setSubtitle( wfMsg( 'protect-backlink', $titleLink ) );
202
203 # Show an appropriate message if the user isn't allowed or able to change
204 # the protection settings at this time
205 if( $this->disabled ) {
206 if( wfReadOnly() ) {
207 $wgOut->readOnlyPage();
208 } elseif( $this->mPermErrors ) {
209 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $this->mPermErrors ) );
210 }
211 } else {
212 $wgOut->addWikiMsg( 'protect-text', $this->mTitle->getPrefixedText() );
213 }
214
215 $wgOut->addHTML( $this->buildForm() );
216
217 $this->showLogExtract( $wgOut );
218 }
219
220 function save() {
221 global $wgRequest, $wgUser;
222 # Permission check!
223 if ( $this->disabled ) {
224 $this->show();
225 return false;
226 }
227
228 $token = $wgRequest->getVal( 'wpEditToken' );
229 if ( !$wgUser->matchEditToken( $token ) ) {
230 $this->show( wfMsg( 'sessionfailure' ) );
231 return false;
232 }
233
234 # Create reason string. Use list and/or custom string.
235 $reasonstr = $this->mReasonSelection;
236 if ( $reasonstr != 'other' && $this->mReason != '' ) {
237 // Entry from drop down menu + additional comment
238 $reasonstr .= wfMsgForContent( 'colon-separator' ) . $this->mReason;
239 } elseif ( $reasonstr == 'other' ) {
240 $reasonstr = $this->mReason;
241 }
242 $expiry = array();
243 foreach( $this->mApplicableTypes as $action ) {
244 $expiry[$action] = $this->getExpiry( $action );
245 if( empty($this->mRestrictions[$action]) )
246 continue; // unprotected
247 if ( !$expiry[$action] ) {
248 $this->show( wfMsg( 'protect_expiry_invalid' ) );
249 return false;
250 }
251 if ( $expiry[$action] < wfTimestampNow() ) {
252 $this->show( wfMsg( 'protect_expiry_old' ) );
253 return false;
254 }
255 }
256
257 # They shouldn't be able to do this anyway, but just to make sure, ensure that cascading restrictions aren't being applied
258 # to a semi-protected page.
259 global $wgGroupPermissions;
260
261 $edit_restriction = isset( $this->mRestrictions['edit'] ) ? $this->mRestrictions['edit'] : '';
262 $this->mCascade = $wgRequest->getBool( 'mwProtect-cascade' );
263 if ($this->mCascade && ($edit_restriction != 'protect') &&
264 !(isset($wgGroupPermissions[$edit_restriction]['protect']) && $wgGroupPermissions[$edit_restriction]['protect'] ) )
265 $this->mCascade = false;
266
267 if ($this->mTitle->exists()) {
268 $ok = $this->mArticle->updateRestrictions( $this->mRestrictions, $reasonstr, $this->mCascade, $expiry );
269 } else {
270 $ok = $this->mTitle->updateTitleProtection( $this->mRestrictions['create'], $reasonstr, $expiry['create'] );
271 }
272
273 if( !$ok ) {
274 throw new FatalError( "Unknown error at restriction save time." );
275 }
276
277 $errorMsg = '';
278 # Give extensions a change to handle added form items
279 if( !wfRunHooks( 'ProtectionForm::save', array($this->mArticle,&$errorMsg) ) ) {
280 throw new FatalError( "Unknown hook error at restriction save time." );
281 }
282 if( $errorMsg != '' ) {
283 $this->show( $errorMsg );
284 return false;
285 }
286
287 if( $wgRequest->getCheck( 'mwProtectWatch' ) ) {
288 $this->mArticle->doWatch();
289 } elseif( $this->mTitle->userIsWatching() ) {
290 $this->mArticle->doUnwatch();
291 }
292 return $ok;
293 }
294
295 /**
296 * Build the input form
297 *
298 * @return $out string HTML form
299 */
300 function buildForm() {
301 global $wgUser, $wgLang;
302
303 $mProtectreasonother = Xml::label( wfMsg( 'protectcomment' ), 'wpProtectReasonSelection' );
304 $mProtectreason = Xml::label( wfMsg( 'protect-otherreason' ), 'mwProtect-reason' );
305
306 $out = '';
307 if( !$this->disabled ) {
308 $out .= $this->buildScript();
309 $out .= Xml::openElement( 'form', array( 'method' => 'post',
310 'action' => $this->mTitle->getLocalUrl( 'action=protect' ),
311 'id' => 'mw-Protect-Form', 'onsubmit' => 'ProtectionForm.enableUnchainedInputs(true)' ) );
312 $out .= Xml::hidden( 'wpEditToken',$wgUser->editToken() );
313 }
314
315 $out .= Xml::openElement( 'fieldset' ) .
316 Xml::element( 'legend', null, wfMsg( 'protect-legend' ) ) .
317 Xml::openElement( 'table', array( 'id' => 'mwProtectSet' ) ) .
318 Xml::openElement( 'tbody' );
319
320 foreach( $this->mRestrictions as $action => $selected ) {
321 // Special case: apply upload protection only on images
322 if ( $action == 'upload' && $this->mTitle->getNamespace() != NS_FILE )
323 continue;
324
325 /* Not all languages have V_x <-> N_x relation */
326 $msg = wfMsg( 'restriction-' . $action );
327 if( wfEmptyMsg( 'restriction-' . $action, $msg ) ) {
328 $msg = $action;
329 }
330 $out .= "<tr><td>".
331 Xml::openElement( 'fieldset' ) .
332 Xml::element( 'legend', null, $msg ) .
333 Xml::openElement( 'table', array( 'id' => "mw-protect-table-$action" ) ) .
334 "<tr><td>" . $this->buildSelector( $action, $selected ) . "</td></tr><tr><td>";
335
336 $reasonDropDown = Xml::listDropDown( 'wpProtectReasonSelection',
337 wfMsgForContent( 'protect-dropdown' ),
338 wfMsgForContent( 'protect-otherreason-op' ),
339 $this->mReasonSelection,
340 'mwProtect-reason', 4 );
341 $scExpiryOptions = wfMsgForContent( 'protect-expiry-options' );
342
343 $showProtectOptions = ($scExpiryOptions !== '-' && !$this->disabled);
344
345 $mProtectexpiry = Xml::label( wfMsg( 'protectexpiry' ), "mwProtectExpirySelection-$action" );
346 $mProtectother = Xml::label( wfMsg( 'protect-othertime' ), "mwProtect-$action-expires" );
347
348 $expiryFormOptions = '';
349 if ( $this->mExistingExpiry[$action] && $this->mExistingExpiry[$action] != 'infinity' ) {
350 $timestamp = $wgLang->timeanddate( $this->mExistingExpiry[$action] );
351 $d = $wgLang->date( $this->mExistingExpiry[$action] );
352 $t = $wgLang->time( $this->mExistingExpiry[$action] );
353 $expiryFormOptions .=
354 Xml::option(
355 wfMsg( 'protect-existing-expiry', $timestamp, $d, $t ),
356 'existing',
357 $this->mExpirySelection[$action] == 'existing'
358 ) . "\n";
359 }
360
361 $expiryFormOptions .= Xml::option( wfMsg( 'protect-othertime-op' ), "othertime" ) . "\n";
362 foreach( explode(',', $scExpiryOptions) as $option ) {
363 if ( strpos($option, ":") === false ) {
364 $show = $value = $option;
365 } else {
366 list($show, $value) = explode(":", $option);
367 }
368 $show = htmlspecialchars($show);
369 $value = htmlspecialchars($value);
370 $expiryFormOptions .= Xml::option( $show, $value, $this->mExpirySelection[$action] === $value ) . "\n";
371 }
372 # Add expiry dropdown
373 if( $showProtectOptions && !$this->disabled ) {
374 $out .= "
375 <table><tr>
376 <td class='mw-label'>
377 {$mProtectexpiry}
378 </td>
379 <td class='mw-input'>" .
380 Xml::tags( 'select',
381 array(
382 'id' => "mwProtectExpirySelection-$action",
383 'name' => "wpProtectExpirySelection-$action",
384 'onchange' => "ProtectionForm.updateExpiryList(this)",
385 'tabindex' => '2' ) + $this->disabledAttrib,
386 $expiryFormOptions ) .
387 "</td>
388 </tr></table>";
389 }
390 # Add custom expiry field
391 $attribs = array( 'id' => "mwProtect-$action-expires",
392 'onkeyup' => 'ProtectionForm.updateExpiry(this)',
393 'onchange' => 'ProtectionForm.updateExpiry(this)' ) + $this->disabledAttrib;
394 $out .= "<table><tr>
395 <td class='mw-label'>" .
396 $mProtectother .
397 '</td>
398 <td class="mw-input">' .
399 Xml::input( "mwProtect-expiry-$action", 50, $this->mExpiry[$action], $attribs ) .
400 '</td>
401 </tr></table>';
402 $out .= "</td></tr>" .
403 Xml::closeElement( 'table' ) .
404 Xml::closeElement( 'fieldset' ) .
405 "</td></tr>";
406 }
407 # Give extensions a chance to add items to the form
408 wfRunHooks( 'ProtectionForm::buildForm', array($this->mArticle,&$out) );
409
410 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
411
412 // JavaScript will add another row with a value-chaining checkbox
413 if( $this->mTitle->exists() ) {
414 $out .= Xml::openElement( 'table', array( 'id' => 'mw-protect-table2' ) ) .
415 Xml::openElement( 'tbody' );
416 $out .= '<tr>
417 <td></td>
418 <td class="mw-input">' .
419 Xml::checkLabel( wfMsg( 'protect-cascade' ), 'mwProtect-cascade', 'mwProtect-cascade',
420 $this->mCascade, $this->disabledAttrib ) .
421 "</td>
422 </tr>\n";
423 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
424 }
425
426 # Add manual and custom reason field/selects as well as submit
427 if( !$this->disabled ) {
428 $out .= Xml::openElement( 'table', array( 'id' => 'mw-protect-table3' ) ) .
429 Xml::openElement( 'tbody' );
430 $out .= "
431 <tr>
432 <td class='mw-label'>
433 {$mProtectreasonother}
434 </td>
435 <td class='mw-input'>
436 {$reasonDropDown}
437 </td>
438 </tr>
439 <tr>
440 <td class='mw-label'>
441 {$mProtectreason}
442 </td>
443 <td class='mw-input'>" .
444 Xml::input( 'mwProtect-reason', 60, $this->mReason, array( 'type' => 'text',
445 'id' => 'mwProtect-reason', 'maxlength' => 255 ) ) .
446 "</td>
447 </tr>
448 <tr>
449 <td></td>
450 <td class='mw-input'>" .
451 Xml::checkLabel( wfMsg( 'watchthis' ),
452 'mwProtectWatch', 'mwProtectWatch',
453 $this->mTitle->userIsWatching() || $wgUser->getOption( 'watchdefault' ) ) .
454 "</td>
455 </tr>
456 <tr>
457 <td></td>
458 <td class='mw-submit'>" .
459 Xml::submitButton( wfMsg( 'confirm' ), array( 'id' => 'mw-Protect-submit' ) ) .
460 "</td>
461 </tr>\n";
462 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
463 }
464 $out .= Xml::closeElement( 'fieldset' );
465
466 if ( $wgUser->isAllowed( 'editinterface' ) ) {
467 $title = Title::makeTitle( NS_MEDIAWIKI, 'Protect-dropdown' );
468 $link = $wgUser->getSkin()->link(
469 $title,
470 wfMsgHtml( 'protect-edit-reasonlist' ),
471 array(),
472 array( 'action' => 'edit' )
473 );
474 $out .= '<p class="mw-protect-editreasons">' . $link . '</p>';
475 }
476
477 if ( !$this->disabled ) {
478 $out .= Xml::closeElement( 'form' ) .
479 $this->buildCleanupScript();
480 }
481
482 return $out;
483 }
484
485 function buildSelector( $action, $selected ) {
486 global $wgRestrictionLevels, $wgUser;
487
488 $levels = array();
489 foreach( $wgRestrictionLevels as $key ) {
490 //don't let them choose levels above their own (aka so they can still unprotect and edit the page). but only when the form isn't disabled
491 if( $key == 'sysop' ) {
492 //special case, rewrite sysop to protect and editprotected
493 if( !$wgUser->isAllowed('protect') && !$wgUser->isAllowed('editprotected') && !$this->disabled )
494 continue;
495 } else {
496 if( !$wgUser->isAllowed($key) && !$this->disabled )
497 continue;
498 }
499 $levels[] = $key;
500 }
501
502 $id = 'mwProtect-level-' . $action;
503 $attribs = array(
504 'id' => $id,
505 'name' => $id,
506 'size' => count( $levels ),
507 'onchange' => 'ProtectionForm.updateLevels(this)',
508 ) + $this->disabledAttrib;
509
510 $out = Xml::openElement( 'select', $attribs );
511 foreach( $levels as $key ) {
512 $out .= Xml::option( $this->getOptionLabel( $key ), $key, $key == $selected );
513 }
514 $out .= Xml::closeElement( 'select' );
515 return $out;
516 }
517
518 /**
519 * Prepare the label for a protection selector option
520 *
521 * @param string $permission Permission required
522 * @return string
523 */
524 private function getOptionLabel( $permission ) {
525 if( $permission == '' ) {
526 return wfMsg( 'protect-default' );
527 } else {
528 $key = "protect-level-{$permission}";
529 $msg = wfMsg( $key );
530 if( wfEmptyMsg( $key, $msg ) )
531 $msg = wfMsg( 'protect-fallback', $permission );
532 return $msg;
533 }
534 }
535
536 function buildScript() {
537 global $wgStylePath, $wgStyleVersion;
538 return Xml::tags( 'script', array(
539 'type' => 'text/javascript',
540 'src' => $wgStylePath . "/common/protect.js?$wgStyleVersion.1" ), '' );
541 }
542
543 function buildCleanupScript() {
544 global $wgRestrictionLevels, $wgGroupPermissions;
545 $script = 'var wgCascadeableLevels=';
546 $CascadeableLevels = array();
547 foreach( $wgRestrictionLevels as $key ) {
548 if ( (isset($wgGroupPermissions[$key]['protect']) && $wgGroupPermissions[$key]['protect']) || $key == 'protect' ) {
549 $CascadeableLevels[] = "'" . Xml::escapeJsString( $key ) . "'";
550 }
551 }
552 $script .= "[" . implode(',',$CascadeableLevels) . "];\n";
553 $options = (object)array(
554 'tableId' => 'mwProtectSet',
555 'labelText' => wfMsg( 'protect-unchain-permissions' ),
556 'numTypes' => count($this->mApplicableTypes),
557 'existingMatch' => 1 == count( array_unique( $this->mExistingExpiry ) ),
558 );
559 $encOptions = Xml::encodeJsVar( $options );
560
561 $script .= "ProtectionForm.init($encOptions)";
562 return Xml::tags( 'script', array( 'type' => 'text/javascript' ), $script );
563 }
564
565 /**
566 * @param OutputPage $out
567 * @access private
568 */
569 function showLogExtract( &$out ) {
570 # Show relevant lines from the protection log:
571 $out->addHTML( Xml::element( 'h2', null, LogPage::logName( 'protect' ) ) );
572 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle->getPrefixedText() );
573 # Let extensions add other relevant log extracts
574 wfRunHooks( 'ProtectionForm::showLogExtract', array($this->mArticle,$out) );
575 }
576 }