getUser()->equals( $targetUser ); $available = $this->changeableGroups(); if ( $targetUser->getId() === 0 ) { return false; } if ( $available['add'] || $available['remove'] ) { // can change some rights for any user return true; } if ( ( $available['add-self'] || $available['remove-self'] ) && ( $isself || !$checkIfSelf ) ) { // can change some rights for self return true; } return false; } /** * Manage forms to be shown according to posted data. * Depending on the submit button used, call a form or a save function. * * @param string|null $par String if any subpage provided, else null * @throws UserBlockedError|PermissionsError * @suppress PhanUndeclaredMethod */ public function execute( $par ) { $user = $this->getUser(); $request = $this->getRequest(); $session = $request->getSession(); $out = $this->getOutput(); $out->addModules( [ 'mediawiki.special.userrights' ] ); $this->mTarget = $par ?? $request->getVal( 'user' ); if ( is_string( $this->mTarget ) ) { $this->mTarget = trim( $this->mTarget ); } if ( $this->mTarget !== null && User::getCanonicalName( $this->mTarget ) === $user->getName() ) { $this->isself = true; } $fetchedStatus = $this->fetchUser( $this->mTarget, true ); if ( $fetchedStatus->isOK() ) { $this->mFetchedUser = $fetchedStatus->value; if ( $this->mFetchedUser instanceof User ) { // Set the 'relevant user' in the skin, so it displays links like Contributions, // User logs, UserRights, etc. $this->getSkin()->setRelevantUser( $this->mFetchedUser ); } } // show a successbox, if the user rights was saved successfully if ( $session->get( 'specialUserrightsSaveSuccess' ) && $this->mFetchedUser !== null ) { // Remove session data for the success message $session->remove( 'specialUserrightsSaveSuccess' ); $out->addModuleStyles( 'mediawiki.notification.convertmessagebox.styles' ); $out->addHTML( Html::rawElement( 'div', [ 'class' => 'mw-notify-success successbox', 'id' => 'mw-preferences-success', 'data-mw-autohide' => 'false', ], Html::element( 'p', [], $this->msg( 'savedrights', $this->mFetchedUser->getName() )->text() ) ) ); } $this->setHeaders(); $this->outputHeader(); $out->addModuleStyles( 'mediawiki.special' ); $this->addHelpLink( 'Help:Assigning permissions' ); $this->switchForm(); if ( $request->wasPosted() && $request->getCheck( 'saveusergroups' ) && $this->mTarget !== null && $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget ) ) { /* * If the user is blocked and they only have "partial" access * (e.g. they don't have the userrights permission), then don't * allow them to change any user rights. */ if ( !MediaWikiServices::getInstance() ->getPermissionManager() ->userHasRight( $user, 'userrights' ) ) { $block = $user->getBlock(); if ( $block && $block->isSitewide() ) { throw new UserBlockedError( $block, $user, $this->getLanguage(), $request->getIP() ); } } $this->checkReadOnly(); // save settings if ( !$fetchedStatus->isOK() ) { $this->getOutput()->addWikiTextAsInterface( $fetchedStatus->getWikiText( false, false, $this->getLanguage() ) ); return; } $targetUser = $this->mFetchedUser; if ( $targetUser instanceof User ) { // UserRightsProxy doesn't have this method (T63252) $targetUser->clearInstanceCache(); // T40989 } $conflictCheck = $request->getVal( 'conflictcheck-originalgroups' ); $conflictCheck = ( $conflictCheck === '' ) ? [] : explode( ',', $conflictCheck ); $userGroups = $targetUser->getGroups(); if ( $userGroups !== $conflictCheck ) { $out->wrapWikiMsg( '$1', 'userrights-conflict' ); } else { $status = $this->saveUserGroups( $this->mTarget, $request->getVal( 'user-reason' ), $targetUser ); if ( $status->isOK() ) { // Set session data for the success message $session->set( 'specialUserrightsSaveSuccess', 1 ); $out->redirect( $this->getSuccessURL() ); return; } else { // Print an error message and redisplay the form $out->wrapWikiTextAsInterface( 'error', $status->getWikiText( false, false, $this->getLanguage() ) ); } } } // show some more forms if ( $this->mTarget !== null ) { $this->editUserGroupsForm( $this->mTarget ); } } private function getSuccessURL() { return $this->getPageTitle( $this->mTarget )->getFullURL(); } /** * Returns true if this user rights form can set and change user group expiries. * Subclasses may wish to override this to return false. * * @return bool */ public function canProcessExpiries() { return true; } /** * Converts a user group membership expiry string into a timestamp. Words like * 'existing' or 'other' should have been filtered out before calling this * function. * * @param string $expiry * @return string|null|false A string containing a valid timestamp, or null * if the expiry is infinite, or false if the timestamp is not valid */ public static function expiryToTimestamp( $expiry ) { if ( wfIsInfinity( $expiry ) ) { return null; } $unix = strtotime( $expiry ); if ( !$unix || $unix === -1 ) { return false; } // @todo FIXME: Non-qualified absolute times are not in users specified timezone // and there isn't notice about it in the ui (see ProtectionForm::getExpiry) return wfTimestamp( TS_MW, $unix ); } /** * Save user groups changes in the database. * Data comes from the editUserGroupsForm() form function * * @param string $username Username to apply changes to. * @param string $reason Reason for group change * @param User|UserRightsProxy $user Target user object. * @return Status */ protected function saveUserGroups( $username, $reason, $user ) { $allgroups = $this->getAllGroups(); $addgroup = []; $groupExpiries = []; // associative array of (group name => expiry) $removegroup = []; $existingUGMs = $user->getGroupMemberships(); // This could possibly create a highly unlikely race condition if permissions are changed between // when the form is loaded and when the form is saved. Ignoring it for the moment. foreach ( $allgroups as $group ) { // We'll tell it to remove all unchecked groups, and add all checked groups. // Later on, this gets filtered for what can actually be removed if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) { $addgroup[] = $group; if ( $this->canProcessExpiries() ) { // read the expiry information from the request $expiryDropdown = $this->getRequest()->getVal( "wpExpiry-$group" ); if ( $expiryDropdown === 'existing' ) { continue; } if ( $expiryDropdown === 'other' ) { $expiryValue = $this->getRequest()->getVal( "wpExpiry-$group-other" ); } else { $expiryValue = $expiryDropdown; } // validate the expiry $groupExpiries[$group] = self::expiryToTimestamp( $expiryValue ); if ( $groupExpiries[$group] === false ) { return Status::newFatal( 'userrights-invalid-expiry', $group ); } // not allowed to have things expiring in the past if ( $groupExpiries[$group] && $groupExpiries[$group] < wfTimestampNow() ) { return Status::newFatal( 'userrights-expiry-in-past', $group ); } // if the user can only add this group (not remove it), the expiry time // cannot be brought forward (T156784) if ( !$this->canRemove( $group ) && isset( $existingUGMs[$group] ) && ( $existingUGMs[$group]->getExpiry() ?: 'infinity' ) > ( $groupExpiries[$group] ?: 'infinity' ) ) { return Status::newFatal( 'userrights-cannot-shorten-expiry', $group ); } } } else { $removegroup[] = $group; } } $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason, [], $groupExpiries ); return Status::newGood(); } /** * Save user groups changes in the database. This function does not throw errors; * instead, it ignores groups that the performer does not have permission to set. * * @param User|UserRightsProxy $user * @param array $add Array of groups to add * @param array $remove Array of groups to remove * @param string $reason Reason for group change * @param array $tags Array of change tags to add to the log entry * @param array $groupExpiries Associative array of (group name => expiry), * containing only those groups that are to have new expiry values set * @return array Tuple of added, then removed groups */ public function doSaveUserGroups( $user, array $add, array $remove, $reason = '', array $tags = [], array $groupExpiries = [] ) { // Validate input set... $isself = $user->getName() == $this->getUser()->getName(); $groups = $user->getGroups(); $ugms = $user->getGroupMemberships(); $changeable = $this->changeableGroups(); $addable = array_merge( $changeable['add'], $isself ? $changeable['add-self'] : [] ); $removable = array_merge( $changeable['remove'], $isself ? $changeable['remove-self'] : [] ); $remove = array_unique( array_intersect( $remove, $removable, $groups ) ); $add = array_intersect( $add, $addable ); // add only groups that are not already present or that need their expiry updated, // UNLESS the user can only add this group (not remove it) and the expiry time // is being brought forward (T156784) $add = array_filter( $add, function ( $group ) use ( $groups, $groupExpiries, $removable, $ugms ) { if ( isset( $groupExpiries[$group] ) && !in_array( $group, $removable ) && isset( $ugms[$group] ) && ( $ugms[$group]->getExpiry() ?: 'infinity' ) > ( $groupExpiries[$group] ?: 'infinity' ) ) { return false; } return !in_array( $group, $groups ) || array_key_exists( $group, $groupExpiries ); } ); $this->getHookRunner()->onChangeUserGroups( $this->getUser(), $user, $add, $remove ); $oldGroups = $groups; $oldUGMs = $user->getGroupMemberships(); $newGroups = $oldGroups; // Remove groups, then add new ones/update expiries of existing ones if ( $remove ) { foreach ( $remove as $index => $group ) { if ( !$user->removeGroup( $group ) ) { unset( $remove[$index] ); } } $newGroups = array_diff( $newGroups, $remove ); } if ( $add ) { foreach ( $add as $index => $group ) { $expiry = $groupExpiries[$group] ?? null; if ( !$user->addGroup( $group, $expiry ) ) { unset( $add[$index] ); } } $newGroups = array_merge( $newGroups, $add ); } $newGroups = array_unique( $newGroups ); $newUGMs = $user->getGroupMemberships(); // Ensure that caches are cleared $user->invalidateCache(); // update groups in external authentication database $this->getHookRunner()->onUserGroupsChanged( $user, $add, $remove, $this->getUser(), $reason, $oldUGMs, $newUGMs ); wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) ); wfDebug( 'newGroups: ' . print_r( $newGroups, true ) ); wfDebug( 'oldUGMs: ' . print_r( $oldUGMs, true ) ); wfDebug( 'newUGMs: ' . print_r( $newUGMs, true ) ); // Only add a log entry if something actually changed if ( $newGroups != $oldGroups || $newUGMs != $oldUGMs ) { $this->addLogEntry( $user, $oldGroups, $newGroups, $reason, $tags, $oldUGMs, $newUGMs ); } return [ $add, $remove ]; } /** * Serialise a UserGroupMembership object for storage in the log_params section * of the logging table. Only keeps essential data, removing redundant fields. * * @param UserGroupMembership|null $ugm May be null if things get borked * @return array */ protected static function serialiseUgmForLog( $ugm ) { if ( !$ugm instanceof UserGroupMembership ) { return null; } return [ 'expiry' => $ugm->getExpiry() ]; } /** * Add a rights log entry for an action. * @param User|UserRightsProxy $user * @param array $oldGroups * @param array $newGroups * @param string $reason * @param array $tags Change tags for the log entry * @param array $oldUGMs Associative array of (group name => UserGroupMembership) * @param array $newUGMs Associative array of (group name => UserGroupMembership) */ protected function addLogEntry( $user, array $oldGroups, array $newGroups, $reason, array $tags, array $oldUGMs, array $newUGMs ) { // make sure $oldUGMs and $newUGMs are in the same order, and serialise // each UGM object to a simplified array $oldUGMs = array_map( function ( $group ) use ( $oldUGMs ) { return isset( $oldUGMs[$group] ) ? self::serialiseUgmForLog( $oldUGMs[$group] ) : null; }, $oldGroups ); $newUGMs = array_map( function ( $group ) use ( $newUGMs ) { return isset( $newUGMs[$group] ) ? self::serialiseUgmForLog( $newUGMs[$group] ) : null; }, $newGroups ); $logEntry = new ManualLogEntry( 'rights', 'rights' ); $logEntry->setPerformer( $this->getUser() ); $logEntry->setTarget( $user->getUserPage() ); $logEntry->setComment( $reason ); $logEntry->setParameters( [ '4::oldgroups' => $oldGroups, '5::newgroups' => $newGroups, 'oldmetadata' => $oldUGMs, 'newmetadata' => $newUGMs, ] ); $logid = $logEntry->insert(); if ( count( $tags ) ) { $logEntry->addTags( $tags ); } $logEntry->publish( $logid ); } /** * Edit user groups membership * @param string $username Name of the user. */ private function editUserGroupsForm( $username ) { $status = $this->fetchUser( $username, true ); if ( !$status->isOK() ) { $this->getOutput()->addWikiTextAsInterface( $status->getWikiText( false, false, $this->getLanguage() ) ); return; } /** @var User $user */ $user = $status->value; '@phan-var User $user'; $groups = $user->getGroups(); $groupMemberships = $user->getGroupMemberships(); $this->showEditUserGroupsForm( $user, $groups, $groupMemberships ); // This isn't really ideal logging behavior, but let's not hide the // interwiki logs if we're using them as is. $this->showLogFragment( $user, $this->getOutput() ); } /** * Normalize the input username, which may be local or remote, and * return a user (or proxy) object for manipulating it. * * Side effects: error output for invalid access * @param string $username * @param bool $writing * @return Status */ public function fetchUser( $username, $writing = true ) { $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username ); if ( count( $parts ) < 2 ) { $name = trim( $username ); $dbDomain = ''; } else { list( $name, $dbDomain ) = array_map( 'trim', $parts ); if ( WikiMap::isCurrentWikiId( $dbDomain ) ) { $dbDomain = ''; } else { if ( $writing && !MediaWikiServices::getInstance() ->getPermissionManager() ->userHasRight( $this->getUser(), 'userrights-interwiki' ) ) { return Status::newFatal( 'userrights-no-interwiki' ); } if ( !UserRightsProxy::validDatabase( $dbDomain ) ) { return Status::newFatal( 'userrights-nodatabase', $dbDomain ); } } } if ( $name === '' ) { return Status::newFatal( 'nouserspecified' ); } if ( $name[0] == '#' ) { // Numeric ID can be specified... // We'll do a lookup for the name internally. $id = intval( substr( $name, 1 ) ); if ( $dbDomain == '' ) { $name = User::whoIs( $id ); } else { $name = UserRightsProxy::whoIs( $dbDomain, $id ); } if ( !$name ) { return Status::newFatal( 'noname' ); } } else { $name = User::getCanonicalName( $name ); if ( $name === false ) { // invalid name return Status::newFatal( 'nosuchusershort', $username ); } } if ( $dbDomain == '' ) { $user = User::newFromName( $name ); } else { $user = UserRightsProxy::newFromName( $dbDomain, $name ); } if ( !$user || $user->isAnon() ) { return Status::newFatal( 'nosuchusershort', $username ); } if ( $user instanceof User && $user->isHidden() && !MediaWikiServices::getInstance() ->getPermissionManager() ->userHasRight( $this->getUser(), 'hideuser' ) ) { // Cannot see hidden users, pretend they don't exist return Status::newFatal( 'nosuchusershort', $username ); } return Status::newGood( $user ); } /** * @since 1.15 * * @param array $ids * * @return string */ public function makeGroupNameList( $ids ) { if ( empty( $ids ) ) { return $this->msg( 'rightsnone' )->inContentLanguage()->text(); } else { return implode( ', ', $ids ); } } /** * Output a form to allow searching for a user */ protected function switchForm() { $this->getOutput()->addModules( 'mediawiki.userSuggest' ); $this->getOutput()->addHTML( Html::openElement( 'form', [ 'method' => 'get', 'action' => wfScript(), 'name' => 'uluser', 'id' => 'mw-userrights-form1' ] ) . Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) . Xml::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) . Xml::inputLabel( $this->msg( 'userrights-user-editname' )->text(), 'user', 'username', 30, str_replace( '_', ' ', $this->mTarget ), [ 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest ] + ( // Set autofocus on blank input and error input $this->mFetchedUser === null ? [ 'autofocus' => '' ] : [] ) ) . ' ' . Xml::submitButton( $this->msg( 'editusergroup' )->text() ) . Html::closeElement( 'fieldset' ) . Html::closeElement( 'form' ) . "\n" ); } /** * Show the form to edit group memberships. * * @param User|UserRightsProxy $user User or UserRightsProxy you're editing * @param array $groups Array of groups the user is in. Not used by this implementation * anymore, but kept for backward compatibility with subclasses * @param array $groupMemberships Associative array of (group name => UserGroupMembership * object) containing the groups the user is in */ protected function showEditUserGroupsForm( $user, $groups, $groupMemberships ) { $list = $membersList = $tempList = $tempMembersList = []; foreach ( $groupMemberships as $ugm ) { $linkG = UserGroupMembership::getLink( $ugm, $this->getContext(), 'html' ); $linkM = UserGroupMembership::getLink( $ugm, $this->getContext(), 'html', $user->getName() ); if ( $ugm->getExpiry() ) { $tempList[] = $linkG; $tempMembersList[] = $linkM; } else { $list[] = $linkG; $membersList[] = $linkM; } } $autoList = []; $autoMembersList = []; $isUserInstance = $user instanceof User; if ( $isUserInstance ) { foreach ( Autopromote::getAutopromoteGroups( $user ) as $group ) { $autoList[] = UserGroupMembership::getLink( $group, $this->getContext(), 'html' ); $autoMembersList[] = UserGroupMembership::getLink( $group, $this->getContext(), 'html', $user->getName() ); } } $language = $this->getLanguage(); $displayedList = $this->msg( 'userrights-groupsmember-type' ) ->rawParams( $language->commaList( array_merge( $tempList, $list ) ), $language->commaList( array_merge( $tempMembersList, $membersList ) ) )->escaped(); $displayedAutolist = $this->msg( 'userrights-groupsmember-type' ) ->rawParams( $language->commaList( $autoList ), $language->commaList( $autoMembersList ) )->escaped(); $grouplist = ''; $count = count( $list ) + count( $tempList ); if ( $count > 0 ) { $grouplist = $this->msg( 'userrights-groupsmember' ) ->numParams( $count ) ->params( $user->getName() ) ->parse(); $grouplist = '
' . $grouplist . ' ' . $displayedList . "
\n"; } $count = count( $autoList ); if ( $count > 0 ) { $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' ) ->numParams( $count ) ->params( $user->getName() ) ->parse(); $grouplist .= '' . $autogrouplistintro . ' ' . $displayedAutolist . "
\n"; } $systemUser = $isUserInstance && $user->isSystemUser(); if ( $systemUser ) { $systemusernote = $this->msg( 'userrights-systemuser' ) ->params( $user->getName() ) ->parse(); $grouplist .= '' . $systemusernote . "
\n"; } // Only add an email link if the user is not a system user $flags = $systemUser ? 0 : Linker::TOOL_LINKS_EMAIL; $userToolLinks = Linker::userToolLinks( $user->getId(), $user->getName(), false, /* default for redContribsWhenNoEdits */ $flags ); list( $groupCheckboxes, $canChangeAny ) = $this->groupCheckboxes( $groupMemberships, $user ); $this->getOutput()->addHTML( Xml::openElement( 'form', [ 'method' => 'post', 'action' => $this->getPageTitle()->getLocalURL(), 'name' => 'editGroup', 'id' => 'mw-userrights-form2' ] ) . Html::hidden( 'user', $this->mTarget ) . Html::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget ) ) . Html::hidden( 'conflictcheck-originalgroups', implode( ',', $user->getGroups() ) ) . // Conflict detection Xml::openElement( 'fieldset' ) . Xml::element( 'legend', [], $this->msg( $canChangeAny ? 'userrights-editusergroup' : 'userrights-viewusergroup', $user->getName() )->text() ) . $this->msg( $canChangeAny ? 'editinguser' : 'viewinguserrights' )->params( wfEscapeWikiText( $user->getName() ) ) ->rawParams( $userToolLinks )->parse() ); if ( $canChangeAny ) { $this->getOutput()->addHTML( $this->msg( 'userrights-groups-help', $user->getName() )->parse() . $grouplist . $groupCheckboxes . Xml::openElement( 'table', [ 'id' => 'mw-userrights-table-outer' ] ) . "